Skip to content

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

  1. Immediate Revocation Control vs Zero DB Network Lookups
  2. Gain (Sessions): Deleting the Redis session key terminates access instantly across all devices.
  3. Lose (Sessions): Every single HTTP request incurs a network lookup hop to Redis.
  4. Stateless Scale vs Token Invalidation Window
  5. Gain (JWT): Microservices scale infinitely without touching a central session database.
  6. Lose (JWT): Revoking a stolen JWT before its exp time requires maintaining a centralized revocation list.
  7. Browser Security (HTTPOnly Cookie) vs Storage Exposure (LocalStore)
  8. Gain (Sessions): HTTPOnly cookies protect against XSS token theft.
  9. Lose (Sessions): Vulnerable to Cross-Site Request Forgery (CSRF) without anti-CSRF tokens.
  10. Token Size & Network Overhead
  11. Gain (Sessions): Opaque session ID is tiny (32 bytes).
  12. Lose (JWT): Base64-encoded JWT payloads add 500B–2KB of header overhead to every HTTP request.
  13. Decoupled Identity Provider (IdP) Architecture
  14. Gain (JWT): IdP signs JWT using private key; external services verify using IdP's public key (JWKS).
  15. Lose (JWT): Compromising the IdP private key compromises the entire microservice mesh.

6. Interview Counter Questions

  1. What are the 3 parts of a JWT (Header, Payload, Signature) and how is the signature calculated?
  2. Why is storing JWTs in Browser localStorage or sessionStorage a security vulnerability?
  3. How do you implement immediate revocation for a stolen JWT token?
  4. What is the Dual-Token Pattern (Access Token + Refresh Token) and how does it work?
  5. What is the none algorithm vulnerability in JWT libraries and how do you prevent it?
  6. How does JWKS (JSON Web Key Sets) work for public key rotation in microservices?
  7. What is the difference between XSS (Cross-Site Scripting) and CSRF (Cross-Site Request Forgery) regarding cookies vs JWTs?
  8. How does an API Gateway handle JWT validation before forwarding requests to backend microservices?
  9. When would you combine Sessions and JWTs in a hybrid architecture?
  10. Why should sensitive PII data (passwords, SSNs) never be placed in a JWT payload?

7. Gold Standard Answers

  1. Header (algorithm & type), Payload (claims: sub, exp, iat), Signature (HMACSHA256(base64(Header) + "." + base64(Payload), secret)). Signature verifies data integrity.
  2. 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.
  3. Maintain a centralized Redis Token Revocation Blacklist storing revoked jti (JWT ID) claims until their exp time, OR keep JWT lifespan ultra-short (5-15 mins) and control revocation at the Refresh Token tier.
  4. 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.
  5. alg: "none" allows attackers to strip the signature and bypass verification. Prevent by explicitly white-listing expected signing algorithms (e.g., RS256 only) in JWT verification libraries.
  6. 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.
  7. XSS steals tokens stored in JS memory/localStorage. CSRF tricks the browser into sending cookies automatically. HTTPOnly cookies block XSS token theft; SameSite=Strict + Anti-CSRF tokens block CSRF attacks.
  8. 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).
  9. Hybrid: Web BFF handles HTTPOnly session cookies with browser clients, translates cookie session state to a JWT, and forwards the JWT to internal stateless microservices.
  10. 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, and SameSite=Strict flags 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 HTTPOnly cookie. Central Redis state (\(1\text{ms}\) lookup). Instant revocation. Best for Web SPAs & Banking.
  • JWT (Stateless): Signed JSON token in Authorization: Bearer header. Verified locally via public key (0 DB lookups). Best for Mobile & Microservices.
  • XSS Defense: Store tokens in HTTPOnly cookies or in-memory variables. NEVER in localStorage!
  • 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 block alg: "none" signature bypass exploits.

11. Related Decisions