Understanding Cookies, Sessions, and JWT: A Complete Guide to Web Authentication

This article explains how cookies and sessions compensate for HTTP's stateless nature, details their creation, types, and limitations, compares them with JSON Web Tokens, and provides guidance on choosing the appropriate authentication method for different application scales and security requirements.

macrozheng
macrozheng
macrozheng
Understanding Cookies, Sessions, and JWT: A Complete Guide to Web Authentication

Cookie and Session

HTTP is a stateless protocol, meaning each request is independent and the server does not retain client history. Sessions and cookies are used to overcome this limitation.

What is a Session

When a client requests a server, the server creates a memory space (a Session object) stored in a ConcurrentHashMap. The session allows the server to keep track of client actions during a single conversation.

How a Session Identifies the Same Conversation

On the first request the server creates a Session and generates a sessionId, sending it to the client via the response header Set-Cookie: JSESSIONID=XXXXXX. The browser stores this cookie until the session ends. Subsequent requests include the cookie, allowing the server to retrieve the same Session.

Drawbacks of Sessions

In a load‑balanced environment, if a request is routed to a different server that does not share the original Session store, the Session may become invalid.

What is a Cookie

A cookie is a small piece of data the server sends to the web browser. The browser stores it and returns it with subsequent requests, enabling session management, personalization, and tracking.

HTTP Cookie mechanism is a supplement and improvement to the stateless nature of HTTP.

Cookies serve three main purposes: Session management – login, shopping cart, game scores, etc. Personalization – user preferences, themes, etc. Tracking – recording and analyzing user behavior.

Creating a Cookie

When the server receives a request, it can send a Set-Cookie header. The browser stores the cookie and includes it in future requests.

Set-Cookie and Cookie Headers

Example of a Set-Cookie header:

This tells the client to store the cookie. Subsequent requests automatically include the stored cookie.

There are two cookie types:

Session Cookies – no expiration date, stored in memory, deleted when the browser closes.

Persistent Cookies – have an Expires or Max-Age attribute and are saved to disk until that time.

Secure and HttpOnly Flags

A secure cookie is sent only over HTTPS. The HttpOnly flag prevents client‑side scripts from accessing the cookie, reducing the risk of XSS attacks.

Without HttpOnly, attackers can steal cookies via JavaScript.

With HttpOnly, the cookie is inaccessible to scripts, protecting session identifiers.

Cookie Scope

The Domain and Path attributes define where a cookie is sent. If Domain=mozilla.org, subdomains like developer.mozilla.org also receive the cookie. A Path=/docs matches URLs such as /docs, /docs/Web/, and /docs/Web/HTTP.

JSON Web Token vs Session Cookies

JWT (JSON Web Token) and Session Cookies both provide user authentication but differ in several ways.

Similarities

Both can authenticate users and maintain login state across page navigations, preventing repeated logins caused by HTTP's statelessness.

Differences

Signature – JWT includes a cryptographic signature; Session Cookies do not.

Statelessness – JWT stores claims on the client, making it stateless; Session Cookies rely on server‑side memory.

Scalability – JWT reduces server memory usage, improving scalability for large systems.

Cross‑Domain Support – JWT can be used across multiple domains, whereas Session Cookies are limited to a single domain or its subdomains.

What is a JWT

A JWT, defined in RFC 7519, is a compact, URL‑safe token consisting of three Base64‑URL‑encoded parts: Header, Payload, and Signature.

Header

Specifies the token type and signing algorithm, e.g.:

{
  "alg": "HS256",
  "typ": "JWT"
}

Payload

Contains claims about an entity (usually a user). Claims can be registered, public, or private.

{
  "sub": "1234567890",
  "name": "John Doe",
  "admin": true
}

Signature

Created by signing the encoded header and payload with a secret using an algorithm such as HMAC‑SHA256.

HMACSHA256(
  base64UrlEncode(header) + "." + base64UrlEncode(payload),
  secret
)

Example of a complete JWT:

eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJzdWIiOiIxMjM0NTY3ODkwIiwibmFtZSI6IkpvaG4gRG9lIiwiYWRtaW4iOnRydWV9.TJVA95OrM7E2cBab30RMHrHDcEfxjoYZgeFONFh7HgQ

Choosing Between JWT and Session Cookies

For small to medium sites that only need to store login state in a database, Session Cookies are usually sufficient. For enterprise‑level applications, especially those involving many services or cross‑domain APIs, JWT offers better scalability and cross‑origin authentication.

Postscript

The author wrote this article after encountering interview questions about disabling cookies and still using sessions. The suggested solution is URL rewriting to propagate the session ID when cookies are disabled.

If cookies are disabled, the server still sends the session ID via Set-Cookie, but the browser discards it.

To maintain a session without cookies, append the session ID to URLs (URL rewriting).

References include the JWT specification (RFC 7519) and various online tutorials.

Original Source

Signed-in readers can open the original source through BestHub's protected redirect.

Sign in to view source
Republication Notice

This article has been distilled and summarized from source material, then republished for learning and reference. If you believe it infringes your rights, please contactadmin@besthub.devand we will review it promptly.

AuthenticationJWTWeb SecuritycookiesSession
macrozheng
Written by

macrozheng

Dedicated to Java tech sharing and dissecting top open-source projects. Topics include Spring Boot, Spring Cloud, Docker, Kubernetes and more. Author’s GitHub project “mall” has 50K+ stars.

0 followers
Reader feedback

How this landed with the community

Sign in to like

Rate this article

Was this worth your time?

Sign in to rate
Discussion

0 Comments

Thoughtful readers leave field notes, pushback, and hard-won operational detail here.