Appearance
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_T2YPfNL1iTcZZuAeWfIOUcThe 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 fit | Poor fit |
|---|---|
| Short-lived API access tokens | Long browser sessions that must be revocable |
| Identity between your own services | Storing lots of user data |
| ID tokens in OpenID Connect | Anything secret, since the payload is readable |
| One-time links, such as email verification | Replacing 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.
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.
| Part | Put | Do not put |
|---|---|---|
| Header | alg, typ, kid | A key, or a URL to fetch keys from that you trust blindly |
| Payload | iss, sub, aud, exp, iat, scopes, a role | Passwords, card numbers, personal data you would not show the user |
| Signature | Computed for you | Nothing |
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.
| Kind | Example | Defined by |
|---|---|---|
| Registered | iss, sub, aud, exp, nbf, iat, jti | RFC 7519, the JWT standard |
| Public | email, name, scope, roles | An IANA registry or a standard such as OIDC |
| Private | tenant_id, plan | Your 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.
| Claim | Name | Example | Receiver must |
|---|---|---|---|
iss | Issuer | https://auth.shop.example | Match the expected issuer exactly |
sub | Subject | u_42 | Use as the identity |
aud | Audience | orders-api | Contain its own name |
exp | Expires | 1793000900 | Be in the future, allowing a few seconds of clock skew |
nbf | Not before | 1793000000 | Be in the past |
iat | Issued at | 1793000000 | Optional age check |
jti | Token ID | 9f1c… | 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)
}- Custom claims go in the constructor.
- The header names the algorithm and the key ID, so verifiers can pick the right key during rotation.
- A short lifetime, so a leaked token is useful for at most 15 minutes.
- Only accept the algorithm you expect. This blocks the
noneand algorithm-switch attacks (question 55). - Check issuer and audience, so a token from another issuer or for another API is rejected.
- Allow 5 seconds of clock difference between servers.
- Only now is the payload trustworthy.
jwtVerifythrows 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:
| Place | Who can read it |
|---|---|
Browser localStorage | Any script on the page, including injected ones |
URLs, such as ?token=… | Browser history, server logs, Referer headers |
| Logs and error trackers | Everyone with log access |
| A user's own device | The 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.
| Signing | Encryption | |
|---|---|---|
| Protects | Integrity and authenticity | Confidentiality |
| Readable by others | Yes | No |
| Detects tampering | Yes | With authenticated encryption, yes |
| With a key pair | Sign with the private key, check with the public key | Encrypt with the public key, decrypt with the private key |
| JWT format | JWS | JWE |
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.
| Standard | RFC | What it defines |
|---|---|---|
| JWT | 7519 | The claims set and registered claim names |
| JWS | 7515 | Signed container, three parts |
| JWE | 7516 | Encrypted container, five parts |
| JWK | 7517 | Keys as JSON, and key sets (JWKS) |
| JWA | 7518 | Algorithm names such as RS256 and A256GCM |
The five parts of a JWE:
- Header: the key management algorithm, such as
RSA-OAEP-256, and the content cipher, such asA256GCM. - Encrypted key: a fresh random content key, locked with the recipient's public key.
- Initialisation vector: random input that makes every encryption different.
- Ciphertext: the encrypted claims.
- 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.
| JWS | JWE | |
|---|---|---|
| Parts | 3 | 5 |
| Content visible | Yes | No |
| Main guarantee | Who issued it, unchanged | Only the recipient can read it |
| Typical use | Access tokens, ID tokens | Tokens carrying sensitive claims through a browser |
| Cost | Cheap to check | More 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.
| Algorithm | Type | Key | Signature size | Notes |
|---|---|---|---|---|
HS256 | Symmetric, HMAC | Shared secret, at least 256 bits | 32 bytes | Fast; everyone who checks can also sign |
RS256 | Asymmetric, RSA | 2048-bit or larger | 256 bytes | Most supported |
PS256 | Asymmetric, RSA-PSS | 2048-bit or larger | 256 bytes | Better padding than RS256 |
ES256 | Asymmetric, ECDSA P-256 | 256-bit | 64 bytes | Small; needs good randomness |
EdDSA | Asymmetric, Ed25519 | 256-bit | 64 bytes | Fast, deterministic |
none | No signature | Must 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.
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.
| HS256 | RS256 | |
|---|---|---|
| Keys | One secret | Private and public pair |
| Who can sign | Everyone with the secret | Only the private key holder |
| Key distribution | Secret must reach every verifier safely | Public key published openly in a JWKS |
| Speed | Very fast | Signing slower, verifying fast |
| Use when | Same service issues and checks | Many 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) | |
|---|---|---|
| Keys | 1 shared | 2: private and public |
| Verifier can forge | Yes | No |
| Key sharing | Must be secret | Public key can be published |
| Proves to a third party who signed | No, either holder could have | Yes, only the private key holder |
| Speed | Fastest | Slower to sign |
Choosing in practice:
- Signing your own session cookie or a short-lived internal token that the same service checks: HMAC with a strong secret is fine.
- 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). - Keep the private key in a KMS if you can, so even the auth server never holds it in memory (the KMS question).