Design secure session management for a web application: cover cookie vs. JWT, revocation, and refresh rotation.
Key Talking Points
- ✓Server-side sessions: the server stores session state (e.g. in Redis); the cookie carries only an opaque, cryptographically random session ID. Revocation is instant — delete the server-side record. Preferred for sensitive apps where logout must be immediate.
- ✓JWTs (stateless tokens): the server issues a signed token carrying claims; each request is verified by signature check, no DB lookup needed — better for distributed/microservice architectures. But revocation is hard: a valid JWT is valid until it expires, even after logout. Must use short expiry (5–15 min) plus refresh tokens.
- ✓Refresh token rotation: issue a new refresh token on every use and immediately invalidate the old one. This bounds the window of a stolen refresh token and provides reuse-detection (if an old token is presented, revoke the entire family as a possible theft).
- ✓Cookie security attributes: always set `HttpOnly` (blocks XSS-based theft via `document.cookie`), `Secure` (HTTPS only), `SameSite=Lax` or `Strict` (CSRF protection), and a tight `Path`/`Domain`. Never put session tokens in `localStorage` (exposed to XSS).
- ✓For JWTs: store the access token in memory (JS variable), refresh token in an `HttpOnly` Secure cookie — this limits XSS exposure of the access token and makes refresh token theft harder.
- ✓Session expiry: set idle timeout (e.g. 15–30 min) and absolute timeout (e.g. 24 h). Re-authenticate for high-privilege actions regardless of session age.
- ✓Token binding and audience: always set `aud` claim to your service so a token issued for Service A can't be replayed against Service B.
- ✓Logout must invalidate server-side session or add the JWT ID (jti) to a revocation list (Redis blocklist with TTL = token expiry) — silent logout is a security failure.
Session management is the mechanism that keeps a user authenticated across requests. The two dominant approaches — server-side sessions (with a cookie carrying an opaque session ID) and JWTs (self-contained tokens) — have different security trade-offs, especially around revocation.