Server Sessions vs JWTs (Rotation, Storage & Pitfalls)
Trade-offs between stateful server sessions and stateless JWTs, refresh-token rotation with reuse detection, cookie storage, and JWT alg/kid pitfalls.
TL;DR
Opaque server sessions give instant revocation and simple security, while stateless JWTs avoid a central lookup per request at the cost of harder revocation. In browsers, store credentials in HttpOnly; Secure; SameSite cookies (never localStorage), keep access tokens short-lived, and rotate refresh tokens with reuse detection.
Intent
Choose between opaque server sessions and JWT access tokens, design a safe refresh-token rotation lifecycle, and avoid the classic alg: none, key-confusion, and localStorage mistakes.
Problem
Many apps issue 7-day JWTs stored in localStorage because "JWTs are modern and stateless". When a user logs out, changes their password, or gets hit by XSS, those tokens remain valid until expiry—and storing them in localStorage lets any injected script steal them silently.
Solution
Match the token model to your architecture, and follow ASVS V7/V9 and RFC 8725:
- Default to opaque server sessions for classic web apps with one backend + Redis/Postgres: generate ≥ 128 bits of CSPRNG entropy, store the session server-side, and send it in an
HttpOnly; Secure; SameSite=Laxcookie. - Use short-lived JWTs (5–15 min) + rotating refresh tokens when downstream services must verify identity without calling an auth DB on every request:
- Every
/refreshcall issues a new refresh token and marks the previous one used. - If an already-used refresh token is presented again (reuse detection), revoke the entire token family immediately—either the attacker or the legitimate user raced, so force re-login.
- Every
- Storage rule: Never put access or refresh tokens in
localStorageorsessionStoragein a browser app; useHttpOnlycookies (with CSRF protection) or keep short-lived access tokens only in memory via a BFF (Backend-for-Frontend). - JWT verification rules (RFC 8725): Pin allowed algorithms (
['EdDSA']or['RS256'], nevernone), validateiss,aud,exp, andnbf, and sanitizekidso it can never trigger path traversal or arbitrary SQL/HTTP lookups.
Real-world analogy
▶ Flow: watch it work
Login → Access + Refresh → Expiry → Rotate
Press Start or tap any step dot to trace the path.
▸All steps (8)
Code
Pin the verification algorithm and claims explicitly—never accept alg: none or unvalidated kid headers:
// UNSAFE: trusts token header algorithm, skips issuer/audience checks
import jwt from 'jsonwebtoken';
const payload = jwt.decode(token); // decodes without verifying signature!
// SAFE: pins algorithm allowlist, issuer, and audience (RFC 8725 / ASVS V9)
import { jwtVerify } from 'jose';
const { payload: verified } = await jwtVerify(token, publicKey, {
algorithms: ['EdDSA'],
issuer: 'https://auth.example.com',
audience: 'https://api.example.com',
});When to use / when to avoid
- Use opaque server sessions when you have a shared session store (Redis/DB) and need instant logout or permission revocation.
- Use short-lived JWTs + rotating refresh tokens when multiple independent services verify tokens offline via JWKS.
- Always set HttpOnly, Secure, and SameSite=Lax (or Strict) on session and refresh cookies.
- Do not store long-lived tokens or refresh tokens in localStorage or sessionStorage.
- Do not put sensitive PII or secrets inside JWT payloads—JWTs are base64url-encoded, not encrypted (unless JWE).
How to implement
Regenerate session IDs on login
Always issue a fresh session ID after authentication to prevent session fixation (ASVS V7).
Keep access tokens short-lived
Set access JWT exp to 5–15 minutes and validate iss, aud, exp, and algorithms on every API.
Implement refresh rotation + reuse detection
Store hashed refresh tokens with a familyId and used flag; revoke the family if a used token is replayed.
Pros / Cons
- Opaque sessions offer immediate revocation on logout, password change, or anomaly detection.
- JWTs with JWKS scale horizontally across microservices without per-request auth DB calls.
- Opaque sessions require a low-latency central store (such as Redis) on every authenticated request.
- JWTs cannot be revoked before expiry without adding a denylist (which reintroduces state).
Relations
Check yourself
Check Yourself
1. An attacker steals a single-use refresh token R1 and uses it after the legitimate user already rotated R1 to R2. What should the authorization server do when R1 is presented again?
2. Which JWT verification mistake allows an attacker to forge a token by changing the header to alg: HS256 and signing with the server's public RSA key?
Sources
Related Notes
Passwords, Hashing, MFA & Rate Limiting
OWASP Password Storage Cheat Sheet parameters for Argon2id/bcrypt/scrypt, NIST SP 800-63B password rules, MFA choices, and rate limiting vs account lockout.
OAuth 2.1, OIDC & PKCE
What OAuth 2.1 changes (mandatory PKCE, no implicit grant, exact redirect matching), how OIDC adds identity via ID tokens, and the full Authorization Code + PKCE flow.