System Design HLD-16.02
OAuth 2.0, OpenID Connect and JWT
How apps act for users without their passwords: the authorization code flow with PKCE, access vs refresh tokens, ID tokens, and validating and revoking JWTs.
The big idea
A budgeting app wants to read your bank transactions. The old way was to hand the app your bank password, which gives it full access to everything, forever, and leaves your password in yet another database. OAuth 2.0An authorization framework that lets an application obtain limited, revocable access to a user's resources on another service, through tokens issued by an authorization server, without seeing the user's password. replaces that with delegation: you log in at the bank itself, approve "read transactions" for this app, and the bank gives the app an access token limited to that scope, which you can revoke without changing your password.
OAuth answers "what may this app do?". OpenID Connect (OIDC)An identity layer on top of OAuth 2.0 that lets an app learn who the user is, through a signed ID token issued by the identity provider. adds "who is the user?", which is what "Sign in with Google" uses. Both commonly use JWTsJSON Web Token: a compact token made of a base64url-encoded header, payload of claims and signature, which services can verify without contacting the issuer.: signed tokens that any service can verify on its own, fast but hard to revoke early.
Think of a hotel key card. The front desk (authorization server) checks your identity once and issues a card that opens only your room and the gym, and only until checkout. The doors (APIs) do not call the front desk; they just check that the card is genuine and not expired.
How it works
Step 1: The authorization code flow with PKCE
- redirect to /authorize + code_challenge The app creates a random code_verifier, keeps it secret, and redirects the browser to the authorization server with its hash, the code_challenge, plus the requested scope.
- user logs in and approves scope The user logs in at the authorization server itself, never on the app, and approves the requested permissions.
- redirect back with one-time code The authorization server redirects the browser back to the app with a short-lived, one-time authorization code.
- code arrives at app's redirect URI The code reaches the app. On its own it is not enough to get tokens.
- POST /token: code + code_verifier The app exchanges the code for tokens over a direct back-channel request, proving it started the flow by sending the original code_verifier.
- access token + refresh token (+ ID token) The server checks that the verifier hashes to the challenge and returns an access token, a refresh token, and with OpenID Connect an ID token describing the user.
- GET /orders Authorization: Bearer <access token> The app calls the API with the access token. The API validates it and enforces its scope.
The PKCEProof Key for Code Exchange: the client sends a hash of a random secret when starting the flow and the secret itself when exchanging the code, so a stolen authorization code is useless to an attacker. step matters: the code travels through the browser and could be intercepted, but only the app that created the code_verifier can exchange it. Authorization code with PKCE is the recommended flow for web, mobile and single-page apps; the old implicit flow, which put tokens directly in the redirect URL, is deprecated. Machine-to-machine calls with no user use the client credentials flow instead.
Step 2: Access tokens, refresh tokens and ID tokens
- Access token: sent to APIs on every call. Short-lived (minutes to an hour) and limited by scope.
- Refresh token: used only with the authorization server to get new access tokens without another login. Long-lived, so stored carefully, and often rotated on every use so a stolen one is detected.
- ID token (OpenID Connect): a JWT about the user (who they are, when they logged in) meant for the app, not for calling APIs.
Step 3: JWT structure and validation
A JWT is three base64url parts separated by dots: a header (algorithm), a payload of claims (issuer iss, subject sub, audience aud, expiry exp, scopes) and a signature over the first two. Anyone can decode it; only the issuer can produce a valid signature. An API must check, every time:
- The signature, using the issuer's key (fetched from its published key set), with an expected algorithm; never accept
alg: noneor let the token choose. - Expiry (
exp), and not-before if present. - Issuer (
iss) and audience (aud): a token issued for another API must be rejected. - Scopes or roles for the action being performed ( Authentication vs authorization ).
Try it
Try this:
- Decode the valid token: read the subject, scope and expiry, and watch all four checks pass.
- Pick payload edited to admin. The payload decodes perfectly and claims admin scope, but the signature no longer matches, so it must be rejected.
- Try alg "none" and token for another API. Both are classic attacks or mix-ups that only explicit checks catch.
Going deeper
Revocation trade-offs
A JWT is valid until it expires, even if the user logs out or is fired, because APIs do not ask the issuer. Options: keep access tokens short (5 to 15 minutes) and revoke the refresh token; maintain a deny-list of revoked token ids that APIs check (giving back some of the lookup cost); or use opaque tokens that APIs check with the authorization server (token introspection), which revokes instantly at the cost of a call per request or a short cache.
Where tokens live in a browser
Tokens in localStorage are readable by any script on the page, so a cross-site scripting bug leaks them. Many web apps therefore keep tokens on the server side (a backend-for-frontend, API gateway and backend-for-frontend ) and give the browser only an HttpOnly session cookie.
Trade-offs
| Option | Wins when | Loses when |
|---|---|---|
| Self-contained JWT access tokens | Many services validating tokens without a central lookup | Revocation before expiry; token size |
| Opaque tokens with introspection | Instant revocation and central control | A call (or cache) to the authorization server per request |
| Short-lived access + rotating refresh tokens | Limiting damage from leaked access tokens | More token refresh traffic and client complexity |
| Backend-for-frontend holding tokens | Keeping tokens out of browser JavaScript | An extra server-side component |
Common mistakes
- Decoding a JWT and trusting its claims without verifying the signature.
- Accepting whatever algorithm the token header specifies, including "none".
- Not checking audience, so a token for one API works on another.
- Long-lived access tokens with no way to revoke them.
- Using an ID token to call APIs, or an access token to identify the user in the app.
In the wild
"Sign in with Google", "Sign in with Apple" and enterprise single sign-on are OpenID Connect flows, and APIs such as GitHub, Google and Microsoft Graph use OAuth 2.0 access tokens with scopes. Identity providers such as Auth0, Okta, Keycloak and Microsoft Entra ID issue JWT access and ID tokens and publish their signing keys for verification.
Check yourself
-
What does PKCE protect against?
Show answer
B. An attacker who intercepts the authorization code using it to obtain tokens Only the client holding the original code_verifier can exchange the code.
-
A user's account is disabled, but their JWT access token still works for 40 minutes. Why?
Show answer
B. Self-contained JWTs are validated locally until they expire; the API never asks the issuer Keep access tokens short-lived or add introspection or deny-lists for faster revocation.
-
An attacker edits a JWT's payload to add an admin scope. What stops them?
Show answer
B. Signature verification fails because the signature no longer matches the payload Anyone can change the payload; only the issuer's key can produce a matching signature.
-
Which token should a single-page app send when calling the orders API?
Show answer
B. The access token Access tokens are for APIs; ID tokens describe the user to the app; refresh tokens only go to the authorization server.
Recap
- OAuth 2.0 delegates limited, revocable access without sharing passwords; OpenID Connect adds user identity.
- Use the authorization code flow with PKCE for user-facing apps and client credentials for machine-to-machine.
- Access tokens are short-lived and scoped; refresh tokens renew them; ID tokens describe the user.
- Validate every JWT: signature with an expected algorithm, expiry, issuer, audience and scope.
- JWTs are fast to verify but hard to revoke; keep them short-lived or add introspection.