JWTs show up in almost every backend, full-stack, and security interview. The questions look easy and then get sharp fast: an interviewer who asks "what are the three parts of a JWT" is usually two follow-ups away from "so how would you revoke one." Most candidates can decode a token. Far fewer can explain why alg=none was a real vulnerability, when HS256 beats RS256, or why localStorage is a bad home for an access token. This guide covers the JWT interview questions that actually come up in coding interviews, with answers grounded in RFC 7519, the spec that defines JSON Web Tokens.
Interview Coder's AI Interview Assistant helps you practice these out loud: it gives real-time answers and explanations during technical interviews so you can check your reasoning against a correct one.
JWT Structure and Claims
These are the warm-up questions. Get them wrong and the interview gets shorter. Get them precisely right and you earn the harder questions.
1. What is a JSON Web Token (JWT)?
A JWT is a compact, URL-safe format for representing claims between two parties, defined in RFC 7519. The claims are JSON key-value pairs, and the token is signed so the receiver can verify who issued it and that nothing was tampered with — without a database lookup. That self-contained property is the whole point: a server can trust the token's contents by checking a signature. JWTs are used as API access tokens, OpenID Connect ID tokens, email verification links, and password reset tokens. One thing worth saying in an interview: JWT is a token format, not an authentication protocol. It says nothing about how tokens are issued, stored, or refreshed — that is your job to design.
2. What are the three parts of a JWT?
Header, payload, and signature, each base64url-encoded and joined with dots: header.payload.signature. The header (the JOSE header) describes the token type and signing algorithm, like {"alg": "RS256", "typ": "JWT"}. The payload holds the claims — who the user is, when the token expires, who issued it. The signature is computed over the encoded header and payload, so changing a single character in either one breaks it. You can paste any JWT into the debugger at jwt.io and read the first two parts instantly. Mention that detail — it leads naturally into the next question, which interviewers love.
3. Is the payload of a JWT encrypted?
No. This is the most common JWT misconception and a deliberate trap question. Base64url is an encoding, not encryption — anyone who gets the token can decode and read every claim in seconds, no key required. A standard signed JWT (a JWS) gives you integrity and authenticity: you know who issued it and that it was not modified. It gives you zero confidentiality. So never put passwords, PII, or anything sensitive in the payload. If you genuinely need an encrypted token, that is JWE — a separate spec — but in practice the right answer is usually "don't put secrets in the token at all."
Why they ask it: candidates who say "the payload is encrypted" reveal they have used JWTs without understanding them.
4. What are the registered claims in RFC 7519?
There are seven: iss (issuer), sub (subject — typically the user ID), aud (audience — who the token is intended for), exp (expiration time), nbf (not before), iat (issued at), and jti (JWT ID, a unique identifier for the token). All of them are optional per the spec, but their meaning is standardized so interoperating systems agree on what they mean. In any real system you should treat exp as mandatory and validate iss and aud too. Being able to list these from memory, with what each one does, is table stakes for a backend interview.
5. What is the difference between registered, public, and private claims?
Registered claims are the seven defined in RFC 7519 (iss, sub, aud, exp, nbf, iat, jti) — standardized names with standardized meanings. Public claims are custom claims meant for broad use; to avoid name collisions they should be registered with IANA or use a collision-resistant name like a URI (https://example.com/roles). Private claims are names agreed on between one producer and one consumer — userId, tenant, plan — with no collision protection. In practice most application claims are private claims, and the practical risk is two systems using the same name to mean different things.
6. What goes in the JWT header, and what is the kid parameter?
The header carries metadata about how to process the token. alg names the signing algorithm and is required. typ is conventionally "JWT". kid is a key ID: when an issuer has multiple signing keys (during rotation, for example), kid tells the verifier which public key to use for verification, typically by matching against a key set. The critical caveat: until the signature is verified, every header field is attacker-controlled input. Use kid to look up keys in your own trusted key set — never to fetch a key from an arbitrary location the token suggests. Header parameters like jku and x5u, which point to external key URLs, have been abused exactly that way.
7. How do exp, nbf, and iat work?
They are NumericDate values: seconds since the Unix epoch, as plain numbers. A verifier must reject a token when the current time is at or past exp, and before nbf if present. iat records when the token was issued and is useful for enforcing a maximum age. Two practical points worth volunteering. First, allow a small clock-skew leeway — typically a minute or less — because the issuer's and verifier's clocks are never perfectly synced. Second, a classic real-world bug: generating exp in milliseconds (JavaScript's Date.now()) instead of seconds, which produces tokens that "expire" 50,000 years from now. Saying that out loud signals you have actually shipped this.
8. How do JWT, JWS, and JWE relate to each other?
JWT (RFC 7519) defines the claims format — what the JSON payload means. JWS, RFC 7515, defines how to sign content; JWE, RFC 7516, defines how to encrypt it. Nearly every JWT you meet in the wild is a JWS in compact serialization: three dot-separated parts, signed, readable by anyone. A JWE token has five parts and its payload is actually encrypted — used when the claims themselves are sensitive, which is rare in typical auth flows. The clean interview phrasing: "JWT is the what, JWS and JWE are the how — signed or encrypted."
Signing Algorithms: HS256 vs RS256
The single most common JWT system-design follow-up. Interviewers use it to check whether you understand symmetric versus asymmetric cryptography at a working level.
9. How does HS256 work?
HS256 is HMAC with SHA-256 — a symmetric scheme. One shared secret both creates and verifies the signature: the signer computes an HMAC over header.payload with the secret, and the verifier recomputes it and compares. The consequence interviewers want you to state: anyone who can verify a token can also forge one, because verification requires the same secret that signs. That makes HS256 fine when a single service issues and consumes its own tokens, and dangerous the moment you hand the secret to a second team, a third-party, or a less-trusted service. It is fast and the signatures are small, which is why it remains the default in many tutorials.
10. How does RS256 work?
RS256 is RSASSA-PKCS1-v1_5 with SHA-256 — an asymmetric scheme. The issuer signs with an RSA private key; anyone with the corresponding public key can verify. Verifiers cannot mint tokens, which is the property that matters: you can publish the public key openly (typically via a JWKS endpoint) and let dozens of services validate tokens without any of them being able to forge one. Costs: RSA signatures are large (256 bytes for a 2048-bit key versus 32 for HS256) and signing is slower. Verification, which is what most services do, is cheap.
11. When would you choose RS256 over HS256?
The blunt rule: if more than one party verifies tokens, use an asymmetric algorithm. RS256 (or ES256) is right when multiple microservices validate the same tokens, when a third party needs to verify your tokens, or when you use an identity provider — sharing an HMAC secret across all of those means every one of them can forge tokens, and one leaked secret compromises everything. HS256 is right for a monolith or a single service issuing tokens for itself: simpler key management, faster, smaller tokens. A good closing line: "the question isn't which algorithm is stronger, it's how many parties hold the verification key and whether they should all be able to sign."
12. What about ES256 and EdDSA?
ES256 is ECDSA with the P-256 curve and SHA-256: asymmetric like RS256, but with much smaller keys and signatures (64 bytes versus 256) and good performance, which matters when tokens travel on every request. EdDSA with Ed25519 is the most modern option: fast, compact, and deterministic, which removes ECDSA's classic footgun of nonce reuse leaking the private key. So why does RS256 still dominate? Ecosystem inertia — it is the default in most identity providers and supported everywhere, while EdDSA support in libraries and IdPs is still uneven. A reasonable 2026 answer: prefer ES256 or EdDSA for new systems where you control both ends; accept RS256 where compatibility decides.
13. What is a JWKS endpoint and how does key rotation work?
A JWKS (JSON Web Key Set) is a document of public keys, in the JWK format from RFC 7517, served over HTTPS by the issuer — identity providers expose it at a URL listed in their discovery document. Each key carries a kid. Verifiers fetch the set, cache it, and match the token's kid to pick the right key. Rotation then needs no coordination: the issuer adds a new key to the set, starts signing with it, and keeps the old key published until all tokens signed with it have expired. Then it removes the old key. Mention caching behavior — refreshing the JWKS on an unknown kid, with rate limits — to show production experience.
Validation and Common Vulnerabilities
This is where JWT questions overlap with cybersecurity interview questions. The attacks below are not theoretical — all of them have hit real products.
14. What checks must a server perform when validating a JWT?
In order: verify the signature using the algorithm and key your server configuration expects — not whatever the token's header claims; reject the token if exp has passed or nbf has not arrived, with a small leeway; check iss matches the issuer you trust; check aud includes your service's identifier; then, and only then, read the claims and make authorization decisions. Anything missing or unexpected means reject. The ordering matters: a surprising number of bugs come from code that reads sub or roles from the payload before the signature check, which means acting on attacker-controlled data. Validation is allowlist thinking — accept exactly one issuer, one audience, one or two algorithms.
15. What is the alg=none attack?
RFC 7519 allows "unsecured" JWTs: alg set to none with an empty signature, intended for contexts where integrity is handled elsewhere. Early JWT libraries honored that header unconditionally. The attack: take any token, decode it, change the claims to whatever you want — "admin": true — set alg to none, strip the signature, and send it. A vulnerable verifier sees none, skips signature verification, and accepts the forged claims. The fix is configuration, not cryptography: the server decides which algorithms it accepts, and none is never on that list. Modern libraries reject it by default, and RFC 8725 makes the prohibition explicit.
Why they ask it: it is the canonical example of trusting attacker-controlled metadata, which generalizes far beyond JWTs.
16. What is the HS256/RS256 key confusion attack?
Also called algorithm confusion. A server verifies RS256 tokens with an RSA public key, but its library exposes a generic verify(token, key) that picks the algorithm from the token header. The attacker crafts a token with alg: HS256 and signs it using HMAC — with the server's RSA public key, as a string, as the HMAC secret. The public key is public, so the attacker has it. The library sees HS256, treats the provided key material as an HMAC secret, recomputes the same MAC, and the forged token validates. Defenses: pin the expected algorithm explicitly, use library APIs with typed keys that refuse to use an RSA key for HMAC, and keep libraries current — modern ones block this.
17. Why should you never trust the alg header from the token?
Because it inverts the trust relationship: the token — the thing you are trying to authenticate — is telling you how to authenticate it. Until the signature is verified, the header is plain attacker input, no more trustworthy than a query parameter. Both alg=none and key confusion are the same root flaw wearing different clothes: the verifier let the message choose the verification method. The correct design is that your server configuration decides the algorithm and the key, full stop, and the token only supplies data. If a token arrives claiming a different algorithm than you expect, that is not a negotiation — it is a rejection.
18. What is a JWT replay attack and how do you mitigate it?
A stolen token is a valid token: anyone who captures it can replay it until exp, because the signature proves issuance, not who is sending it. Mitigations stack: always HTTPS so capture is hard in the first place; short expirations so a stolen token has a small window; jti plus server-side tracking to make sensitive one-shot operations (password reset, payment confirmation) single-use; and for high-security APIs, sender-constrained tokens via mutual TLS or DPoP, which bind the token to a client key so replaying it from another machine fails. A good answer names the tradeoff: jti tracking reintroduces server state, which pure JWT designs were trying to avoid.
19. How do you revoke a JWT?
You cannot un-sign one — a signed token is valid until exp no matter what the server wishes. So revocation is designed around that fact. Option one, the standard pattern: short-lived access tokens (minutes) plus refresh tokens that hit the server, where revocation checks live. Option two: a denylist of revoked jti values checked on each request — it only needs to hold entries until their tokens expire, so it stays small, but it is a lookup on every request. Option three: a per-user token-version claim, incremented in the database on password change or logout-everywhere; tokens carrying an old version are rejected. Rotating the signing key revokes everything for everyone — a blunt instrument for emergencies.
Why they ask it: revocation is JWT's structural weakness, and they want to hear you say so instead of hand-waving.
20. What makes an HS256 secret weak, and what does a strong one look like?
HMAC secrets can be brute-forced offline: one captured token gives an attacker the exact header and payload, so they can try candidate secrets at GPU speed until a computed signature matches — no requests to your server, no rate limits, no logs. Human-chosen strings like secretkey123 or a company name fall in seconds to wordlist attacks. A strong secret is at least 256 bits (32 bytes) from a cryptographically secure random generator, stored in a secret manager, rotated periodically, and never committed to a repository. If the secret is guessable, the attacker does not crack your tokens — they mint their own.
21. What does RFC 8725 recommend?
RFC 8725 is the JWT Best Current Practices document, and citing it by name lands well in interviews. Its core guidance: verifiers must use an explicit allowlist of algorithms and never accept none unless deliberately configured; validate all relevant claims — iss, aud, exp — not just the signature; use aud so a token issued for one service cannot be replayed against another (cross-service token reuse); use separate keys for separate algorithms and purposes to kill confusion attacks; treat header parameters that reference external keys (jku, x5u) with extreme suspicion; and prefer asymmetric algorithms when tokens cross trust boundaries. It is essentially a checklist of every attack from this section, inverted into rules.
Refresh Tokens, and Sessions vs JWT
Architecture questions. There is no universally right answer here, which is exactly why interviewers ask — they are testing whether you reason in tradeoffs.
22. Why pair short-lived access tokens with refresh tokens?
It splits the problem. The access token is validated statelessly on every API call — fast, no database — but lives only minutes, so theft has a short blast radius and revocation lag is bounded by its lifetime. The refresh token lives longer but is used rarely, at exactly one endpoint, where the server does hold state: it checks the token against its store, confirms the session is still alive, and can refuse. So you get cheap validation on the hot path and real revocation on the slow path. Typical numbers: access tokens of 5–15 minutes, refresh tokens of days to weeks. Stating those defaults, plus the reasoning, is what separates a memorized answer from an engineered one.
23. What is refresh token rotation and reuse detection?
Rotation: every time a refresh token is used, the server issues a new refresh token and invalidates the old one — each token works exactly once. Reuse detection is the payoff: if an already-used refresh token shows up again, two parties hold the same token, and one of them is a thief. You cannot tell which, so you revoke the entire token family and force a fresh login for that session. This turns a silent long-term compromise into a detectable event that self-heals. It is standard practice for SPAs and mobile apps in 2026, and most identity providers implement it. Mention the family/lineage tracking — that detail shows you understand the mechanism, not just the slogan.
24. JWT vs server-side sessions — what are the tradeoffs?
Sessions: the cookie holds a random ID, all state lives server-side. Instant revocation, tiny cookie, data never leaves your infrastructure — but every request needs a session lookup, and horizontal scaling requires a shared store like Redis. JWTs: claims travel in the token, validation is a signature check with no lookup, and they work cleanly across services and domains — but revocation is hard, tokens are hundreds of bytes on every request, and claims go stale until reissue. The blunt take interviewers respect: for a single monolith with one database, sessions are simpler and usually better. JWTs earn their complexity in distributed systems — a topic worth pairing with system design interview preparation.
25. Are stateless JWTs actually stateless in practice?
Mostly no, and saying so is a strong answer. Real deployments almost always reintroduce state somewhere: refresh tokens live in a database, rotation needs reuse tracking, logout-everywhere needs a denylist or token-version table, and compliance teams eventually demand the ability to kill a specific session. What JWTs genuinely buy you is statelessness on the hot path — API request validation with no lookup — while state concentrates at low-traffic points like the token endpoint. The honest framing: JWT-based auth is a caching strategy for authorization state, with exp as the TTL. You trade revocation latency for read performance. Engineers who frame it that way show they have operated one, not just tutorial-built one.
26. Where should refresh tokens be stored?
Browser apps: in an HttpOnly, Secure, SameSite cookie, path-scoped so it is only sent to the token refresh endpoint — or better, not in the browser at all, with a backend-for-frontend holding tokens server-side. Never localStorage: a refresh token is long-lived credential material, and XSS reads localStorage trivially. Mobile apps: the OS secure enclave — Keychain on iOS, Keystore on Android — never plain files or preferences. Server-side, store refresh tokens hashed, like passwords, so a database leak does not hand out live credentials. The principle that ties it together: protection should scale with lifetime, and the refresh token is the longest-lived secret in the whole flow.
27. How do you implement logout with JWTs?
Three layers, and an honest admission. Client side: delete the tokens — from memory and cookies. Server side: revoke the refresh token so no new access tokens can be minted. The admission: the current access token remains technically valid until exp, because nothing can un-sign it. With a 10-minute lifetime that window is usually acceptable; if it is not — admin consoles, banking — add a denylist check or token-version check on sensitive endpoints, accepting the lookup cost. Interviewers ask this precisely to see whether you will state the limitation plainly or pretend deleting a cookie is revocation. Say the quiet part: "logout is immediate for refresh, eventual for access."
Storage: Cookies vs localStorage, XSS and CSRF
Where frontend and security meet — this cluster is a staple of front end developer interview questions too.
28. Should you store JWTs in localStorage or cookies?
localStorage is simple and immune to CSRF (nothing is auto-sent), but any JavaScript running on your page can read it — one XSS hole and the token is exfiltrated. An HttpOnly cookie cannot be read by JavaScript, killing token theft via XSS, but the browser attaches it automatically, which opens CSRF and adds size constraints. The 2026 consensus: HttpOnly cookies with SameSite and CSRF defenses beat localStorage for anything long-lived; the strictest setup keeps tokens out of the browser entirely behind a backend-for-frontend. A defensible middle ground: access token in memory only (a JS variable), refresh token in an HttpOnly cookie. What fails the interview is "localStorage, because it's easy."
29. How does XSS threaten JWT storage?
If an attacker injects script into your page, that script runs with full access to everything your code can touch. Tokens in localStorage are exfiltrated with one line. HttpOnly cookies block the read — but here is the nuance that earns points: XSS can still ride the session. Injected script can call your API from the victim's page, cookies attached, and act as the user in real time. So HttpOnly narrows the damage from "token stolen, reusable anywhere until expiry" to "abuse only while the victim's tab is open" — meaningful, not sufficient. The conclusion to land: storage choice is mitigation, not a substitute for fixing XSS itself — output escaping, framework defaults, and a Content Security Policy.
30. How does CSRF apply to cookie-stored JWTs?
If the JWT rides in a cookie, the browser attaches it to requests triggered from other sites — a hidden form auto-submitted from a malicious page hits your API authenticated as the victim. The attacker never sees the token; they just spend it. Defenses: SameSite=Lax (a sane default — cookies are withheld from most cross-site requests) or Strict; anti-CSRF tokens, where state-changing requests must carry a value that foreign pages cannot read; validating the Origin header server-side; and never mutating state on GET. Note the symmetry, because interviewers probe it: localStorage tokens are CSRF-immune but XSS-stealable, cookie tokens are XSS-read-proof but CSRF-prone. Each storage choice picks which defense you must build.
31. What cookie attributes should you set on a token cookie?
HttpOnly so script cannot read it. Secure so it only travels over HTTPS. SameSite=Lax or Strict to cut off most cross-site sending. A tight Path — a refresh token cookie should only be sent to the refresh endpoint, not every request. A sensible Max-Age aligned with the token's actual lifetime. And the underused one that signals depth: the __Host- name prefix, which makes the browser enforce Secure, no Domain attribute, and Path=/ — preventing subdomains or insecure contexts from planting a lookalike cookie. Reciting these unprompted, with the reason for each, reads as production experience rather than blog-post knowledge.
Real-World Auth Flow Design
The final boss of JWT interviews: "design the auth for our app." These questions test synthesis — everything above, assembled under constraints. They come up constantly in Node.js interviews and any backend role.
32. Walk me through a complete JWT auth flow for a SPA and API.
User signs in — credentials to your auth endpoint, or an OAuth 2.0 Authorization Code flow with PKCE against an identity provider. The server issues a short-lived access token (10 minutes, RS256 or ES256 if multiple services verify) and a refresh token. The SPA keeps the access token in memory only; the refresh token sits in an HttpOnly, Secure, SameSite=Lax cookie path-scoped to the refresh endpoint. Every API call carries Authorization: Bearer <token>; the API validates signature, exp, iss, and aud against cached JWKS keys. On 401 or a timer, the SPA silently calls refresh; tokens rotate, reuse is detected. Logout revokes the refresh token and drops the access token. Each choice answers a specific attack — be ready to say which.
33. How do JWTs work in a microservices architecture?
Two validation models. Gateway-validates: the API gateway checks the token once and forwards trusted context — fewer checks, but everything behind the gateway must be sealed off. Zero-trust: every service validates the JWT itself against cached JWKS keys — more robust, and the asymmetric algorithm earns its keep since no service holds signing capability. Use a distinct aud per service so a token for the orders API cannot be replayed against the payments API. Avoid forwarding the user's original token through six hops; for service-to-service calls, exchange it for a narrower internal token (OAuth 2.0 Token Exchange) or use separate workload credentials. Keep lifetimes short and clocks synced — claim validation depends on both.
34. What is the difference between an ID token and an access token in OIDC?
An ID token is for the client application: it is always a JWT, its aud is the client ID, and it answers "who just authenticated, when, and how." The client reads it; APIs should never accept it for authorization. An access token is for the resource server: it answers "what is this caller allowed to do," its audience is the API, and the spec does not even require it to be a JWT — it may be opaque, validated by introspection. The classic mistake — sending ID tokens to APIs as bearer credentials — breaks audience checks and shows up in real codebases constantly, which is exactly why interviewers probe this distinction.
Why they ask it: confusing authentication ("who you are") with authorization ("what you may do") is the most common conceptual error in auth design.
35. How would you migrate a session-based app to JWTs — or should you?
Start by interrogating the requirement, out loud: if the app is one monolith, the honest recommendation is to keep sessions — they already provide instant revocation with less machinery. If services genuinely multiply, migrate incrementally. A backend-for-frontend works well as the bridge: the browser keeps its familiar session cookie, while the BFF holds JWTs server-side and attaches them to downstream API calls — token-based architecture inside, zero token exposure in the browser. Alternatively, dual-issue: mint JWTs alongside sessions, move services to token validation one at a time, retire sessions last. Keep session-style instant revocation for high-risk surfaces like admin panels. Pushing back on the premise, then giving a path anyway, is a senior-level answer.
Final Word
Most JWT interview failures are not knowledge gaps — they are precision gaps. "It's encrypted" instead of "it's signed and readable." "Just delete the token" instead of "revocation needs design because signatures can't be recalled." Drill the vocabulary until it is exact: claims, JWS versus JWE, algorithm allowlists, rotation, reuse detection. Then practice saying tradeoffs out loud, because every strong answer above is a tradeoff stated plainly. For the broader plan around questions like these, see our guide to software engineer interview prep.
If you want backup during the live rounds themselves, Interview Coder is a desktop app that gives you real-time answers during technical interviews, with coding answers powered by Claude Sonnet 4.6, Anthropic's latest Sonnet model. There is a free tier to try it; paid plans are $299/month or a one-time $799 for lifetime access.


