Interview's MateAI Engineering
Interview's Mate

AI Engineering

LLMs, RAG, agents & evals

Visualizer

DSA Visualizer
All 32 lessons
Custom Playground
Try your own examples

Learning

System Design
31 architecture topics
SQL Learning
160 foundations → production topics
AI Engineering
160 LLM → backend topics
Data Science
160 Python → MLOps topics
Data Engineer
160 SQL → streaming topics
Docker
160 Docker learning topics
Kubernetes
160 K8s fundamentals → cloud
Java LearnSoon
Coming soon
Python Learn
Interview Q&A & internals
JavaScript Learn
Closures, async & DOM Q&A
Tech Learn
Search, practise & track Q&A
AI DSA Practice
Solve coding problems
Theme
Home
AI Engineering topics
Lesson 146/ 160
08. Backend

Authentication with JWT

Stateless auth tokens for API access with expiry and claim validation.

BeginnerJWT · Claims3 quiz questions
Practice Generative AI Q&A
In plain wordsDiagramTheoryStep by stepWhen to use itInterview cluesMistakes to avoidHands-onQuiz (3)Practice

In plain words

A JWT is a signed note the server gives you after you log in. It says who you are and how long it's good for, so other parts of the system can trust it without asking again.

Think of it like…

A festival wristband with a printed expiry time and a hologram. Staff at every gate can check the hologram and the time without phoning the box office, but if a wristband is stolen the gates can't cancel it, so wristbands are made to expire quickly and lost ones are listed at the gates.

Where you’ve seen it

After login, the auth service issues an access token valid for 15 minutes with claims iss: https://auth.example.com, sub: u_8412, aud: api.example.com, tenant_id: t_77, scope: chat:write docs:read, iat, exp and jti, about 350 bytes on the wire, and an opaque refresh token (random 256-bit value, stored hashed in the database, rotated on every use, valid for 30 days). It signs with ES256 and publishes the public keys at a JWKS endpoint with a kid so every service can verify without sharing a secret. Each service pins the accepted algorithm (rejecting none and any switch from RS/ES to HS, the classic algorithm-confusion attack), verifies the signature, then checks exp and nbf with 30 seconds of leeway for clock skew, iss and aud, and reads tenant_id and scope only after that. With 10,000 active users and 15-minute tokens, refreshes run 10,000 × 4 = 40,000 per hour, about 11 per second, a trivial load. Revocation is the cost of statelessness: if a user is disabled or a token leaks, the access token would work for up to 15 minutes, so the gateway keeps a Redis denylist of revoked jti values with a TTL equal to the remaining lifetime (at most 15 minutes), and a per-user token_version claim is bumped on password change or logout-everywhere. Browser sessions store the access token in memory and the refresh token in an HttpOnly; Secure; SameSite=Lax cookie, avoiding localStorage, where any XSS bug can read it. Per-tenant rate limits and AI budgets read the verified tenant_id claim, never a header the client controls. A WebSocket handshake uses a separate 60-second, single-use token with aud: realtime.

Words you’ll hear

Claim
A statement in the token payload, such as sub, exp or tenant_id.
JWKS
A published set of public keys, identified by kid, used to verify signatures.
Access vs refresh token
A short-lived credential for API calls, and a longer-lived one used to get new access tokens.
Algorithm confusion
An attack that tricks a verifier into using the wrong algorithm or key type.

Visual diagram

Loading interactive diagram

Theory & deep dive

Structure, signing and validation

A JWT is base64url(header).base64url(payload).base64url(signature). The header names the algorithm (alg) and key (kid); the payload holds registered claims (iss, sub, aud, exp, nbf, iat, jti) plus your own; the signature covers the first two parts. HS256 uses one shared secret (simple, but every verifier can also forge tokens), while RS256 or ES256 use a private key to sign and a public key to verify, so many services can verify without being able to mint tokens; publish public keys in a JWKS endpoint and rotate them using kid. Base64url expands data by about a third, so a 6 to 8 claim token is roughly 300 to 400 bytes, sent on every request.

Validation is where most vulnerabilities live. Pin the algorithm and key type your verifier accepts; reject alg: none and don't let the token choose between a public-key and a shared-secret algorithm. Verify the signature first, then check exp (not expired), nbf (not before), iss (expected issuer) and aud (this service), allowing about 30 seconds of clock skew. Treat claims as untrusted until the signature passes. Use libraries rather than hand-rolling, keep keys in a secrets manager and make verification failures return 401 without revealing which check failed.

A decoded payload

{"iss":"https://auth.example.com","sub":"u_8412","aud":"api.example.com","tenant_id":"t_77","scope":"chat:write docs:read","iat":1763712000,"exp":1763712900,"jti":"a91f"}. exp − iat = 900 s = 15 minutes.

Key takeaway: Sign with asymmetric keys, pin the algorithm and validate signature, expiry, issuer and audience before trusting any claim.

Lifetimes, revocation and storage

JWTs are valid until they expire, so lifetime is your revocation latency: a 15-minute access token can be misused for up to 15 minutes after a leak. Pair it with an opaque refresh token that is stored server-side (hashed), rotated on each use (a reused old refresh token signals theft and revokes the whole family) and bound to a device or session. For immediate revocation keep a small denylist of jti values in Redis with a TTL equal to the token's remaining life (at most 15 minutes, so it stays tiny) or compare a token_version claim with a per-user counter on sensitive routes. With 10,000 active users and 15-minute tokens the refresh endpoint handles about 40,000 refreshes an hour, roughly 11 per second.

Storage in browsers: keep access tokens in memory and refresh tokens in HttpOnly; Secure; SameSite cookies; localStorage exposes tokens to any injected script. Scopes and tenancy: put tenant_id, role and coarse scopes in claims, and derive per-tenant rate limits and token budgets from the verified values; check fine-grained permissions against the database. Service-to-service calls use short-lived tokens with a distinct aud or mutual TLS rather than user tokens. Don't use JWTs for anything that needs instant, per-request revocation across huge scale unless you accept a lookup, and don't put sensitive data in the payload; if it must be hidden, use encrypted tokens (JWE) or opaque tokens with introspection.

Refresh load

10,000 active users × (60 min / 15 min) = 40,000 refreshes per hour = 11.1 per second. Moving to 5-minute tokens triples that to 120,000 per hour (33 per second) and shrinks the leak window from 15 minutes to 5.

Key takeaway: Token lifetime sets revocation latency; use rotating refresh tokens, a small denylist and safe browser storage.

How it works, step by step

Step 1 of 4
Security engineer

1. Choose algorithm and keys

Sign with ES256 or RS256, publish a JWKS with key IDs and plan key rotation.

kid + JWKS endpoint
Key numbers at this step
Avoid
shared HS256 across services

When to use it & trade-offs

What it is

A JSON Web Token (JWT) is a compact, signed string of three base64url parts, header.payload.signature. The payload carries claims: who the token is about (sub), who issued it (iss), who it is for (aud), when it was issued and when it expires (iat, exp) and application claims such as tenant_id, scope or plan. A server verifies the signature with a key it trusts, checks the claims and can then authorise the request without a database lookup, which is why JWTs suit APIs spread across many services. The payload is only encoded, not encrypted, so anyone holding the token can read it; secrets and personal data don't belong there. Good JWT practice means short-lived access tokens, rotating refresh tokens, strict validation and a plan for revocation.

Why it matters: Authentication is the front door of an AI backend: every call spends money, touches private documents and may trigger agent actions. JWTs make that check cheap and portable, which matters when a gateway, a chat service and a retrieval service all need to know the caller and tenant. Their weaknesses (they can't be recalled before they expire, and a sloppy verifier accepts forged tokens) are well known, so the details of algorithms, expiry and storage decide whether the scheme is safe.

When to reach for it

  • Authenticating user requests across gateway and microservices
  • Carrying tenant and scope information for rate limits and budgets
  • Short-lived tokens for WebSocket handshakes

When to avoid or be careful

  • Storing JWTs in localStorage
  • Putting secrets or personal data in the payload
  • Accepting whatever algorithm the token header names

Session credential types

JWT access token
Best for: Stateless API authentication across services

Strengths: No lookup per request; carries claims.

Watch out: Can't be recalled before expiry.

Opaque token with introspection
Best for: Instant revocation and hidden claims

Strengths: Revocable; reveals nothing.

Watch out: A lookup on every request.

Server-side session cookie
Best for: Browser apps on a single backend

Strengths: Simple revocation; smaller exposure.

Watch out: Shared session store; harder for third-party APIs.

Interview signals & numbers to know

When this topic comes up

  • “How do you revoke a JWT?”
  • HS256 versus RS256
  • Access and refresh token design
  • What must a verifier check?
  • Where to store tokens in a browser

Benchmarks & rules of thumb

≈ 350 bytes -
typical JWT with 6 to 8 claims
900 s -
a 15-minute access token lifetime
40,000/h ≈ 11/s -
refreshes for 10,000 users at 15-minute tokens

Common mistakes & follow-ups

Common interview mistakes

  • Trusting claims before verifying the signature.
  • Issuing long-lived access tokens because refresh is inconvenient.
  • Reading tenant_id from a request header instead of the verified token.

Likely interviewer follow-ups

  • What would you do if a token leaked?
  • How do you rotate signing keys without logging everyone out?
  • When would you use opaque tokens instead?
Interview tip: Name the checks in order (signature, algorithm, exp, iss, aud) and say lifetime equals revocation latency.
Loading hands-on exercise

Knowledge check

Loading quiz

Put it into practice

Practice related interview Q&A

Apply Authentication with JWT with generative AI interview Q&A and hands-on practice.

Open Generative AI Q&A →Tech Learn Q&A
Previous topic
WebSockets
Next topic
OAuth 2.0