How it works
After verifying a login, the authentication service issues a signed access token. A typical compact signed JWT has three base64url-encoded parts: header, payload, and signature. The header identifies the signing algorithm and often a key ID; the payload contains claims such as sub (subject), iss (issuer), aud (audience), and exp (expiration).
For example, a token might identify user u123, target the orders API, and expire in five minutes. The client sends it with requests, commonly using Authorization: Bearer <token> over HTTPS. A signed JWT is not encrypted: anyone holding it can read its payload, so do not include passwords, secrets, or unnecessary personal data.
The API uses a trusted verification key and an explicitly allowed algorithm to verify the signature. It also checks the expected issuer, audience, expiration, and any required claims, with bounded clock-skew tolerance. Decoding the payload alone does not authenticate anything.
With asymmetric signing, the authentication service holds the private key while APIs receive public keys, often through a JSON Web Key Set (JWKS) endpoint. APIs cache those keys, allowing local verification without contacting the authentication service for every request. A valid identity still needs resource-level authorization: user u123 cannot read every order merely because the token is valid.
A common design pairs short-lived access JWTs with longer-lived refresh tokens backed by server-side session records. Refreshing checks that the session remains active and issues a new access token. Refresh-token rotation and reuse detection help contain theft, but require coordinated state and careful handling of concurrent refresh requests.
Expiration bounds how long a stolen or revoked access token remains usable under local-only validation. If logout, account suspension, or permission changes must take effect sooner, add a revocation lookup, session-version check, or current authorization check. That reintroduces shared state and an explicit cache-freshness policy.
A worked example
Five-minute tokens with a stricter suspension deadline
Suppose an API handles 20,000 requests per second and issues access JWTs valid for five minutes. Each API instance caches trusted public keys and validates tokens locally, avoiding a session lookup on every request. Logout revokes the refresh session, but a copied access token can still work for its remaining lifetime, plus allowed clock skew. Now require account suspension to take effect within 30 seconds. Add an account-status check with cache freshness and propagation delays bounded by that deadline. If status cannot be refreshed before the bound expires, reject protected requests. JWTs still provide verifiable identity, but the stricter revocation guarantee now depends on shared state and its availability.
Trade-offs to say out loud
- Local validation versus immediate revocation
- Avoiding session lookups removes a request-path dependency, but an already issued token generally remains valid until expiration unless validators consult additional state.
- Short lifetimes versus refresh traffic
- Shorter access-token lifetimes reduce the replay window but increase refresh requests and dependence on the authentication service.
- Embedded claims versus fresh permissions
- Putting roles or scopes in tokens saves reads, but those claims can become stale and do not replace current resource-level access checks.
- Distributed verification versus key management
- Asymmetric signatures let services verify without gaining minting authority, but require secure signing-key storage, trusted key distribution, and planned rotation.
- Self-contained tokens versus request overhead
- JWTs are often larger than opaque session IDs, increasing bandwidth and potentially hitting header or cookie limits when claims grow.
- Bearer convenience versus theft risk
- Anyone possessing a bearer token can replay it within its scope and lifetime, so transport, client storage, logging, and browser protections matter.
When to reach for it
- Several APIs need to validate tokens from one trusted issuer without a synchronous authentication-service call on every request.
- Regional APIs must continue validating existing credentials during a temporary authentication-service outage, with an explicit policy for expiration and revocation.
- A short-lived, narrowly scoped credential must carry verifiable claims such as an audience, tenant, or playback-session identifier.
- The requirements tolerate a bounded revocation delay, or justify the additional state needed for faster revocation.
How to bring it up in the interview
- Start with the revocation requirement, not the token format: ask how quickly logout, account suspension, and permission removal must take effect.
- Compare JWT access tokens with opaque server-side sessions; for a single application, an opaque session cookie may be simpler and easier to revoke.
- Name the validation boundary and trust model: which component signs, which services verify, and how downstream services reject forged identity headers or tokens intended for another audience.
- Explain routine key rotation: publish the new public key before signing with it, retain old verification keys until their tokens expire, and bound refresh attempts for unknown key IDs. Expect questions about compromised keys and stale JWKS caches.
- Separate browser storage from token format: HttpOnly, Secure cookies limit JavaScript access but require CSRF defenses, while JavaScript-readable storage exposes tokens to theft through XSS.
Common mistakes
- Treating base64url encoding as encryption or treating a decoded payload as authenticated.
- Checking the signature but skipping issuer, audience, expiration, or algorithm restrictions.
- Claiming that deleting a browser token or revoking a refresh token immediately invalidates every issued access JWT.
- Assuming a signed role or tenant claim is sufficient authorization for a particular document, order, or account.
- Calling the whole authentication system stateless even though refresh sessions, recovery, revocation, and signing-key management require state.
Where it comes up
Interview questions where jwt is part of a strong answer, and why.
- Design a login and authentication systemJWT access tokens versus opaque sessions is a core design choice when balancing fast validation, logout, account suspension, and recovery.
- Design an ETA and live location sharing serviceShort-lived, trip-scoped JWTs offer a concrete access mechanism whose lifetime and revocation behavior must account for assignment changes.
- Design Netflix's concurrent screen limitA signed playback JWT can bind delivery access to an admitted session, but its expiry and renewal must respect lease revocation and slot reuse.
Questions people ask
What is the difference between JWT and OAuth?
JWT is a token format; OAuth is a framework for delegated authorization. An OAuth access token can be a JWT or an opaque string. OpenID Connect adds an authentication layer on top of OAuth and uses JWTs for ID tokens, which should not be substituted for API access tokens.
Is JWT authentication better than session authentication?
Neither is universally better. JWTs support local validation across services, while opaque session IDs make centralized revocation and session updates straightforward. Choose based on trust boundaries, request-path dependencies, and revocation requirements rather than assuming JWTs are inherently more scalable.
How do you revoke a JWT before it expires?
Validators must consult additional state, such as a token denylist, active-session record, or account token version. Cache lifetime and propagation delay determine how quickly revocation takes effect. Short token lifetimes limit exposure but do not provide immediate revocation.