Course contents

12. Security and Identity Lesson 3 of 8

JWT

JSON Web Tokens: structure, local signature verification without a lookup, the claims to check, the revocation problem, refresh tokens and where to store tokens.

18 minIntermediate10 steps
Loading the interactive simulation…
Loading the knowledge check…

Summary

  • A JWT is header.payload.signature; the payload is readable by anyone, the signature makes it tamper-evident.
  • APIs verify JWTs locally with cached public keys (JWKS): no per-request call to the identity provider.
  • Verification means a pinned algorithm plus iss, aud, exp and nbf checks; a valid signature alone is not enough.
  • A JWT stays valid until it expires: keep access tokens short, rotate refresh tokens, add a deny list only where instant revocation is required.
  • Keep tokens out of page scripts where possible (BFF), never long-lived in localStorage; sender-constrain them with DPoP or mTLS for high-value APIs.
Deep diveHow it works, trade-offs, failure modes, misconceptions and the interview angle.

What it is

A JSON Web Token (JWT, RFC 7519) is a compact, URL-safe token that carries claims about a subject, protected by a signature (JWS, RFC 7515) or, less often, encrypted (JWE, RFC 7516). It has three base64url-encoded parts separated by dots:

  • Header: {"alg": "ES256", "kid": "2026-11", "typ": "at+jwt"}, the algorithm and which key signed it.
  • Payload: registered claims such as iss (issuer), sub (subject), aud (audience), exp (expiry), nbf (not before), iat (issued at), jti (token id), plus application claims such as scope.
  • Signature over header.payload, made with the issuer’s private key (ES256, EdDSA, RS256/PS256) or a shared secret (HS256).

For OAuth access tokens, RFC 9068 defines a standard JWT profile (typ: at+jwt, required claims).

Why it exists

With opaque tokens or server-side sessions, every request needs a lookup: a session store, or the issuer’s introspection endpoint (RFC 7662). Across many services and high request rates, that lookup becomes a shared bottleneck and a shared point of failure. A signed token carries its own proof: any service holding the issuer’s public key can verify it locally, with no network call.

How it works

Issue. After authentication, the identity provider builds the claims, signs them with its private key and returns the token, usually as an OAuth access token.

Publish keys. The issuer publishes its public keys as a JWK Set (JWKS) at a well-known URL. Verifiers fetch and cache it, and refetch when they see an unknown kid. Key rotation works by publishing the new key before signing with it and keeping the old one until tokens signed with it have expired.

Verify. On each request the API:

  1. Parses the token and rejects any alg other than the one it expects (never none; never accept an HMAC algorithm when you expect an asymmetric one, or the public key can be misused as the HMAC secret).
  2. Finds the key by kid in the trusted JWKS and verifies the signature.
  3. Checks iss equals the expected issuer and aud contains this API.
  4. Checks exp and nbf against the clock, allowing a small skew (seconds to a minute).
  5. Checks typ where profiles define it, then applies authorization using sub and scope.

Signature verification is CPU work measured in microseconds for ECDSA, EdDSA or RSA verification on current hardware, so it adds almost nothing to request latency.

Expire and refresh. Access tokens are short-lived (often 5–15 minutes). The client keeps a refresh token, which only the authorization server accepts, and exchanges it for new access tokens. Because the server checks refresh tokens against its own state, revocation takes effect at the next refresh. Refresh token rotation returns a new refresh token on each use; if an old one is presented again, the server treats it as theft and revokes the whole family (recommended by the OAuth security BCP, RFC 9700, for public clients unless tokens are sender-constrained).

When to use it

  • APIs called by many services or at high rates, where a lookup per request would be a bottleneck.
  • Distributed systems where services should keep working when the identity provider is briefly unavailable.
  • OAuth 2.0 / OpenID Connect deployments (ID tokens are always JWTs; access tokens often are).
  • Short-lived, narrowly scoped service-to-service credentials.

When not to

  • As a browser session replacement when you need instant logout and have a single site: a server-side session is simpler and revocable.
  • For long-lived credentials: a stolen long-lived JWT is a long-lived breach.
  • For carrying secrets or personal data the client should not see, unless encrypted.
  • When the token would grow large (many roles, permissions lists): it travels on every request and may exceed header limits.

Trade-offs

Choice You gain You pay
JWT verified locally vs opaque token introspection No per-request call, IdP off the hot path, scales with the APIs Revocation delayed until expiry; claims may be stale
Short access-token lifetime Smaller revocation window More refresh traffic to the authorization server
Revocation (deny) list Near-instant revocation A lookup per request again, and state to distribute
Asymmetric (ES256/EdDSA/RS256) vs HS256 Verifiers cannot mint tokens; keys published via JWKS Slightly larger signatures; key rotation to manage
Tokens in a BFF vs in the browser Tokens never exposed to page scripts A server component per frontend; cookies need CSRF defences

Alternatives

  • Opaque tokens with introspection, ideally with a short cache: instant revocation, one source of truth, cost per request.
  • Server-side sessions for browser apps.
  • PASETO or other token formats with fewer algorithm choices, avoiding classic JWT misconfigurations.
  • Sender-constrained tokens: DPoP (RFC 9449) or mutual-TLS-bound tokens (RFC 8705), which a thief cannot use without the client’s private key.

Failure modes

  • Algorithm confusion: accepting alg: none, or verifying an HS256 token with the RSA public key as the secret.
  • Missing audience check: a token minted for service A is accepted by service B.
  • Long-lived tokens: stolen tokens stay valid for hours or days.
  • Stale claims: roles removed at the IdP keep working until the token expires.
  • JWKS fetch failure or key rotation without overlap: every verification fails when keys change.
  • Token theft via XSS: tokens in localStorage are readable by any script on the origin.
  • Oversized tokens: hundreds of claims blow past proxy header limits.
  • Clock skew: servers with drifting clocks reject fresh tokens or accept expired ones.

In production

Use a well-maintained library and configure it explicitly: allowed algorithms, issuer, audience, clock skew. Cache the JWKS with a sensible TTL and refetch on unknown kid. Keep access tokens short (minutes) and narrowly scoped to one audience. Rotate refresh tokens and detect reuse. For browser apps, prefer a backend-for-frontend so tokens never reach JavaScript; for SPAs that must hold tokens, keep the access token in memory. Store tokens in the OS keychain or keystore on mobile. Log jti, sub and client_id for audit, never whole tokens. For high-value APIs, sender-constrain tokens with DPoP or mTLS.

Common misconceptions

  • “JWTs are encrypted.” Signed JWTs are only encoded. Anyone can read them.
  • “Logging out invalidates the JWT.” It ends the session at the IdP; the access token works until exp.
  • “JWTs are stateless, so no server state is needed.” Refresh tokens, revocation lists and key sets are all state. JWTs move state off the hot path, not out of the system.
  • “HttpOnly cookies are always better than headers.” They stop exfiltration but bring CSRF; header tokens avoid CSRF but must be kept out of reach of scripts. Choose per architecture.

Interview angle

Expect “sessions or JWTs?”. A good answer weighs local verification and IdP independence against revocation, then offers the standard mitigation: short-lived access tokens, rotating refresh tokens checked at the authorization server, and a deny list only where instant revocation is a requirement. Name the verification checks (pinned alg, iss, aud, exp), the JWKS and key rotation, and a BFF or sender-constrained tokens for browser clients.

Model assumptions

Token structure, verification checks, revocation, refresh and storage are a scripted illustration: packets are placed by hand with illustrative durations (10 ms between browser and API, 14 ms to the identity provider). The engine has no model of signatures, claims or clocks. Validation cost is simulated: Poisson arrivals; an Orders API with 64 workers and 2 ms mean service time (lognormal, cv 0.3), 10 ms from the browsers; an introspection endpoint with 8 workers, 8 ms per call (cv 0.4) and room for 40 waiting calls, 5 ms from the API, so about 1,000 introspections per second; and a revocation list modelled as a key-value lookup with 16 connections and 0.5 ms per read, 1 ms away. Local signature verification is assumed to fit inside the API’s 2 ms of work. In the challenge, the introspection cache is modelled with a fixed 80% hit ratio. Numbers are illustrative, not benchmarks.

The lesson as textEvery step of the simulation, written out.
  1. 1. Three parts, one signature

    After login the identity provider issues a JSON Web Token (RFC 7519): header.payload.signature, each part base64url-encoded. The header names the algorithm and key id (alg: ES256, kid: 2026-11). The payload holds claims: issuer iss, subject sub, audience aud, expiry exp, issued-at iat, a unique id jti, and often scope. The signature covers the first two parts, made with the IdP’s private key.

    Base64url is encoding, not encryption: anyone holding the token can read the claims. Never put secrets in them. This step is a scripted illustration.

    Scene: The browser logs in at the identity provider and receives a signed JWT made of a header, a payload of claims and a signature.

    Key idea: A JWT is signed, not encrypted: readable by anyone, unforgeable without the private key.

  2. 2. The alternative: ask the issuer every time

    To see what a JWT saves, start with an opaque token: a random string that means nothing by itself. To learn who sent it, the API asks the identity provider’s introspection endpoint (RFC 7662) on every request.

    The simulation runs 400 requests per second. Every request makes the extra round trip to the IdP and waits for its answer: about 40 ms per request, and the IdP is about 40% busy just answering “is this token valid?”.

    Scene: Browsers send 400 requests per second to the Orders API, which asks the identity provider to introspect each token before answering. Latency is about 40 ms.

    Key idea: Opaque tokens need a call to the issuer per request (or a cache): simple to revoke, costly to check.

  3. 3. The identity provider becomes everyone’s bottleneck

    Traffic rises to 1,100 requests per second. The introspection endpoint can answer about 1,000 per second. Its queue fills, it starts rejecting calls, and the API fails those requests: roughly one in ten. The ones that succeed wait behind the queue.

    Every service that accepts tokens adds its whole request rate to the IdP, so the IdP must scale with total API traffic, not with logins.

    Scene: At 1,100 requests per second the introspection endpoint is saturated; its queue is full, it rejects calls and about one request in ten fails.

    Key idea: Per-request introspection couples every API’s capacity and availability to the identity provider.

  4. 4. Verify the signature, skip the call

    With JWTs the API checks the token itself. It fetched the IdP’s public keys once from its JWKS endpoint (the single request and response at the start) and caches them, refreshing when it sees an unknown kid. Verifying an ES256 or EdDSA signature is CPU work measured in microseconds.

    Same 1,100 requests per second: no errors, about 22 ms per request, and the IdP sees no per-request traffic. At 2 s the IdP goes down, and API calls keep working: only logins and token refreshes need it.

    Scene: The Orders API fetches the identity provider’s public keys once, then verifies every token locally. At 1,100 requests per second nothing fails and latency is about 22 ms, even after the identity provider goes down.

    Key idea: Self-contained tokens move validation from a network call to a local signature check: stateless, fast, IdP off the hot path.

  5. 5. A valid signature is not enough

    Verification is a checklist, and libraries get it wrong when misconfigured. Pin the algorithm: accept only the one you expect (never alg: none, and never let an RSA public key be used as an HMAC secret). Check iss (our IdP), aud (this API, so a token minted for another service is refused), exp and nbf with a small clock-skew allowance, and pick the key by kid from the trusted JWKS only.

    The attacker tries two forgeries: a payload edited to role: admin (signature no longer matches) and a token with alg: none. Both get 401.

    Scene: An attacker sends a token with an edited payload and then one claiming no algorithm. The Orders API rejects both with 401.

    Key idea: Verify signature with a pinned algorithm, then iss, aud, exp/nbf. Use a maintained library with explicit settings.

  6. 6. Logout does not reach the API

    Alice logs out (or an admin disables her account). The IdP ends her session. But the attacker copied her access token earlier, and that token is still valid: the signature checks out and exp has not passed. The API never asks anyone, so it answers 200.

    This is the price of statelessness: a JWT cannot be revoked by the issuer once it is out. It stays usable until it expires. Role changes have the same problem: claims baked into the token stay until it expires.

    Scene: The browser logs out at the identity provider. Afterwards the attacker sends the stolen access token to the Orders API, which still accepts it because the signature and expiry are valid.

    Key idea: A self-contained token is valid until exp, whatever happens at the IdP. Its lifetime is your revocation delay.

  7. 7. Short-lived access tokens, rotating refresh tokens

    Shrink the window: give access tokens 5–15 minutes. When one expires the API answers 401, the client presents its refresh token to the IdP, and gets a new access token. The IdP checks the refresh token against its own state, so this is where revocation takes effect: a logged-out user gets no new access token.

    The IdP also rotates refresh tokens: each use returns a new one and invalidates the old. When the attacker later replays an old refresh token, the IdP sees the reuse, refuses it and revokes the whole token family, logging out the legitimate client too, which is the safe outcome.

    Scene: The browser’s access token has expired, so the Orders API answers 401; the browser exchanges its refresh token at the identity provider for a new access token and retries successfully. Then the attacker replays the old refresh token and the identity provider rejects it.

    Key idea: Short access tokens bound the revocation delay; refresh tokens are checked at the IdP, rotated, and reuse revokes the family.

  8. 8. When minutes are too long: a revocation list

    Some systems cannot wait even ten minutes (a bank freezing a stolen account). Then the API also checks the token’s jti against a revocation list: tokens revoked before their expiry. The list stays small, because entries can be dropped once the token would have expired anyway.

    The simulation runs 600 requests per second with the check: still no errors, about 2–3 ms more per request for the extra round trip. Notice what happened: you have added back a lookup per request, just a much cheaper one than full introspection. Some teams push the list into each API instance’s memory instead.

    Scene: Browsers send 600 requests per second; the Orders API verifies each token locally and checks its id against a small revocation list. Nothing fails and latency rises by 2 to 3 ms.

    Key idea: Instant revocation needs state again; a small deny list of unexpired revoked token ids keeps it cheap.

  9. 9. Where should a browser keep tokens?

    Anything JavaScript can read, an XSS bug can read and send to an attacker, who then uses it from anywhere until it expires. That rules out long-lived tokens in localStorage. Keeping a short-lived access token in memory is better, but injected script can still use it while the page is open.

    For browser apps, current IETF guidance favours a backend-for-frontend (BFF): the browser holds only an HttpOnly session cookie, and the BFF keeps the access and refresh tokens server-side and attaches them to API calls. You inherit cookie concerns (CSRF defences) and gain tokens that never reach the browser. Sender-constrained tokens (DPoP, RFC 9449, or mutual TLS, RFC 8705) go further: a stolen token is useless without the client’s private key. Native apps keep tokens in the OS keychain or keystore.

    Scene: The browser sends a request with only a session cookie to the backend-for-frontend, which attaches the access token and calls the Orders API, then relays the answer.

    Key idea: Keep tokens out of JavaScript where you can (BFF + HttpOnly cookie); otherwise short-lived and in memory, never long-lived in localStorage.

  10. 10. Stateless, with the state put back where it matters

    Browsers send 600 requests per second again. The API verifies each JWT locally against cached keys and checks a small revocation list; the identity provider handles only logins and refreshes.

    JWTs buy fast, local, scalable validation and an IdP off the request path. They cost you revocation: keep access tokens short, rotate refresh tokens, add a deny list only where instant revocation is required, verify every claim, and keep tokens out of reach of page scripts.

    Scene: Browsers send 600 requests per second to the Orders API, which verifies tokens locally and checks the revocation list. The identity provider is not on the request path; nothing fails.

    Key idea: Verify locally, expire quickly, refresh at the IdP, and keep tokens out of JavaScript.