← Study Notes Security


Security

Session Management

How a server remembers who you are between requests: a session ID in a cookie pointing at server-side state, or a self-contained token like a JWT. Cookie flags do the heavy lifting — HttpOnly against script theft, Secure against plain HTTP, SameSite against CSRF. Most session bugs are lifecycle bugs: fixation, missing rotation, sessions that never die.


Purpose

HTTP is stateless, so "logged in" is an illusion maintained by a credential sent with every request. Session management is the lifecycle of that credential — issue, transmission, validation, rotation, expiry, revocation — and it is where authentication actually succeeds or fails day to day: a perfect login flow is worthless if the resulting session can be stolen, fixed in advance, or lives forever.

When to Use It

The classic model — random session ID in a cookie, state server-side in Redis or the database — fits most web apps and revokes instantly. Stateless JWTs fit APIs and microservice hops where a shared session store is impractical; the price is revocation, which now needs short lifetimes plus a rotating refresh token. Many real systems mix both: a session cookie at the edge, short-lived tokens between services.

Trade-offs

Server-side sessions cost a lookup per request and a shared store; JWTs trade that for the revocation problem and a temptation to stuff claims into a token that anyone can decode (signed ≠ encrypted). The attacks are lifecycle-shaped: fixation (attacker plants a session ID before login), theft via XSS if the cookie is script-readable, and CSRF if cross-site requests carry it freely.

Implementation

Generate session IDs from a CSPRNG; set cookies HttpOnly; Secure; SameSite=Lax (or Strict where UX allows). Rotate the ID at login and any privilege change — that single line kills fixation. Enforce idle and absolute timeouts, invalidate server-side on logout and password change, and show users their active sessions. With JWTs: minutes-long access tokens, rotating refresh tokens, and validate alg, issuer and audience explicitly.