Skip to Content
Mengty Learns
Security

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.

explanationintermediateTested with asvs 5.0.0 (V7, V9), rfc RFC 8725 (JWT Best Current Practices)Updated Nov 26, 2026

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

TL;DR

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.

Opaque sessions look up state on every call (instant revoke); JWTs verify signatures locally and rely on short TTLs + refresh rotation.

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=Lax cookie.
  • 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 /refresh call 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.
  • Storage rule: Never put access or refresh tokens in localStorage or sessionStorage in a browser app; use HttpOnly cookies (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'], never none), validate iss, aud, exp, and nbf, and sanitize kid so it can never trigger path traversal or arbitrary SQL/HTTP lookups.

Real-world analogy

▶ Flow: watch it work

Login → Access + Refresh → Expiry → Rotate

Overview of Login → Access + Refresh → Expiry → Rotate. 8 steps.
Overview8 steps in this flow

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

When to use
  • 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.
When to avoid
  • 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

Pros
  • 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.
Cons
  • 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