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 asscope. - 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:
- Parses the token and rejects any
algother than the one it expects (nevernone; never accept an HMAC algorithm when you expect an asymmetric one, or the public key can be misused as the HMAC secret). - Finds the key by
kidin the trusted JWKS and verifies the signature. - Checks
issequals the expected issuer andaudcontains this API. - Checks
expandnbfagainst the clock, allowing a small skew (seconds to a minute). - Checks
typwhere profiles define it, then applies authorization usingsubandscope.
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.