JWT interview questions and answers for backend and API engineers

JWT interview questions check whether you can treat a JSON Web Token as a signed claim set rather than a magic login string: how the header, payload and signature are built, which algorithm and key verify it, which claims your API must reject on, and how you revoke or rotate something that is valid until it expires. Expect a decode-this-token warm-up, a verification checklist, questions on alg none and key confusion, and a design question about logout, refresh tokens and where the token lives in a browser.

By Published 10 min read

How JWT questions show up

Tokens come up in backend, full stack, API platform, mobile and application security interviews. Some interviewers paste a token into the chat and ask what it tells them. Others hand you a middleware function and ask what it forgot to check. Design rounds ask how a gateway and ten microservices should trust one login. The flows that produce tokens (authorization code, PKCE, client credentials) are covered in OAuth interview questions; this page goes deeper on the token itself and the code that accepts it.

  1. Decode and explainRead the header and payload out loud, name each claim, and say what the signature proves and what it does not.
  2. Review verification codeSpot a missing audience check, a trusted header algorithm, or an expiry compared in the wrong unit.
  3. Lifecycle designLifetimes, refresh, logout, revocation and key rotation for a real product.
  4. Trade-offsJWT against opaque tokens and server sessions, and what you would pick for this team.

Fundamentals: anatomy and claims

Warm-up questions for juniors and screening calls
QuestionWhat it testsWhat a strong answer shows
Walk me through a token you have never seen before.Reading tokensSplit on the dots, base64url-decode the first two segments, read alg, kid and typ from the header and the claims from the payload, and point out that none of it is trusted until the third segment verifies.
Why base64url and not plain base64?Encoding detailTokens travel in URLs and headers. base64url swaps + and / for - and _ and drops the = padding, so nothing needs escaping.
What does a valid signature prove?IntegrityThat the bytes of header and payload were produced by whoever holds the signing key and have not changed since. It says nothing about whether the user still exists or still has that role.
Registered, public and private claims?Claim typesRegistered claims have meanings defined by the JWT standard (iss, sub, aud, exp, nbf, iat, jti). Public claims use collision-resistant names. Private claims are whatever two parties agree on, such as a tenant id.
In what unit is exp expressed?Easy bugSeconds since the Unix epoch. JavaScript's Date.now() returns milliseconds, so comparing the two directly makes every token look valid for decades.
What belongs in the payload, and what never does?Data designIdentifiers, scopes and the few facts every request needs. Never passwords, card numbers, personal data the client should not see, or anything secret, because the payload is readable by anyone holding the token.
JWS, JWE and JWT: how do they relate?VocabularyJWT is the claim format. JWS is the signed wrapper most people mean. JWE encrypts the content so only the recipient can read it. A token can be signed and then encrypted (nested).
What is the typ header for?Token confusionIt labels the kind of token. Profiles such as access tokens for OAuth use a specific type so a verifier can refuse, for example, an ID token presented as an API credential.
Warm-up questions for juniors and screening calls. Scroll sideways on a small screen.

Signing algorithms and keys

  • When would you choose HMAC (HS256) over a public-key algorithm? Only when issuer and verifier are the same service or tightly trusted. Every verifier holding the shared secret can mint tokens, so it does not scale to many teams.
  • RS256 or ES256? Both sign with a private key and verify with a public one. ES256 (ECDSA on P-256) gives much shorter keys and signatures; RS256 has the widest library support. Either is a defensible answer when you name the trade-off.
  • What is EdDSA and why do some teams prefer it? Ed25519 signatures are deterministic, fast and hard to misuse, since there is no per-signature random nonce to get wrong. Support across JWT libraries is narrower, so check yours.
  • Why does ECDSA in a JWT need the raw signature format? JWS expects the two integers r and s concatenated at fixed length. Many crypto libraries default to DER encoding, which produces tokens other verifiers reject.
  • How should a verifier find the right public key? By the kid header, looked up in a key set the issuer publishes (a JWKS document) and the server caches. Unknown ids trigger one controlled refetch, not a fetch per request.
  • How long should signing keys live? Long enough that verifiers cache them, short enough that a leaked key has a bounded life. Rotation schedules vary by organization; the important part is that the procedure is rehearsed.
import { generateKeyPairSync, sign, verify } from "node:crypto";

const enc = (o) => Buffer.from(JSON.stringify(o)).toString("base64url");
const dec = (s) => JSON.parse(Buffer.from(s, "base64url"));

// The issuer keeps the private key. Verifiers get public keys by kid (a tiny JWKS).
const { privateKey, publicKey } = generateKeyPairSync("ec", { namedCurve: "P-256" });
const keys = { "k-2026-12": { alg: "ES256", key: publicKey } };

function issue(claims, kid) {
  const input = enc({ alg: "ES256", typ: "JWT", kid }) + "." + enc(claims);
  const sig = sign("sha256", Buffer.from(input), { key: privateKey, dsaEncoding: "ieee-p1363" });
  return input + "." + sig.toString("base64url");
}

function check(token, { iss, aud, now = Math.floor(Date.now() / 1000), leeway = 30 }) {
  const parts = token.split(".");
  if (parts.length !== 3) throw new Error("not a compact JWS");
  const [h, p, s] = parts;
  const header = dec(h);
  const entry = keys[header.kid];
  // The algorithm comes from our key record, never from the token alone.
  if (!entry || header.alg !== entry.alg) throw new Error("unknown key or algorithm");
  const ok = verify("sha256", Buffer.from(h + "." + p),
    { key: entry.key, dsaEncoding: "ieee-p1363" }, Buffer.from(s, "base64url"));
  if (!ok) throw new Error("bad signature");
  const c = dec(p);
  if (c.iss !== iss) throw new Error("wrong issuer");
  if (![].concat(c.aud).includes(aud)) throw new Error("wrong audience");
  if (typeof c.exp !== "number" || now - leeway >= c.exp) throw new Error("expired");
  if (typeof c.nbf === "number" && now + leeway < c.nbf) throw new Error("not yet valid");
  return c;
}

const now = Math.floor(Date.now() / 1000);
const opts = { iss: "https://id.example.com", aud: "orders-api" };
const token = issue({ ...opts, sub: "user-42", iat: now, exp: now + 300, scope: "orders:read" }, "k-2026-12");
console.log(check(token, opts).sub);                 // user-42

const [h, p, s] = token.split(".");
const attempts = {
  algNone: enc({ alg: "none", kid: "k-2026-12" }) + "." + p + ".",
  escalated: h + "." + enc({ ...dec(p), scope: "orders:admin" }) + "." + s,
  otherApi: issue({ ...opts, aud: "billing-api", sub: "user-42", exp: now + 300 }, "k-2026-12"),
  later: token,
};
for (const [name, t] of Object.entries(attempts)) {
  try { check(t, name === "later" ? { ...opts, now: now + 400 } : opts); console.log(name, "ACCEPTED"); }
  catch (e) { console.log(name, "->", e.message); }
}
// algNone -> unknown key or algorithm
// escalated -> bad signature
// otherApi -> wrong audience
// later -> expired
ES256 issue and verify with node:crypto (no libraries) to show what a JWT library does. The verifier looks up the key by kid, takes the algorithm from its own key record, then checks issuer, audience and time claims. Three forged tokens are rejected. Use a maintained library in production.

Intermediate: verification and header attacks

Questions built around a code review
QuestionWhat it testsWhat a strong answer shows
What is wrong with calling decode() and reading sub?Decode versus verifyDecoding does no checking at all. Any client can type a payload. Only a verified token's claims may drive access decisions.
List your verification checklist in order.DisciplineStructure, allowed algorithm for this key, signature, then iss, aud, exp, nbf, and finally token type and any scope your route needs. Reject on the first failure and log the reason, not the token.
The jku or x5u header points at a key URL. Should you follow it?Header injectionNot from an untrusted token. An attacker can host their own key and sign with it. Keys come only from the issuer you configured.
Could the kid value itself be an attack?Input handlingYes, if code uses it in a file path or a database query. Treat it as untrusted input and only match it against known ids.
Why does the audience check matter so much in microservices?Token replayWithout it, a token issued for a low-risk internal service is accepted by the payments API. Each service should require its own audience.
How much clock skew would you allow?Practical judgementA small window of seconds, applied to exp and nbf, plus synced clocks on every host. A large window quietly extends every token's life.
How do you handle a token that arrives in a query string?LeakageAvoid it. URLs end up in logs, browser history and referrer headers. Use the Authorization header, or a cookie for browser sessions.
What would you log when verification fails?OperationsThe reason, the kid, the issuer and a request id. Never the full token, since a log reader could replay it until it expires.
Questions built around a code review. Scroll sideways on a small screen.
  • How do you invalidate one JWT before it expires? Keep a deny list of jti values (or a per-user "tokens issued before" timestamp) in a fast store and check it on each request. That reintroduces a lookup, which is why short lifetimes are the usual first answer.
  • What do you do when a user's role changes? Claims are a snapshot from issue time. Keep access tokens short so the next refresh carries the new role, and for urgent removals use the same deny list or force re-login.
  • Where should a browser app keep its token? An HttpOnly, Secure, SameSite cookie keeps it away from scripts, at the cost of needing CSRF defenses. Local storage is readable by any script on the page, so one XSS bug exposes every token. Memory-only storage limits exposure but loses state on reload.
  • Why are big JWTs a problem? Every request carries the whole token. Stuffing permissions lists or profile data into it inflates headers, can hit proxy header limits, and leaks data to whoever sees traffic.

Refresh tokens and rotation

A common follow-up is: "Access tokens last five minutes. How does the user stay logged in for a week, and what happens if the refresh token is stolen?" The standard answer is rotation with reuse detection. Each refresh returns a new refresh token and marks the old one used. If a used token ever comes back, two parties hold copies, so the server ends the whole login session (the token family). The sketch below shows the logic.

import secrets


class RefreshStore:
    """Rotating refresh tokens with reuse detection, one family per login.
    A real store keeps a hash of each token, not the token itself."""

    def __init__(self):
        self.tokens = {}      # token -> {"family": id, "used": bool}
        self.revoked = set()  # families killed after a replay

    def login(self):
        return self._mint(secrets.token_hex(8))

    def _mint(self, family):
        token = secrets.token_urlsafe(32)
        self.tokens[token] = {"family": family, "used": False}
        return token

    def refresh(self, token):
        rec = self.tokens.get(token)
        if rec is None or rec["family"] in self.revoked:
            raise PermissionError("unknown or revoked")
        if rec["used"]:
            # An old token came back: someone else holds a copy. End the whole session.
            self.revoked.add(rec["family"])
            raise PermissionError("reuse detected, family revoked")
        rec["used"] = True
        return self._mint(rec["family"])


store = RefreshStore()
r1 = store.login()
r2 = store.refresh(r1)            # normal rotation
try:
    store.refresh(r1)             # attacker replays the stolen first token
except PermissionError as e:
    print(e)                      # reuse detected, family revoked
try:
    store.refresh(r2)             # the legitimate client is logged out too
except PermissionError as e:
    print(e)                      # unknown or revoked
Rotating refresh tokens with reuse detection, standard library only. A replayed token revokes its whole family, logging out both the attacker and the real client.
  • Should the refresh token be a JWT too? It does not need to be. It is only ever read by the issuer, so an opaque random string backed by a database row is simpler and easy to revoke.
  • Two browser tabs refresh at the same moment and one gets logged out. Why? Both sent the same refresh token; the second looked like reuse. Fixes include a short grace window for the immediately previous token or serializing refresh in the client.
  • How does logout work with stateless access tokens? Delete the refresh token server side and clear the cookie. Outstanding access tokens stay valid until they expire, which is acceptable only because they are short.

Senior and scenario questions

Design and incident scenarios
ScenarioWhat the interviewer wants to hear
Design auth for a gateway in front of twenty services.The gateway or each service verifies against the issuer's published keys, each service checks its own audience and scopes, and service-to-service calls get their own tokens rather than forwarding the user's token everywhere.
The signing key leaked an hour ago.Publish a new key and remove the old one from the key set at once, accept that every token signed with it must die, force re-authentication, check logs for tokens with that kid, and find out how it leaked.
Rotate keys with zero failed requests.Publish the new public key first, wait longer than verifier cache lifetimes, start signing with it, then retire the old key after the longest token lifetime has passed.
Product wants "log out of all devices".A per-user session version or issued-before timestamp checked on refresh and, for sensitive routes, on each request. Explain the latency cost of the lookup.
A team stores the user's email and plan tier in the token to save a database call.Fine for display hints, risky for authorization. Data goes stale, the payload is readable, and tokens grow. Keep authorization claims minimal and stable.
Would you use JWTs for a monolith with one web app?Often not. A server session in a signed cookie with a store behind it is simpler and revocable. JWTs earn their keep when many independent services must verify without calling home.
A partner integration uses a signed JWT assertion instead of a client secret.The client proves its identity by signing a short-lived assertion with its private key, and the server checks it against a registered public key. Salesforce's server-to-server JWT bearer flow is one widely used example, which matters for Lightning Web Components apps that call outside systems.
Design and incident scenarios. Scroll sideways on a small screen.

Fictional example

Answering "Our API accepted a forged token. What went wrong?"
Interviewer
Security found that a token with a modified role claim was accepted by one of our APIs. Where do you look first?
Candidate
I would read the verification code before anything else, because a valid signature cannot survive an edited payload. Three common causes: the service calls a decode function instead of verify, the library is allowed to pick the algorithm from the header so a none or HMAC token slips through, or the service trusts a key URL from the token. I would reproduce it with the forged token in a test, pin the algorithm to the key record, add audience and type checks, and then search logs for other requests that carried the same pattern. Afterwards I would add a shared verification middleware so each service does not write its own.

A one-week JWT practice plan

  • Days 1 and 2: decode a few real tokens from a test identity provider by hand, and explain every header field and claim without notes.
  • Days 3 and 4: write the verifier above in your main language, then feed it an alg: none token, a tampered payload, a token for another audience and an expired one.
  • Day 5: add refresh rotation with reuse detection and write tests for the two-tab race.
  • Day 6: sketch key rotation and "log out everywhere" on paper, with the order of steps and the cache timings.
  • Day 7: practice the JWT versus session trade-off as a two-minute spoken answer. Related loops: backend developer interview questions and OAuth interview questions.

Natively, an AI interview assistant for Mac and Windows, is handy for rehearsing these reviews. It transcribes a mock round on your computer so you can check whether you listed the audience check before you were prompted, and it can draft answer suggestions as you go. Grab a screenshot of a verification function or an error message during practice and it can read it and point at the gap. Add your résumé and the job description (Pro or the free trial) to steer suggestions toward the stack you are interviewing for, then review the saved transcript and notes afterwards.

Questions people ask

What JWT questions are asked in interviews?

Decoding a token and naming its claims, what a signature proves, HS256 versus RS256 or ES256, the checks a verifier must make, alg none and key confusion attacks, revocation, refresh token rotation and where to store tokens in a browser.

Is a JWT encrypted?

A normal signed JWT is not. The header and payload are base64url text anyone can read. Encryption needs JWE, so keep secrets and sensitive personal data out of signed tokens.

How do you revoke a JWT?

You cannot change a token already issued, so keep access tokens short, revoke the refresh token on logout, and for urgent cases check a deny list of token ids or a per-user issued-before time.

What is the difference between JWT and OAuth?

OAuth is a framework for issuing access tokens through flows such as the authorization code flow. JWT is one token format those flows can use. An OAuth server may also issue opaque tokens instead.

Where to go next

Practice with the same assistant you would use on a call: it listens, transcribes and suggests answers from your own resume and the job description.

Facts on this page were last checked on . Product details come from the Natively app itself; if something here is out of date, tell us at hello@heynatively.com.

Keep reading

Put it on your own machine.

A live-conversation assistant that runs locally. Your conversations stay on your machine.

macOS 12+ · Windows 10/11

© 2026 Natively AI Private Limited

Source-available under the Natively Personal Use Source License v1.0 · IP geolocation by DB-IP