Sessions vs JWT¶
1. Decision¶
Choose Server-Side Stateful Sessions (opaque session ID stored in Redis) for web browser applications requiring immediate session revocation capability and strict protection against token theft; choose JSON Web Tokens (JWT) for stateless microservice-to-microservice authentication, mobile application backends, and cross-domain single sign-on (SSO).
2. 30-Second Answer¶
Server-Side Sessions issue an opaque random Session ID stored in a secure HTTPOnly browser cookie. The server maintains active session state in a centralized store (Redis). On every request, the server looks up the session ID in Redis (\(1\text{ms}\)). Sessions allow immediate instant revocation (deleting the key logs out the user instantly), but require a centralized session store and add database/cache lookup overhead. JSON Web Tokens (JWT) are self-contained, digitally signed JSON tokens (Header.Payload.Signature) passed in HTTP Authorization: Bearer <token> headers. Microservices validate the JWT signature using a public key locally without database lookups (Stateless). However, JWTs cannot be revoked before their expiration time without maintaining a centralized token revocation blacklist.
3. Decision Matrix¶
| Option | Best For | Avoid When | Latency | Scalability | Consistency | Operational Complexity |
|---|---|---|---|---|---|---|
| Server-Side Sessions (Redis) | Web browser SPAs, administrative portals, banking apps requiring instant remote logout | Distributed microservices across third-party domains, serverless Lambda backends | Low (<1ms Redis session lookup per HTTP request) | Scales via Redis Cluster session store | Instant Revocation (Delete key logs out user immediately) | Low to Medium |
| JSON Web Tokens (JWT) | Microservice-to-microservice auth, mobile app APIs, cross-domain Single Sign-On (SSO) | Web browser apps vulnerable to XSS theft, security requirements demanding instant revocation | Ultra-Low (Local in-memory signature verification; 0 DB lookups) | Infinite Stateless Scale (Zero central session database needed) | Eventual (Token valid until exp claims expire) |
Low |
4. Selection Rules¶
| Requirement | Best Choice | Rationale / Example |
|---|---|---|
| Instant Remote Logout / Security Breach Revocation | Server-Side Session | Admin clicks "Log out all devices"; deleting Redis keys revokes access instantly |
| Stateless Microservice Network Architecture | JSON Web Tokens (JWT) | Microservices verify JWT signature locally via JWKS without querying a session DB |
| Protect Against XSS Token Theft in Browsers | Session Cookie (HTTPOnly) |
Browser JS cannot access HTTPOnly session cookies, preventing XSS token exfiltration |
| Short-Lived Access + Long-Lived Refresh Tokens | Dual Token Pattern (JWT) | Short-lived Access JWT (15m) + Long-lived Refresh Token (30d) stored in secure storage |
| Cross-Domain Single Sign-On (SSO / OAuth2) | JSON Web Tokens (JWT) | Identity Provider (Okta/Auth0) issues signed JWT assertion to third-party apps |
5. Tradeoffs¶
- Immediate Revocation Control vs Zero DB Network Lookups
- Gain (Sessions): Deleting the Redis session key terminates access instantly across all devices.
- Lose (Sessions): Every single HTTP request incurs a network lookup hop to Redis.
- Stateless Scale vs Token Invalidation Window
- Gain (JWT): Microservices scale infinitely without touching a central session database.
- Lose (JWT): Revoking a stolen JWT before its
exptime requires maintaining a centralized revocation list. - Browser Security (
HTTPOnlyCookie) vs Storage Exposure (LocalStore) - Gain (Sessions):
HTTPOnlycookies protect against XSS token theft. - Lose (Sessions): Vulnerable to Cross-Site Request Forgery (CSRF) without anti-CSRF tokens.
- Token Size & Network Overhead
- Gain (Sessions): Opaque session ID is tiny (32 bytes).
- Lose (JWT): Base64-encoded JWT payloads add 500B–2KB of header overhead to every HTTP request.
- Decoupled Identity Provider (IdP) Architecture
- Gain (JWT): IdP signs JWT using private key; external services verify using IdP's public key (JWKS).
- Lose (JWT): Compromising the IdP private key compromises the entire microservice mesh.
6. Interview Counter Questions¶
- What are the 3 parts of a JWT (Header, Payload, Signature) and how is the signature calculated?
- Why is storing JWTs in Browser
localStorageorsessionStoragea security vulnerability? - How do you implement immediate revocation for a stolen JWT token?
- What is the Dual-Token Pattern (Access Token + Refresh Token) and how does it work?
- What is the
nonealgorithm vulnerability in JWT libraries and how do you prevent it? - How does JWKS (JSON Web Key Sets) work for public key rotation in microservices?
- What is the difference between XSS (Cross-Site Scripting) and CSRF (Cross-Site Request Forgery) regarding cookies vs JWTs?
- How does an API Gateway handle JWT validation before forwarding requests to backend microservices?
- When would you combine Sessions and JWTs in a hybrid architecture?
- Why should sensitive PII data (passwords, SSNs) never be placed in a JWT payload?
7. Gold Standard Answers¶
- Header (algorithm & type), Payload (claims:
sub,exp,iat), Signature (HMACSHA256(base64(Header) + "." + base64(Payload), secret)). Signature verifies data integrity. - JavaScript code running in the browser has full read access to
localStorage. If an attacker executes a Cross-Site Scripting (XSS) vulnerability, they can exfiltrate the raw JWT token. - Maintain a centralized Redis Token Revocation Blacklist storing revoked
jti(JWT ID) claims until theirexptime, OR keep JWT lifespan ultra-short (5-15 mins) and control revocation at the Refresh Token tier. - Access Token: Short-lived JWT (15 mins) used for stateless microservice API requests. Refresh Token: Long-lived opaque string (30 days) stored in DB/Redis used only to fetch a new Access Token.
alg: "none"allows attackers to strip the signature and bypass verification. Prevent by explicitly white-listing expected signing algorithms (e.g.,RS256only) in JWT verification libraries.- Identity Provider exposes an endpoint (
/.well-known/jwks.json) containing public RSA keys. Microservices fetch and cache JWKS keys to verify JWT signatures locally without calling the IdP on every request. - XSS steals tokens stored in JS memory/localStorage. CSRF tricks the browser into sending cookies automatically.
HTTPOnlycookies block XSS token theft;SameSite=Strict+ Anti-CSRF tokens block CSRF attacks. - Gateway intercepts incoming request, verifies JWT signature via JWKS, checks rate limits, strips un-trusted headers, and forwards validated claims to microservices via trusted headers (
X-User-Id). - Hybrid: Web BFF handles
HTTPOnlysession cookies with browser clients, translates cookie session state to a JWT, and forwards the JWT to internal stateless microservices. - The JWT Payload is only Base64-encoded, NOT encrypted! Anyone intercepting the token can decode and read all payload claims. Never place passwords, credit cards, or SSNs in a standard JWT.
8. Common Mistakes¶
- Storing sensitive JWTs in browser
localStorage, exposing them to XSS script exfiltration. - Placing sensitive credentials or un-encrypted PII inside a JWT payload (JWT payloads are Base64 readable!).
- Accepting
alg: "none"or unvalidated signing algorithms in JWT verification middleware. - Setting long-lived expiration times on Access JWTs (e.g. 30 days) without a revocation mechanism.
- Forgetting
HTTPOnly,Secure, andSameSite=Strictflags on session cookies, exposing them to XSS and CSRF attacks.
9. Keywords¶
Sessions, JWT, JSON Web Token, Header, Payload, Signature, Access Token, Refresh Token, HTTPOnly Cookie, XSS, CSRF, SameSite, JWKS, jti, Revocation Blacklist, alg none, Dual-Token Pattern.
10. Cheat Sheet¶
- Sessions (Redis): Opaque ID in
HTTPOnlycookie. Central Redis state (\(1\text{ms}\) lookup). Instant revocation. Best for Web SPAs & Banking. - JWT (Stateless): Signed JSON token in
Authorization: Bearerheader. Verified locally via public key (0 DB lookups). Best for Mobile & Microservices. - XSS Defense: Store tokens in
HTTPOnlycookies or in-memory variables. NEVER inlocalStorage! - Dual-Token Pattern: Short-lived Access JWT (15 mins) + Long-lived Refresh Token (30 days in Redis).
- JWT Payload Rule: JWT payloads are Base64 readable! NEVER store passwords or PII in a JWT.
- Security Check: Enforce algorithm whitelist (
RS256) to blockalg: "none"signature bypass exploits.