Skip to main content
03

Sessions vs JWT, and what OAuth is for

MediumAuthJWTOAuth

What's the difference between session-based auth and JWTs, and what are OAuth 2.0 and OpenID Connect for?

TL;DR

With sessions, the server stores session data and gives the browser a random session ID in a cookie; each request looks the session up. It's simple and easy to revoke. A JWT is a signed token that carries the claims itself (user ID, roles, expiry), so any service can verify it without a lookup. It's stateless and scales easily, but hard to revoke before it expires. OAuth 2.0 is for delegated authorization ("let this app access my Google Calendar"). OpenID Connect adds authentication on top ("Log in with Google") with an ID token.

Key points

  • JWTs are signed, not encrypted: anyone can read the payload. Never put secrets in it.
  • Typical JWT setup: a short-lived access token (5–15 min) plus a refresh token that's rotated on use and can be revoked server-side.
  • Verify the signature, exp, iss and aud, and pin the algorithm (reject alg: none).
  • Browser storage: an HttpOnly, Secure, SameSite cookie is safer than localStorage, which any XSS can read.
  • For SPAs and mobile apps, use the Authorization Code flow with PKCE. The implicit flow is deprecated.
  • Authentication is who you are; authorization is what you may do.

Example

text
Sessions:  browser --cookie: sid=abc--> API --lookup sid--> Redis
JWT:       browser --Authorization: Bearer eyJ...--> API (verify signature locally)

Common follow-ups

  • How do you log out a user who has a JWT? Keep access tokens short-lived, revoke the refresh token, and if you need instant revocation, keep a denylist of token IDs (jti). At that point you've reintroduced state.
  • Which should a typical web app use? A first-party web app is often simplest with sessions in a cookie. JWTs shine across many services or third parties.

What interviewers look for

Tip

Explain the stateful vs stateless trade-off, the revocation problem and how refresh tokens solve it, and OAuth as authorization vs OIDC as authentication.

  • Red flag: "JWTs are encrypted", or long-lived JWTs in localStorage.

Was this helpful?