Machine Room

Sessions vs JWTs

Stateful against stateless, what the server checks on every request, who can read a token, and why logout is the catch. The one-page notes from the reel.

Download the PDF

One-page notes, Sessions vs JWTs. Both keep you logged in. Each one has its own use case. 1, Session: the server remembers you. A browser holds a cookie SID=8a627966… with a padlock marked HttpOnly; an arrow to a server and its sessions table, session ID, user, device: 5f3f4295… Mia laptop, a9172db5… Jack phone, 8a627966… Jack laptop, the last row highlighted. The browser only gets a random session ID, in a cookie marked HttpOnly: scripts on the page can't read it. On every request the browser sends the cookie, and the server looks the ID up, in memory or in a database. 2, JWT: the server remembers nothing. The token as three pieces joined by dots, eyJhbGci… the header, eyJzdWIi… the payload, EdzdwqEK… the signature. Header: {"alg": "HS256", "typ": "JWT"}, names the signing algorithm. Payload: {"sub": "user_42", "name": "Jack", "role": "customer", "exp": 1794000000}, your user ID, role and expiry time. Signature: made over the header + payload with a key only the server holds. 3, On every request. Session: GET /orders with Cookie: SID=8a627966…, the server looks the ID up. JWT: GET /orders with Authorization: Bearer eyJhbGci…, the server looks nothing up; it checks the signature and the expiry, and trusts what's inside. Bearer = the server accepts it from whoever sends it. 4, Can anyone read the payload? Yes. Encoded, not encrypted. Any JWT decoder shows it as plain text, no key needed. Never put a secret in it. Change role "customer" to "admin" and the signature no longer matches, so the server rejects it. 5, Logging out. Session: delete the records, signed out at once, on all your devices. JWT: the server never tracked it, so it can't cancel one before it expires. The fix: JWTs are kept short-lived. A longer-lived refresh token gets a new one, and the server keeps track of that. To log you out, the server cancels the refresh token and no new JWT is issued. The JWT you already have works until its exp. 6, Which one? Sessions: logout has to be instant, a banking site, an admin panel. JWTs: many services trust one login, a mobile app's API, microservices; any server just needs the key, no database lookup. A session gives you an ID for a record the server keeps. A JWT gives you the record itself, signed.

On a phone, press and hold the image to save it.