Sessions, Tokens and JWT
HTTP is stateless, so after a shopper logs in, the next request arrives with no memory of that login. Asking for the password on every click is out of the question. Instead, the server hands over something the client shows on each request, like a wristband at an event. There are two common kinds of wristband.
The rule
A session is a key to a record the server keeps; a token carries its own signed record.
Cookie-based sessions. After login, the server creates a session record such as "session 7f3a… belongs to user 12, expires at 18:00" in its database or cache, and sends the browser a cookie holding only that random id:
Set-Cookie: session=7f3a9c...; HttpOnly; Secure; SameSite=Lax; Path=/The browser sends the cookie back automatically on every request to the site. The server looks up the id to find the user. Logging out, or banning a user, simply deletes the record. HttpOnly hides the cookie from JavaScript, Secure sends it only over HTTPS, and SameSite limits sending it along with requests started by other sites.
Tokens. Instead of keeping a record, the server can issue a signed token, and the client sends it in a header:
Authorization: Bearer eyJhbGciOiJIUzI1NiJ9.eyJzdWIiOiIxMiIsImV4cCI6MTc5MDAwMDAwMH0.4kX...The most common format is the JWT (JSON Web Token). It has three base64url-encoded parts joined by dots:
- Header: which signing algorithm was used, for example
{"alg": "HS256"}. - Payload: the claims, such as
{"sub": "12", "exp": 1790000000}: who the token is about and when it expires. - Signature: computed from the header, the payload and a secret key only the server knows.
The server checks the signature and the expiry, and trusts the claims without a database lookup. Change one character of the payload and the signature no longer matches.
Crucially, signed is not encrypted. Anyone holding the token can decode the payload and read it. Never put passwords, card numbers or other secrets inside.
The shortcut
Ask "Where does the truth live?" With a session, on the server: easy to revoke, but every request needs a lookup. With a JWT, inside the token: no lookup, but it stays valid until it expires, so keep it short-lived and pair it with a refresh mechanism or a revocation check.
Log in
The shopper sends email and password. The server checks the password hash.
Drills
Answer fast — trust the rule.
In a cookie-based session, what does the cookie usually contain?
What are the three parts of a JWT?
Someone copies a JWT and decodes its payload. What can they see?
A user changes a JWT's payload from "sub": "12" to "sub": "1". What should the server do?
A banned user's session must stop working immediately. Which design makes that simplest?
Remember
- A session is a key to a record the server keeps; a token carries its own signed record.
- JWT = header.payload.signature; signed, not encrypted, so no secrets inside.
- Sessions revoke easily; JWTs avoid lookups but need short lifetimes or a revocation check.
