Skip to content

Interview PrepTokens · Core

JSON Web Tokens ​

43. What is a JSON Web Token (JWT), and why is it used? ​

The short answer

A JWT, pronounced "jot", is a compact string that carries a set of facts, called claims, in JSON, plus a signature that proves who issued them and that nobody changed them. Any service that has the right key can check a JWT on its own, without calling a database or the login server. That makes JWTs popular for API access tokens, OpenID Connect ID tokens, and passing identity between services. The price is that a JWT stays valid until it expires, even if you want to cancel it.

A concrete example. After login, the auth service gives the mobile app this token:

text
eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJzdWIiOiJ1XzQyIiwicm9sZSI6ImN1c3RvbWVyIiwiaWF0IjoxNzkzMDAwMDAwLCJleHAiOjE3OTMwMDA5MDB9.tEof62VzKMyT15foqpaL_T2YPfNL1iTcZZuAeWfIOUc

The app sends it on every API call as Authorization: Bearer eyJ…. The orders API checks the signature with its key, reads "this is user u_42, a customer, valid for 15 minutes", and answers. It never called the auth service.

Good fitPoor fit
Short-lived API access tokensLong browser sessions that must be revocable
Identity between your own servicesStoring lots of user data
ID tokens in OpenID ConnectAnything secret, since the payload is readable
One-time links, such as email verificationReplacing a database lookup you need anyway

44. What are the three parts of a signed JWT? ​

The short answer

A signed JWT is three Base64url-encoded pieces joined by dots: header.payload.signature. The header says how it was signed, such as {"alg":"HS256","typ":"JWT"}. The payload holds the claims, such as {"sub":"u_42","exp":1793000900}. The signature is computed over the first two parts with a key. Base64url is just an encoding that makes the bytes safe for URLs and headers. It is not encryption, so anyone can read the header and payload.

eyJhbGciOiJIUzI1….eyJzdWIiOiJ1XzQy….tEof62VzKMyT…header"alg": "HS256""typ": "JWT"how it was signedpayload: claims"sub": "u_42""role": "customer""iat": 1793000000"exp": 1793000900signatureHMAC-SHA256 ofheader + "." + payloadwith the secret keyproves no change
Two readable parts and a seal. Split the token at the dots and decode the first two parts with Base64url: you get plain JSON. The third part is the seal over the first two. Change one character of the payload and the seal no longer matches.

Decode it yourself, no key needed:

ts
const [h, p] = token.split('.')
JSON.parse(Buffer.from(p, 'base64url').toString())
// { sub: 'u_42', role: 'customer', iat: 1793000000, exp: 1793000900 }

That is why question 50 matters.

45. What information belongs in the JWT header, payload, and signature? ​

The short answer

The header holds only how to check the token: alg, the signing algorithm; typ, the token type such as JWT or at+jwt; and kid, which key signed it. The payload holds the claims: who issued it, who it is about, who it is for, when it expires, and a few facts the receiver needs, such as roles or scopes. The signature holds nothing you write directly: it is computed from the header and payload. Keep the payload small, non-secret and limited to what receivers really need.

PartPutDo not put
Headeralg, typ, kidA key, or a URL to fetch keys from that you trust blindly
Payloadiss, sub, aud, exp, iat, scopes, a rolePasswords, card numbers, personal data you would not show the user
SignatureComputed for youNothing

Why the header is dangerous to trust. The receiver reads alg and kid before it has verified anything, so an attacker controls them. Real attacks have set "alg": "none" or switched RS256 to HS256 (question 55). Your verifier must decide the allowed algorithms itself and only use kid to choose among keys it already trusts.

Keep tokens small. Every request carries the token. A payload stuffed with the user's full profile and fifty permissions makes every request bigger, and can exceed header size limits at proxies, often 8 KB.

46. What are JWT claims? ​

The short answer

A claim is one key-value statement in the JWT payload, such as "sub": "u_42", meaning "this token is about user u_42", or "exp": 1793000900, meaning "this token expires at that time". The issuer asserts the claims, and the signature lets receivers trust them. There are three kinds: registered claims defined by the JWT standard, such as iss, sub, aud and exp; public claims registered to avoid name clashes, such as email and name from OpenID Connect; and private claims your own systems agree on, such as tenant_id.

KindExampleDefined by
Registerediss, sub, aud, exp, nbf, iat, jtiRFC 7519, the JWT standard
Publicemail, name, scope, rolesAn IANA registry or a standard such as OIDC
Privatetenant_id, planYour own agreement between issuer and receivers

Claims are statements, not truth. They are only as reliable as the issuer and the check. A token that was signed correctly but has expired, or was issued for a different API, must still be rejected.

47. What are standard JWT claims such as iss, sub, aud, exp, nbf, and jti? ​

The short answer

iss, issuer: who created the token, such as https://auth.shop.example. sub, subject: who the token is about, a stable user or client ID. aud, audience: which API the token is for, so a token for the billing API is rejected by the orders API. exp, expiration: a Unix time after which it is invalid. nbf, not before: a time before which it is invalid. iat, issued at: when it was made. jti, JWT ID: a unique ID for this token, used to stop replays or to revoke it.

ClaimNameExampleReceiver must
issIssuerhttps://auth.shop.exampleMatch the expected issuer exactly
subSubjectu_42Use as the identity
audAudienceorders-apiContain its own name
expExpires1793000900Be in the future, allowing a few seconds of clock skew
nbfNot before1793000000Be in the past
iatIssued at1793000000Optional age check
jtiToken ID9f1c…Check against a used or revoked list when needed

Times are Unix seconds, not milliseconds. 1793000900 is 26 October 2026 at 07:48:20 UTC. Date.now() in JavaScript returns milliseconds, so compare with Math.floor(Date.now() / 1000). Mixing the two is a classic bug that makes tokens last for centuries.

Why aud matters so much. Suppose your company has one auth server and two APIs. Without an audience check, a token issued to the low-risk newsletter API is accepted by the payments API. Every API must reject tokens not meant for it.

48. What are custom JWT claims? ​

The short answer

Custom claims are any extra fields you add for your own system, such as tenant_id, roles, plan or scope. They save receivers a lookup, because the information arrives with the request. Keep them few, non-secret and stable during the token's lifetime, because a token cannot be updated once issued. To avoid clashes with standard names, use clear names or a namespace, such as https://shop.example/roles, which some identity providers require.

json
{
  "iss": "https://auth.shop.example",
  "sub": "u_42",
  "aud": "orders-api",
  "exp": 1793000900,
  "tenant_id": "acme",
  "roles": ["customer"],
  "scope": "orders:read orders:write"
}

The staleness problem. Asha's token says "roles": ["admin"]. At 10:00 her admin rights are removed. Her token still says admin until it expires at 10:15. That is the main reason access tokens are kept short. For permissions that must change instantly, check them on the server instead of reading them from the token.

49. How is a JWT signed and verified? ​

The short answer

Signing: encode the header and payload with Base64url, join them with a dot, compute a signature over that string with the key and the chosen algorithm, then append the encoded signature. Verifying: split the token, recompute or check the signature over the first two parts with the expected key and an allowed algorithm you chose, and reject on any mismatch. Then check the claims: exp, nbf, iss and aud. Only after all of that may you trust the payload.

Signing and verifying with the jose library, using a key pair:

ts
import { SignJWT, jwtVerify, importPKCS8, importSPKI } from 'jose'

const privateKey = await importPKCS8(config.JWT_PRIVATE_KEY, 'RS256')
const publicKey = await importSPKI(config.JWT_PUBLIC_KEY, 'RS256')

export async function issueAccessToken(user: User) {
  return new SignJWT({ roles: user.roles })                                     // (1)
    .setProtectedHeader({ alg: 'RS256', kid: '2026-10' })                       // (2)
    .setIssuer('https://auth.shop.example')
    .setSubject(user.id)
    .setAudience('orders-api')
    .setIssuedAt()
    .setExpirationTime('15m')                                                   // (3)
    .sign(privateKey)
}

export async function verifyAccessToken(token: string) {
  const { payload } = await jwtVerify(token, publicKey, {
    algorithms: ['RS256'],                                                      // (4)
    issuer: 'https://auth.shop.example',                                        // (5)
    audience: 'orders-api',
    clockTolerance: 5,                                                          // (6)
  })
  return payload                                                                // (7)
}
  1. Custom claims go in the constructor.
  2. The header names the algorithm and the key ID, so verifiers can pick the right key during rotation.
  3. A short lifetime, so a leaked token is useful for at most 15 minutes.
  4. Only accept the algorithm you expect. This blocks the none and algorithm-switch attacks (question 55).
  5. Check issuer and audience, so a token from another issuer or for another API is rejected.
  6. Allow 5 seconds of clock difference between servers.
  7. Only now is the payload trustworthy. jwtVerify throws on any failure.

The mistake to never make: calling a decode function and using its result. Decoding reads the payload without checking the signature, so anyone can forge it. Only use the result of a verify function.

50. Can a JWT payload be decoded, and why should it not contain secrets? ​

The short answer

Yes. Anyone who holds the token can decode the payload with one line of code, because Base64url is an encoding, not encryption. The signature only stops people from changing the payload; it does not stop them from reading it. Tokens also end up in browser storage, logs, proxy records and error reports. So never put passwords, API keys, card details or sensitive personal data in a JWT. If you truly need hidden contents, use an encrypted JWT, a JWE, or better, put an opaque ID in the token and keep the data on the server.

Where tokens leak and get read:

PlaceWho can read it
Browser localStorageAny script on the page, including injected ones
URLs, such as ?token=…Browser history, server logs, Referer headers
Logs and error trackersEveryone with log access
A user's own deviceThe user, who can read every claim about themselves

Interview tip. If asked "is a JWT secure?", answer in two parts. Integrity is protected by the signature: nobody can change it undetected. Confidentiality is not protected: everybody can read it.

51. What is the difference between signing and encryption? ​

The short answer

Signing proves who created the data and that it was not changed. Everybody can still read it. Encryption hides the data so only someone with the key can read it. On its own it does not always prove who sent it. A signed JWT is like a letter on a sealed wax stamp, readable by all but obviously tampered with if opened. An encrypted JWT is like a locked box. When you need both, you sign first, then encrypt the signed token.

SigningEncryption
ProtectsIntegrity and authenticityConfidentiality
Readable by othersYesNo
Detects tamperingYesWith authenticated encryption, yes
With a key pairSign with the private key, check with the public keyEncrypt with the public key, decrypt with the private key
JWT formatJWSJWE

Key pairs work in opposite directions. For signing, only the owner of the private key can create the signature, and anyone can check it. For encryption, anyone can lock a message with the public key, and only the owner of the private key can open it.

52. What are JSON Web Signature (JWS) and JSON Web Encryption (JWE)? ​

The short answer

They are the two standard containers behind JWTs. JWS, RFC 7515, carries content with a signature: the familiar three-part header.payload.signature. Almost every JWT you will see is a JWS. JWE, RFC 7516, carries encrypted content in five parts: header.encryptedKey.iv.ciphertext.tag. A JWT is simply a set of claims placed inside one of these containers. The family also includes JWK, a JSON format for keys, and JWA, the list of algorithm names.

StandardRFCWhat it defines
JWT7519The claims set and registered claim names
JWS7515Signed container, three parts
JWE7516Encrypted container, five parts
JWK7517Keys as JSON, and key sets (JWKS)
JWA7518Algorithm names such as RS256 and A256GCM

The five parts of a JWE:

  1. Header: the key management algorithm, such as RSA-OAEP-256, and the content cipher, such as A256GCM.
  2. Encrypted key: a fresh random content key, locked with the recipient's public key.
  3. Initialisation vector: random input that makes every encryption different.
  4. Ciphertext: the encrypted claims.
  5. Authentication tag: detects any change to the ciphertext.

53. How do JWS and JWE differ? ​

The short answer

A JWS is readable and tamper-evident: the receiver checks a signature, anyone can read the content. A JWE is unreadable without the key: only the intended recipient can decrypt it. A JWS proves the issuer; a JWE with a public-key algorithm proves nothing about the sender unless it also contains a signed token. Use JWS for nearly all access and ID tokens. Use JWE only when the token itself must carry data the holder, or the systems it passes through, must not see.

JWSJWE
Parts35
Content visibleYesNo
Main guaranteeWho issued it, unchangedOnly the recipient can read it
Typical useAccess tokens, ID tokensTokens carrying sensitive claims through a browser
CostCheap to checkMore processing; key management for recipients

A nested token gets both: sign the claims into a JWS, then encrypt that JWS into a JWE. The recipient decrypts it, then verifies the inner signature.

The usual better answer. Rather than encrypting a token, give the client an opaque random reference and keep the sensitive data on the server. That avoids JWE's complexity entirely.

54. Which algorithms are commonly used to sign JWTs? ​

The short answer

HS256, HMAC with SHA-256, uses one shared secret for signing and checking. RS256, RSA with SHA-256, uses a private key to sign and a public key to check; it is the most widely supported. ES256, ECDSA on the P-256 curve with SHA-256, works the same way with much smaller keys and signatures. EdDSA with Ed25519 is modern, fast and hard to misuse. PS256 is RSA with a safer padding scheme. Never accept none. Most identity providers sign with RS256, and newer systems often choose ES256 or EdDSA.

AlgorithmTypeKeySignature sizeNotes
HS256Symmetric, HMACShared secret, at least 256 bits32 bytesFast; everyone who checks can also sign
RS256Asymmetric, RSA2048-bit or larger256 bytesMost supported
PS256Asymmetric, RSA-PSS2048-bit or larger256 bytesBetter padding than RS256
ES256Asymmetric, ECDSA P-256256-bit64 bytesSmall; needs good randomness
EdDSAAsymmetric, Ed25519256-bit64 bytesFast, deterministic
noneNo signatureMust always be rejected

55. What is the difference between HS256 and RS256? ​

The short answer

HS256 uses one secret that both signs and verifies. Every service that checks tokens holds the secret, so every one of them could also create valid tokens, and a leak from any of them breaks everything. RS256 uses a key pair: only the auth server holds the private key and can sign, while every API checks with the public key, which is safe to publish in a JWKS endpoint. Use HS256 only when the issuer and the verifier are the same service. Use RS256 or ES256 when other services, or other companies, verify your tokens.

HS256: one shared secretauth serversecret: signsorderssecretbillingsecretreportssecretall can sign; one leak breaks allRS256: private signs, public checksauth serverprivate keyJWKS endpointpublic keyorderspublicbillingpublicreportspublicAPIs can check, never sign
Who can forge a token? On the left, every service holding the secret could mint an admin token, so a bug in the reports service compromises payments. On the right, the APIs hold only a public key, which can check signatures but never create them.

The algorithm confusion attack. An API expects RS256 and has the auth server's public key. A badly written verifier reads alg from the token header. The attacker sends a token with "alg": "HS256", signed using the public key as the HMAC secret. The public key is public, so the attacker has it. The verifier sees HS256, uses the key it has, the public key, as the secret, and the signature matches. The fix is always the same: configure allowed algorithms on the verifier, algorithms: ['RS256'], and never let the token choose.

HS256RS256
KeysOne secretPrivate and public pair
Who can signEveryone with the secretOnly the private key holder
Key distributionSecret must reach every verifier safelyPublic key published openly in a JWKS
SpeedVery fastSigning slower, verifying fast
Use whenSame service issues and checksMany services or third parties verify

56. How do symmetric and asymmetric signing differ? ​

The short answer

Symmetric signing, such as HMAC, uses one secret key for both creating and checking a signature. It is fast and simple, but anyone who can check can also forge. Asymmetric signing, such as RSA, ECDSA or Ed25519, uses a key pair: the private key creates signatures, and the public key only checks them. That lets you hand out the checking key freely, which is what makes OpenID Connect, JWKS endpoints and third-party token verification possible. The trade-off is larger signatures and slower signing.

Symmetric (HMAC)Asymmetric (RSA, ECDSA, Ed25519)
Keys1 shared2: private and public
Verifier can forgeYesNo
Key sharingMust be secretPublic key can be published
Proves to a third party who signedNo, either holder could haveYes, only the private key holder
SpeedFastestSlower to sign

Choosing in practice:

  1. Signing your own session cookie or a short-lived internal token that the same service checks: HMAC with a strong secret is fine.
  2. Tokens checked by other services, other teams or customers: asymmetric, with the public keys published at a JWKS URL and rotated by kid (the key rotation question).
  3. Keep the private key in a KMS if you can, so even the auth server never holds it in memory (the KMS question).

Combine chapters into one PDF

Pick the chapters you want. They print in the order you pick them.

Interview Prep
Authentication & Identity
Cookies & sessions
Authentication
Tokens
OAuth & OIDC
Enterprise SSO
Directories
Authorization
Other topics
Nothing picked yet