Sessions and tokens
Stateful versus stateless, the revocation you give up with a JWT, access and refresh tokens, and where a browser should keep one.
HTTP forgets you between requests. Every scheme for staying logged in is a way of handing the client something it gives back, and the whole design space is one question: does the server remember what it issued, or does it verify what comes back?
That single choice decides how you log someone out, how you scale, and what happens when a token is stolen.
Sessions: the server remembers
The server stores the session — who it belongs to, when it started, anything else — and gives the client an opaque id in a cookie.
Set-Cookie: JSESSIONID=8f2c...; HttpOnly; Secure; SameSite=Lax; Path=/The id means nothing by itself. It is a key into server-side state, so every request is a lookup.
What that buys you is control. Because the server holds the record, it can change its mind: revoke a session the instant a user logs out, invalidate every session when a password changes, list a user's active devices, and end one from an admin screen. Nothing is trusted that the server is not currently willing to honour.
What it costs is state. That store has to be reachable by every instance, which in practice means Redis rather than memory — the same lesson the rate-limiting section reached from a different direction. In-memory sessions behind a load balancer mean sticky routing, and sticky routing means a deploy logs people out.
The cookie flags are not optional, and each prevents a specific attack:
HttpOnly— JavaScript cannot read it, so an XSS flaw cannot steal the session.Secure— sent over HTTPS only, so it is not disclosed on a plain-HTTP request.SameSite=LaxorStrict— not sent on cross-site requests, which is most of CSRF handled by the browser.Path, and a sensible expiry.
Tokens: the server verifies
The alternative is to give the client something that carries the facts and a signature, and check the signature on arrival. A JWT is the usual form: a header, a set of claims, and a signature over both.
Authorization: Bearer eyJhbGciOiJIUzI1NiJ9.eyJzdWIiOiIxMjMiLCJleHAiOjE3...No lookup. Any instance can verify it with a key, and so can a different service that was never told about your session store. That is the real win, and it is why tokens dominate in systems with many services and clients.
The cost is the mirror image of the benefit. The server has no record, so it cannot take it back. A token is valid until it expires, and "log out" is a client-side gesture: the client throws the token away, and a copy taken beforehand keeps working. Nothing you do on the server changes that.
The trade, stated plainly
| Session | JWT | |
|---|---|---|
| where the truth lives | server | the token |
| revocation | immediate | not possible before expiry |
| per-request cost | a store lookup | a signature check |
| works across services | needs shared store | yes |
| size on the wire | tiny id | the whole payload, every request |
| stale data | never | until the token expires |
That last row is underrated. A JWT carrying roles: ["ADMIN"] keeps asserting it after the role is removed. If your token lives an hour, a revoked administrator is an administrator for up to an hour.
So the rule is: the shorter the life, the closer a token gets to being revocable — and short-lived tokens need a way to be renewed. Which is what refresh tokens are.
Access and refresh, and why the split exists
- An access token is short-lived (5–15 minutes), sent on every request, and not stored server-side.
- A refresh token is long-lived, sent only to one endpoint, and is recorded server-side — so it can be revoked.
The split puts the revocable thing on the rare path and the fast thing on the hot path. Revoking a user means deleting the refresh token; within fifteen minutes their access token expires and cannot be renewed. That is not instant revocation, and it is close enough for most systems — as long as you choose the window deliberately rather than inheriting a default of 24 hours.
Refresh token rotation is the part that is usually missing: each refresh issues a new refresh token and invalidates the old one. If an old one is ever presented again, it was stolen — and the correct response is to revoke the whole family, because you now know one of the two parties is an attacker and cannot tell which.
Where to keep a token in a browser
This question causes more argument than it deserves, and the options are genuinely all imperfect:
localStorage— readable by any JavaScript on the page. One XSS flaw and the token is gone. Convenient; the weakest option.- A cookie with
HttpOnly— script cannot read it, so XSS cannot steal it. The browser sends it automatically, which reintroduces CSRF, whichSameSiteand a CSRF token handle. - In memory only — safest, and lost on every page refresh, so it needs a silent-refresh flow.
The honest summary: HttpOnly cookies for a browser app, Authorization headers for a mobile or service client. And note what the first row really says — if you have an XSS vulnerability, token storage is not your problem, XSS is.
What never goes in a token
A JWT is signed, not encrypted. Anyone holding it can read every claim — it is base64, not a cipher, and a paste into any decoder shows the contents.
So: no email addresses if you can avoid it, no internal ids you would rather not publish, no permissions list so detailed it maps your authorisation model, and never anything secret. And keep it small; it travels on every single request.
Two validation details that are skipped surprisingly often, both of which have caused real breaches:
- Check the algorithm. A library that honours the token's own
algheader will acceptalg: none— an unsigned token asserting anything. Pin the expected algorithm in your configuration. - Check
issandaud. A validly signed token from a different service, or intended for a different audience, is still validly signed. Signature alone does not mean for me, from someone I trust.
Under the hood: session fixation, and how a JWT's signature is actually checked
Session fixation is a different bug from session theft, and it is worth telling apart because the defence is different. Theft is the attacker obtaining a session id that already belongs to a logged-in victim. Fixation is the attacker choosing the session id before the victim logs in — tricking the victim into authenticating under an id the attacker already knows (a link containing a session parameter, a cookie planted from a subdomain, or simply a login flow that keeps the same pre-authentication session id after the password is checked) — and then using that same id themselves, now attached to an authenticated account. Nothing was stolen; the attacker supplied the key from the start and waited for it to become valuable. The defence is mechanical and specific: issue a brand-new session identifier at the moment authentication state changes, so any id that existed before login is worthless afterward. This project's own session code (lib/server/session.ts) is fixation-proof by construction rather than by a check someone has to remember: createSession() always mints a fresh 32 random bytes with randomBytes(TOKEN_BYTES) and never accepts a client-supplied id as the session's identity — there is no code path where a value the client already had becomes the authenticated session's token, so there is nothing pre-existing for an attacker to fix in the first place.
A JWT's signature check is arithmetic, not magic, and seeing the arithmetic is what makes "alg: none" make sense as a historical vulnerability rather than a trivia fact. For the common HMAC case (HS256), the token's signature is HMAC-SHA256(secret, base64url(header) + "." + base64url(payload)) — a keyed hash over the exact bytes of the first two segments. Verifying means the receiver recomputes that same HMAC, over the header and payload it actually received, using the secret it already holds (never transmitted, never part of the token), and compares the result to the signature segment. Because an HMAC output changes unpredictably with any change to its input, an attacker who edits the payload (to change a role or a sub) cannot produce a matching signature without the secret — the mismatch is what verification rejects. For asymmetric algorithms (RS256, ES256) the shape is the same with different keys: the issuer signs with a private key, and anyone holding only the public key can verify but never forge, which is why multiple independent services can each verify tokens from one issuer without ever holding a secret that could mint new ones.
alg: none was a real, exploited flaw in several early JWT libraries: the JOSE header itself declares which algorithm was used, and a naive verifier read alg from the untrusted token it was given and dispatched to whichever check that name asked for — including "none", a value the spec permits to mean "unsecured, no signature at all." An attacker could take a validly issued token, change its header to alg: none, edit whatever claims they liked, and supply an empty third segment; a library that honoured the token's own claim about how to verify itself would accept it, full stop. The fix this lesson already states — pin the accepted algorithm in your own configuration — is exactly what closes that hole: the verifier decides how a token must have been signed before it looks at the token, so the token's own alg header is read for information only, never as an instruction.
The cookie flags operate at the level of what the browser itself will and will not do with a stored cookie, not as a suggestion to the server. HttpOnly removes the cookie from document.cookie and every other JavaScript-visible API — the browser still attaches it to outgoing requests, but no script running on the page, including an attacker's injected one, can read its value. Secure is enforced by the browser refusing to put the cookie on the wire for any request that is not HTTPS, regardless of what the server would have accepted. SameSite governs whether the browser attaches the cookie to a request whose top-level initiating site differs from the cookie's own site: Strict withholds it from every cross-site request, including a top-level navigation (clicking a link from another site to yours, on first load, would not carry it); Lax — the common default — still attaches it to a cross-site top-level GET navigation but withholds it from cross-site POSTs, image loads, iframes and fetches. That asymmetry is exactly why SameSite=Lax stops "most of CSRF" rather than all of it, as this lesson already says: a state-changing action wired to a plain GET is still reachable cross-site.
Try it yourself
Trace what changing one byte of a signed payload does to verification
This mirrors, in miniature, what an HMAC-based JWT check does: derive a "signature" from the header and payload together, then verify by recomputing it from whatever was received and comparing.
String secret = "server-only-secret";
String header = "{\"alg\":\"HS256\"}";
String payload = "{\"sub\":\"123\",\"role\":\"user\"}";
String signature = String.valueOf((header + "." + payload + "." + secret).hashCode());
// the token as it would travel: header.payload.signature
String originalPayload = payload;
String tamperedPayload = "{\"sub\":\"123\",\"role\":\"admin\"}"; // one field changed, no new valid signature
boolean originalVerifies = String.valueOf((header + "." + originalPayload + "." + secret).hashCode()).equals(signature);
boolean tamperedVerifies = String.valueOf((header + "." + tamperedPayload + "." + secret).hashCode()).equals(signature);
System.out.println("original verifies: " + originalVerifies);
System.out.println("tampered verifies: " + tamperedVerifies);The secret never appears in the token itself — only header, payload and signature would travel on the wire. Given that, what would it take for the tampered version to verify?
Recomputing a matching signature requires the secret, which never travelled
The attacker who edits payload to "role":"admin" can recompute header + "." + tamperedPayload + "." + secret only if they also know secret — and they do not, because it is never part of the token, only used server-side to compute and check the signature. Without it, they can change the claims, but they cannot produce a value equal to what the original signature actually was for those new claims, so a receiver that recomputes and compares (as real HS256 verification does with HMAC-SHA256, not hashCode()) rejects it. This is also exactly why a token that arrives with alg: none and an empty signature segment is dangerous if honoured: it is a receiver being told "don't do this comparison at all," which is a very different thing from the comparison failing.
Misconceptions
- "JWTs are encrypted, so it's fine to put anything in the claims." They are signed, not encrypted — the header and payload are plain base64url, decodable by anyone with the token and no key at all, which is exactly why this lesson's "what never goes in a token" section exists. A signature proves the claims were not altered; it does nothing to hide them.
- "Session fixation is a man-in-the-middle problem, so TLS prevents it." TLS protects the token in transit; fixation is about whether the server ever lets a pre-existing identifier become authenticated, which is a server-side design question independent of transport security. A perfectly encrypted connection does nothing to stop an attacker who planted the session id legitimately, over that same encrypted connection, before the victim ever logged in.
Sources
- RFC 7519 — JSON Web Token (JWT).
- RFC 6265 — HTTP State Management Mechanism (cookies).
- OWASP Session Management Cheat Sheet.
- OWASP JSON Web Token Cheat Sheet for Java.