Authentication Methods Compared: Sessions, JWT, OAuth
Sessions, JWTs, API keys, OAuth 2.0, OIDC, passkeys and mTLS compared, and which one fits a web app, a mobile app or a service-to-service call.
Related chapters
- Start here in System Design
- How a system design interview is graded
- The delivery framework: five phases and a clock
- Numbers to know: what one machine can really do
- System Design Concepts: CAP, SQL vs NoSQL, Message Queues
- SQL vs NoSQL: How to Choose a Database (System Design)
- Traffic Jumps 10×: What Breaks First? (System Design)
- Proxy vs Load Balancer vs API Gateway (System Design)
- CAP Theorem Explained Simply, with Examples
- Why Use a Message Queue? System Design Explained
- Message Queue vs Pub/Sub vs Kafka: Differences
- Polling vs Long Polling vs SSE vs Webhooks (System Design)
- API design in System Design
- REST vs GraphQL vs gRPC: Choosing an API (System Design)
- API Goals Canvas: Design APIs from the Consumer
- REST API Design: Resources, Methods, Status Codes
- HTTP Semantics, Richardson Maturity Model and HATEOAS
- GraphQL Explained: Over-fetching, Schema, N+1 Problem
- RPC and gRPC Explained: Protobuf, HTTP/2, When to Use
- API Design Best Practices: 9 Principles with Examples
- API Payload Design: Names, Types, Links and Errors
- Mapping Database Tables to API Resources, Step by Step
- API Design for Complex Schemas: Trees, Polymorphism, Bookings
- API Pagination, Idempotency Keys, Errors and Versioning
- Network-Efficient APIs: HTTP Caching, ETags, Field Selection
- Async APIs: 202 Accepted, Webhooks and Bulk Operations
- API Versioning and Evolution Without Breaking Clients
- API Contracts: OpenAPI, Contract Testing and Docs
- API Security: Authentication, Authorization, Rate Limiting
- OAuth 2, OpenID Connect and Scopes for APIs
- OWASP API Top 10 Explained: BOLA, SSRF and More
- Running APIs: Gateways, Mesh, Rate Limits, Canaries
- API Troubleshooting Interview: Slow APIs and Unexpected Errors
- API Design Review: A Staff-Level Capstone
- Spotify Web API: Resources, IDs, Payloads and Paging
- Spotify Web API: OAuth PKCE, Scopes, Quotas, Rate Limits
- Spotify Web API Changes: Real API Evolution Lessons
- Database-heavy designs in System Design
- Design a Distributed Key-Value Store (System Design Interview)
- Design a Hotel Reservation System (System Design Interview)
- Design a Digital Wallet (System Design Interview)
- Design S3-like Object Storage (System Design Interview)
- Games in System Design
- Shard City: Learn Database Sharding by Playing a Game
- System Design Case Studies: Flash Sale, Chat, ChatGPT
- Flash Sale System Design: Who Gets the Last Item
- Food Delivery App System Design: Which Database?
- Cache Stampede: Why the Database Fell Over and the Fix
- Live Streaming System Design: Scaling for a Final
- ChatGPT System Design: Streaming LLM Responses
- RAG System Design: Product Q&A on Sale Day
- IRCTC Tatkal System Design: Booking Under Extreme Load
- Group Chat System Design: WebSockets and Fan-Out
- Authentication in System Design: Sessions, JWT, OAuth
- JWT in System Design: Sessions, Revocation, Refresh Tokens
- JWT Interview Questions and Answers
- Life of a session, step by step
- JWT Structure Explained: Header, Payload, Signature
- Forge lab: why verification must be strict
- JWT vs Session Authentication: Which to Use
- The validation pipeline: where a bad request dies
- How to Revoke a JWT: Blocklists and Short Expiry
- Refresh Tokens and Rotation Explained
- Logout in depth: one device, all devices, SSO
- JWT Security Best Practices
- OAuth 2.0 and OpenID Connect Explained
- Where to Store JWT: localStorage vs HttpOnly Cookie
- JWT in Microservices: API Gateway vs Service Validation
- Microservices, keys, and trust boundaries
- Sender-constrained tokens: making a stolen token useless
- Authentication vs Authorization Middleware
- Failure explorer: what breaks when X fails
- Capacity planner: sessions vs JWT vs hybrid
- Edge cases catalog
- Test it, measure it, migrate to it
- Anti-patterns to reject in a design review
- Design checklist and cheat sheet
Keep learning
Overview
Basic Authentication HTTP/1.0, 1996 Username and password, base64-encoded, on every request Server compares the password with its user table each time Internal tools, a quick script, a test endpoint, always over HTTPS The password travels on every request, and there is no real logout Cookie-based (session) auth late 1990s A random session id in a cookie the browser sends by itself Server looks the id up in its session store A website with its own accounts on one domain Token authentication A random token in the Authorization header (Bearer …) Server looks the token up in a token table Mobile apps, CLIs, API keys for scripts and partners Still one database lookup per request, and the client must store the token safely RFC 7519, 2015 A signed token that contains the user id, roles and expiry Many services, or several servers, that all need to know who is calling OAuth 2.0 RFC 6749, 2012 An access token, issued after the user approves on the provider’s own page The API that owns the data checks the token and its scopes Letting another app act for a user: “allow this app to read your calendar” OpenID Connect An ID token (a JWT) saying who signed in, issued through an OAuth flow Your app checks the ID token’s signature, issuer, audience and expiry “Sign in with Google / Apple / GitHub”, and modern company single sign-on Redirect flows to get right, and you depend on the provider SAML 2.0 A signed XML assertion posted by the browser from the company’s identity provider Your app checks the XML signature against the identity provider’s certificate Enterprise single sign-on: employees log in once through Okta, Entra ID (Azure AD) or ADFS A person in a browser A person in our mobile app A script or another server Another company’s app, for our user We keep the passwords Google, Apple, GitHub… The customer’s company (Okta, Entra ID) The other app must never see the user’s password. The user approves on your page, and the app gets a token limited to the scopes they allowed. A script has no person to type a password or follow a redirect. Give it a long random API key it sends in a header, one per client, so you can revoke one without touching the others. Basic auth is acceptable only for internal, low-risk tools over HTTPS. Between companies’ servers, OAuth’s client credentials flow is the standard. The customer’s IT team owns the accounts. Their identity provider proves who the employee is, and leavers lose access everywhere in one step. Google or Apple proves who the user is and hands you a signed ID token. You never store a password. OIDC only covers the sign-in. After it, issue your own session cookie or token for the following requests. Many services can verify a signed token without each one calling a session store. Keep the JWT short-lived (minutes), store it in an HttpOnly cookie, and use a refresh token to renew it. Logout and bans take effect on the next request: delete the session row and the cookie is worthless. The simplest safe option for a website with its own accounts. The browser sends the cookie for you. Set HttpOnly, Secure and SameSite on the cookie, and protect forms against CSRF. With many services, keep sessions in a shared store such as Redis. Each service verifies the token itself, so no shared lookup on every request. Short access tokens plus a refresh token kept in the phone’s secure storage (Keychain or Keystore). A mobile app does not have a browser’s cookie jar on every call. An opaque token in the Authorization header is simple, and deleting it from the table logs the user out at once. Store it in the Keychain or Keystore, never in plain app storage. 1. Who is calling? Who is calling 2. Who owns the user accounts? Who owns the accounts 3. How many services check the login? How many services One app Many services 4. Logout and bans must work instantly The password crosses the network on every request, and nothing can be logged out Mobile apps, scripts and other domains do not fit the cookie model, and CSRF needs extra defences With many services, every request needs a lookup in a central token store A stolen or revoked token stays valid until it expires A JWT stays valid until expiry, even after logout Not fixed by another method: short expiry, refresh tokens and a denylist for emergencies A third-party app would have to store the user’s real password to call your API Apps began using OAuth tokens as proof of identity, which they are not Adds a standard signed ID token and claims (sub, email) on top of the OAuth flow You still need your own session after the sign-in Heavy XML, browser-only, tricky signature checks SAML does not suit mobile apps and APIs JSON tokens over the same redirect idea, usable from browsers, phones and APIs Many enterprises still require SAML, so B2B products often offer both system design · authentication Authentication: what it means, and which method fits your need Basic, cookies, tokens, JWT, OAuth, OpenID Connect and SAML are not seven answers to one question. Each answers a different need, and each was invented to fix a problem in an earlier one.
1. What authentication means
Authentication answers “who are you?”. Authorization answers “what are you allowed to do?”. A hotel checks your passport at the desk (authentication), then gives you a key card that opens only your room (authorization). Authentication (authn) Prove you are Asha. Fails with 401 Unauthorized. Authorization (authz) Asha may read order 812 but not delete users. Fails with 403 Forbidden. You prove who you are with a factor: Something you know Password, PIN. Something you have Phone with an authenticator app, a security key. Something you are Fingerprint, face. Two factors from different groups is multi-factor authentication (MFA). The methods in this chapter are about what happens around that check.
2. The real problem: HTTP forgets you
HTTP is stateless. Each request arrives alone, so after you log in, every following request must carry some proof. That is where the methods differ. 1. Log in once prove who you are 2. Get a proof session id, token, JWT… 3. Every request carries the proof 4. Server checks it lookup, or verify a signature Ask of any method: what does each request carry, who checks it, and how is it cancelled?
3. Four questions decide the method
Who is calling? A person in a browser, a person in a mobile app, a script, or someone else’s app acting for your user. Who owns the accounts? Your own user table, a social provider like Google, or the customer’s company directory. How many services check it? One app, or many services that would all need to look the login up. How fast must logout work? Instantly (banking, admin tools) or within minutes (most consumer apps).
4. Lab: describe your need, get a method
Answer the four questions. The answer changes as you go.
5. The seven methods, one line each
Each request carries Who checks it Weak spot “OpenID” today means OpenID Connect. The older OpenID 2.0 is retired.
6. Two families, not one list
How each request proves who it is Basic, cookie sessions, tokens, JWT. Used after anyone has logged in, by every request. Who does the login, and for whom OAuth, OpenID Connect, SAML. Protocols between your app and someone else who proves the identity or grants access. That is why they combine. “Sign in with Google” is OpenID Connect for the login, then a session cookie for every request after. An enterprise login is SAML for the login, then your own session or JWT. Your app click “Sign in with Google” redirect to Google user signs in, approves Google owns the password receive code → ID token OIDC: verify signature, issuer, audience create session set an HttpOnly cookie every later request carries the cookie, not the Google token The login method and the per-request method are separate choices.
7. Which method fixes which problem
Read each row left to right: the problem in one method, the method that fixed it, and the new problem it brought. Click any cell to see it in detail, with the requests and an example. Problem in… Fixed by… New problem it brings no other method: short expiry password every time Cookie session password once works off the browser no lookup The per-request family: each step moved work away from the password and the database. Shared passwords apps asked for yours OAuth 2.0 scoped access OpenID Connect standard identity older enterprise SSO, still common The login family: each step kept the password with whoever owns the account.
8. Mistakes interviewers listen for
“We use OAuth for login” OAuth alone grants access. For login, say OpenID Connect and check the ID token. “JWT is more secure than sessions” It is more scalable, not more secure. It is harder to revoke. Basic auth over HTTP Base64 is encoding, not encryption. Anyone on the network reads the password. Tokens in localStorage Any injected script can read them. Prefer HttpOnly cookies in browsers. Mixing up 401 and 403 401: we do not know who you are. 403: we know, and the answer is no. Forgetting the session after SSO SAML or OIDC proves the login once. Your app still needs a session for later requests. ★ Remember HTTP forgets you, so every request carries a proof: a password, session id, token or JWT.
Go deeper
→ JWT, chapter by chapter · JWT vs session · OAuth 2.0 and OIDC flows · revoking a JWT · where the token lives
More courses
- Jobs, linked to lessons — Browse jobs where every requirement links to the chapter that teaches it. See how ready you are, how long the gap takes to close, and which listings look stale.
- Match a job post to courses — Paste a job post. Each skill is matched to a track here and put in learning order, foundations first.
- React patterns from open source — Patterns extracted from Material UI, Radix, React Aria, React Hook Form, Redux Toolkit, TanStack, and Next.js — not slides about hooks.
- Databases in depth — How a query becomes work. Indexes, isolation, locks, and the plans that explain why a page is slow — not an ORM tour.
- NestJS: build a real API — One ticket-booking API, built in order: a plain Node server first, then NestJS modules, validation, a real database, and the features real clients lean on.
- Microservices — Microservice patterns one diagram at a time: how to split a monolith, how services talk, and how data stays consistent without distributed transactions.
- Kafka — A beginner-to-senior path through event logs, reliable delivery, production operations, and disaster recovery.
- AI engineering for software engineers — Eight free reads, in order, for software engineers moving into AI: when to build an agent, how to build one, how to test it, and how the model works underneath.
- Frontend system design — How a UI is sliced when it is a product, not a page: ownership of state, cache, routes, and what happens when the network lies.
- TypeScript in depth — The type system as a design tool. Inference, narrowing, generics, and the errors that mean the model is wrong — not a catalog of utility types.
- CSS in depth — See the box, then the page. Visual chapters from the box model through Flexbox surprises, Grid, selectors, and units, then backgrounds, shapes, and visual effects, each with a playground.
- Accessibility — Foundations first (WCAG in plain words, semantic HTML, lists, alt text), then hands-on HTML labs, a full pass of WAI-ARIA 1.3, and a final fix-the-page challenge.
- Docker — What an image is, why layers cache, and how containers find each other on a network.
- Redis — Fifteen Redis patterns, one picture each: cache, session, lock, counter, rate limiter, queue, and when Redis is the wrong tool.
- Kubernetes — Kubernetes from zero to operators: why it exists, Pods, Deployments and Services, then configuration, networking, storage, scheduling, scaling and security.
- AWS — AWS networking in plain English. A VPC is a gated housing society: streets are subnets, the Internet Gateway is the main gate, and a route table is the signboard.
- Networking: the NetRoute game — NetRoute is a packet logistics game. You wire up computers, switches, routers, firewalls and gateways, set each device, and watch glowing packets travel. If a packet gets dropped, the game shows you which header field was wrong.