Sessions vs tokens

Why you need it

After you log in, every later request must say who you are. The server can look you up in a shared store each time, or you can carry a signed card that proves it by itself. Each way has a cost, and picking the wrong one causes slow logins or users who cannot be logged out.

Think of it like this

A cloakroom ticket against a passport. The ticket is just a number; the cloakroom must check its list to know whose coat it is. A passport carries your name and a stamp that anyone can check without phoning the office that issued it.

Where you’ll find it

  • Google: "Sign in with Google" hands apps an ID token, a signed JWT the app checks by itself.
  • Firebase: Gives each logged-in user an ID token that your servers check with a public key, with no call home.
  • Auth0: A popular login service built on JSON Web Tokens.

What to know first

Cookie. A small piece of text the browser stores and sends back with every request to the same site.

Signature. A stamp made with a secret key. Anyone with the matching key can tell whether the content was changed, but cannot make a new stamp without the secret.

JWT. JSON Web Token: a common token format with three parts, header, content and signature, joined by dots.

How it works

  1. Session: carry a number, look it up. On login the server stores "session 42 = Ana" in a shared store and gives your browser 42 in a cookie. Every request, a server asks the store who 42 is. This is the first half of the animation.
  2. Logging out a session is easy. Delete row 42 and it stops working everywhere, at once. The cost is one store lookup on every request, and a store that must never go down.
  3. Token: carry the facts, signed. On login the server gives you a token saying "user Ana, until 10:15", signed with its key. Any server checks the signature and reads the name. No store, no lookup.
  4. Tokens are hard to take back. A token stays valid until it expires, even if Ana logs out or is banned. So tokens are kept short-lived, about 15 minutes, and renewed with a separate refresh token that the server can refuse.
  5. Tokens are readable. A JWT is signed, not hidden: anyone holding it can read what is inside. Never put secrets in it, and keep it small, because it travels with every request.

An example

A site has 20 servers and 50,000 requests a second. With sessions, that is 50,000 lookups a second against the session store, which becomes the busiest machine in the building.

With 15-minute tokens, servers check each signature on their own in microseconds. The store is only used once every 15 minutes per user, to refresh.

But when an account is stolen, the attacker's token keeps working for up to 15 minutes. Teams accept that window, or keep a small list of banned tokens to check.

Further reading