Sessions, cookies, JWT & OAuth 2.0
How a server remembers who you are — and who let you in.
HTTP is stateless, so identity is carried between requests. A cookie stores a session id that maps to server-side state (stateful), or a signed token/JWT carries self-contained claims the server verifies without storing anything (stateless). OAuth 2.0 layers on delegated authorization so an app can act on your behalf without ever seeing your password.
Log in
The browser sends the user's credentials to the app server over an encrypted HTTPS connection. This is the single moment in the whole flow where the raw password is exchanged, which is why it must never travel over plain HTTP. Everything afterwards relies on a credential the server hands back instead of the password itself.
Create session or issue token
Once the credentials check out, the app coordinates with the auth server to establish proof of identity. In the stateful model it creates server-side session state — a random session id mapped to the user in a store like Redis. In the stateless model it instead mints a signed JWT whose claims describe the user, so no server-side record is kept.
Hand identity to the browser
The server returns the identity credential to the client. For sessions, a Set-Cookie header plants the opaque session id in the browser, ideally flagged HttpOnly, Secure and SameSite. For tokens, the JWT is returned in the response body for the client to store and resend.
Send it with each request
Because HTTP is stateless and forgets everything between requests, the browser must re-present the credential every time. Cookies are attached automatically by the browser; bearer tokens are sent explicitly in an Authorization header. Either way the server has something to recognize the caller by.
Validate
The server verifies the incoming credential before trusting it. A session id is validated by looking it up in the store, which means a database or cache hit on every request. A JWT is validated by recomputing its signature with the server's key — self-contained, so nothing is stored or looked up. OAuth 2.0 access tokens are checked the same two ways.
Respond
With identity confirmed, the server runs the request and returns the protected response. The same trust mechanism is what SSO reuses to grant access across many apps from one login. Revocation differs sharply: sessions can be deleted instantly, whereas a signed JWT stays valid until it expires.
The problem: HTTP has no memory
Every web login has to solve a surprisingly awkward problem: HTTP is stateless. Each request the browser makes is an independent event, and the server, by default, has no idea that the person requesting /account now is the same person who typed a password into /login a moment ago. Without some extra machinery, a user would have to re-enter their password on literally every click.
The universal fix is to hand the browser a credential after login and have it re-present that credential on every subsequent request. The credential proves "I already authenticated" so the server doesn't demand the password again. All of session cookies, JWTs and OAuth 2.0 access tokens are variations on this one idea — the differences are about *what the credential is*, *where the truth lives*, and *how you take it away again*.
Two concerns are worth separating up front because they are constantly confused. Authentication answers "who are you?" — proving identity. Authorization answers "what are you allowed to do?" — granting permissions. Sessions and JWTs are mostly about carrying an authenticated identity between requests. OAuth 2.0, despite being used everywhere for "Log in with Google", is fundamentally an *authorization* framework. Keeping these straight is the single biggest source of clarity in this topic.
Cookies: the envelope everything rides in
A cookie is just a small piece of data the server asks the browser to store and send back. On login the server returns a Set-Cookie header; from then on the browser automatically attaches that cookie to every request bound for the same site. That automatic attachment is the whole point — the developer writes no code to "remember" the user, the browser does it.
Cookies carry a set of critical security attributes, and getting them wrong is a classic vulnerability:
HttpOnlystops JavaScript from reading the cookie, which blunts token theft via cross-site scripting (XSS).Securemeans the cookie is only sent over HTTPS, so it can't leak over plain HTTP.SameSite(Lax,Strict, orNone) controls whether the cookie rides along on cross-site requests, the main defense against cross-site request forgery (CSRF).Expires/Max-Agedecide whether it's a short-lived session cookie or a persistent one.
A cookie is a delivery mechanism, not an identity model by itself. What you *put* in the cookie is the real design decision — and that splits into the two big schools: an opaque session id (stateful) or a self-contained token (stateless).
Stateful sessions: the server holds the truth
In the classic server-side session model, login creates a record on the server — a row or key holding "session a1b2c3 belongs to user 42, logged in at 09:00, role admin" — and the browser only ever receives an opaque, random session id in a cookie. The id itself means nothing; it's a coat-check ticket. On each request the server takes the id, looks it up in its session store (often an in-memory cache like Redis, or a database table), and rehydrates who the user is.
The great strength here is control. Because the server owns the record, it can revoke a session instantly — log someone out everywhere, kill all sessions after a password change, or expire idle sessions — just by deleting the entry. The data never leaves the server, so it can hold as much sensitive context as you like without exposing it.
The cost is that the session is *state the server must store and look up on every single request*. That's fine for one server, but in a horizontally scaled system every request could land on a different machine. You then need either a shared session store that all servers hit (adding a network round trip and a dependency), or "sticky sessions" pinning a user to one server (which hurts load balancing and fails when that server dies). Managing this shared state at scale is exactly the friction that made stateless tokens attractive.
Stateless tokens: the credential carries its own proof
A JWT (JSON Web Token) flips the model: instead of storing state and handing back a meaningless id, the server hands back a token that *contains the identity itself*, cryptographically sealed so it can't be forged. A JWT is three base64url-encoded parts joined by dots — header.payload.signature:
- The header names the signing algorithm (e.g.
HS256orRS256). - The payload holds the *claims* —
sub(subject/user id),exp(expiry),iat(issued-at), roles, and so on. This is encoded, not encrypted, so never put secrets in it. - The signature is a keyed hash of the header and payload. With HMAC the server signs and verifies with one shared secret; with RSA/ECDSA it signs with a private key and anyone can verify with the public key.
Verification needs no lookup: the server recomputes the signature over the received header.payload and checks it matches, then checks exp. If both pass, the claims are trustworthy — any tampering breaks the signature. This is what "stateless" means: no session store, no per-request database hit, and any server holding the key can validate the token. That scales beautifully across many services.
The unavoidable trade-off is revocation. A signed JWT is valid until it expires, and because nothing is stored server-side there's nothing to delete — you can't easily kill a stolen token mid-life. The standard mitigation is a *short-lived access token* (minutes) paired with a *long-lived refresh token*; the access token expires quickly on its own, and the refresh token, which you *can* track and revoke, is used to mint new ones. This is also why token theft is serious: an attacker who steals a bearer JWT can use it until exp.
OAuth 2.0: delegated authorization, not login
OAuth 2.0 solves a different problem: letting an app do something on your behalf *without ever seeing your password*. When a photo-printing site wants your Google Photos, you don't hand it your Google password — you let Google issue it a scoped access token. There are four roles:
- Resource owner — you, the user who owns the data.
- Client — the app that wants access (the printing site).
- Authorization server — the party that authenticates you and issues tokens (Google's auth service).
- Resource server — the API holding the data, which accepts the access token (the Photos API).
The recommended authorization-code flow goes: the client redirects you to the authorization server; you log in and consent to a specific scope (e.g. read-only photos); the server redirects back to the client with a short-lived authorization code; the client then exchanges that code — over a back-channel server-to-server call, along with its own client secret — for an access token (and often a refresh token). The client uses the access token to call the resource server. Splitting it into a code plus a back-channel exchange keeps the token out of the browser URL and out of the user's hands.
A crucial clarification: OAuth 2.0 by itself is *authorization*, not authentication — the access token says "this app may read photos", not "this is definitely Alice". OpenID Connect (OIDC) is the thin layer built on top of OAuth 2.0 that adds real login, returning a signed ID token (itself a JWT) that authenticates the user. "Sign in with Google" is OIDC; "let this app post to your feed" is plain OAuth.
Choosing well: trade-offs, failures, and guidance
There's no universally correct choice — you're trading control against scale, and picking based on your topology:
- Server-side sessions shine for traditional server-rendered web apps and anywhere instant revocation and tight control matter (banking, admin panels). The price is shared session state.
- JWTs shine for stateless APIs, microservices, and mobile clients where you don't want a session lookup on every call. The price is weak revocation, mitigated by short expiries and refresh tokens.
- OAuth 2.0 / OIDC is the answer whenever a *third party* is involved — delegated access to someone else's API, or federated login — so you're not collecting other services' passwords.
The common failure modes are worth memorizing. Storing JWTs in localStorage exposes them to XSS theft; HttpOnly cookies are safer. Putting secrets in a JWT payload leaks them, since it's only encoded. Forgetting to check exp, or accepting the alg: none header, lets forged tokens through. Long-lived tokens with no refresh strategy mean a stolen credential works for days. And treating an OAuth access token as proof of identity (instead of using OIDC's ID token) is a well-known authentication bug.
The through-line: since HTTP forgets you between requests, you must re-present a credential each time, and the entire design space is about *where the trust lives* (in a server store you can revoke, or in a signed token that scales) and *how carefully you protect and expire that credential*. Get the cookie flags, expiries, and revocation story right and the rest follows.
A cookie is a small piece of data the browser stores and sends back with every request to that site.
A session is server-side state keyed by a session id kept in a cookie — stateful, so the server must store it.
A token/JWT is self-contained signed claims (header.payload.signature) the server verifies without storing state — stateless.
SSO means one login grants access across many apps; OAuth 2.0 is delegated authorization, not authentication.
OAuth 2.0 issues an access token so a client can act on a user's behalf without their password (resource owner, client, authorization server, resource server).
Quick quiz
What makes a JWT 'stateless'?
OAuth 2.0 is fundamentally about…
How SSO works
One login, many apps — because everyone trusts the same doorman.
How two-factor authentication works
A password can be stolen. A second, independent factor is much harder to steal too.
How HTTPS works
The TLS handshake that turns a plain TCP connection into a private, verified channel.