JWT Fundamentals
JWT structure, header/payload/signature, signing algorithms, token expiry, claims
- Decode and interpret a JWT token structure
- Understand HMAC-SHA256 vs RSA signing trade-offs
- Handle token expiry and refresh token patterns
Table of Contents
- What is JWT?
- Where JWT is Used Today
- JWT Authentication Flow
- Before JWT — Session ID (Stateful)
- JWT vs Session ID Comparison
- JWT Structure — The Three Parts
- How the Final JWT Token is Assembled
- JWT in HTTP Requests — Bearer Token
- JWT vs JWS vs JWE — Key Distinctions
- Single Sign-On (SSO) with JWT
- Advantages of JWT
- Challenges & Security Concerns with JWT
- Token Invalidation Problem
- Payload is Encoded, Not Encrypted
- Unsecured JWT (Algorithm: None)
- JWK Injection Exploit
- Key ID (kid) and Whitelisted Keys
1. What is JWT?
Overview
JWT stands for JSON Web Token. It is an open standard (RFC 7519) that defines a compact, self-contained way for securely transmitting information between parties as a JSON object.
Definition
A JWT is a digitally signed token that encodes a set of claims (user information and metadata) as a JSON object, which can be transmitted between parties and verified for authenticity and integrity.
Why This Concept Exists
Before JWT, applications relied on session IDs stored in databases to track authenticated users. This approach has serious problems in distributed systems (discussed in Section 4). JWT was created to solve this by making authentication stateless — meaning all necessary information travels inside the token itself, with no server-side storage required.
Real-World Analogy
Think of a JWT like a government-issued ID card (Aadhaar, passport):
- The card carries your information (name, photo, DOB) — this is the payload
- It has a government seal/signature that proves it's authentic — this is the signature
- Anyone can read the card's information, but they can verify authenticity via the seal
- The card has an expiry date baked into it — no server needs to remember it
Just as you don't need to call the government every time someone shows their ID, a server doesn't need to query a database every time a JWT is presented — it just verifies the signature.
Key Property: Stateless
The most fundamental property of JWT:
- The token itself contains all the information needed (user ID, roles, expiry time)
- The server does not need to store any session state in a database
- Any server that knows the secret/public key can validate the token independently
2. Where JWT is Used Today
JWT was originally designed simply as a secure way to transmit information. Over time, it became the dominant standard in three major areas:
| Use Case | What It Means | Example |
|---|---|---|
| Authentication | Confirming user identity ("who are you?") | After login, server issues a JWT proving "this is Shreyansh" |
| Authorization | Checking permissions ("what can you do?") | JWT contains roles/scopes; server checks if user can access /admin |
| Single Sign-On (SSO) | One login grants access to multiple applications | Log in once to Google; access Gmail, Drive, YouTube without re-login |
3. JWT Authentication Flow
Here is the standard flow when JWT is used for authentication:
1Client Auth Server Resource Server (Your App)2 | | |3 |-- username/pwd ->| |4 | |-- generate JWT ------> |5 |<-- JWT token ----| |6 | | |7 |-- GET /resource (Header: Bearer <JWT>) ->|8 | | |9 | |<-- verify token -------|10 | |-- "valid" -----------> |11 |<-- resource data ----------------------- |Step-by-Step Execution
Step 1 — Login: The client sends their username and password to the Authentication Server (this can be a third-party library or your own service — many production systems use providers like Auth0, Keycloak, AWS Cognito).
Step 2 — Token Generation: The Auth Server validates the credentials. If valid, it generates a JWT token (more on structure below) and returns it to the client.
Step 3 — Client Stores Token: The client stores the JWT (typically in memory or localStorage on the browser, or secure storage on mobile).
Step 4 — Authenticated Request: When the client wants to access a protected resource, it sends the JWT in the HTTP Authorization header with every request.
Step 5 — Token Verification: The resource server receives the request. It passes the token to the Auth Server's verify API. The Auth Server checks the token's validity (signature, expiry, etc.).
Step 6 — Access Granted: If the token is valid, the Auth Server responds with "valid." The resource server then grants access and returns the requested data.
4. Before JWT Session ID (Stateful)
To appreciate why JWT exists, you must understand what came before it: Session IDs.
How Session ID Authentication Works
1Client App/Auth Server Database2 | | |3 |-- username/pwd -> | |4 | |-- INSERT session ->|5 | | {session_id, |6 | | user_id, |7 | | roles, |8 | | expiry} |9 |<-- session_id ----| |10 | | |11 |-- GET /resource | |12 | (Cookie: session_id=xyz) -> |13 | |-- SELECT * WHERE ->|14 | | session_id=xyz |15 | |<-- {user, roles, expiry}16 | |-- validate locally|17 |<-- resource data -| |Problems with Session IDs
1. Stateful Server Must Store State
When a session ID is created, all the session information is written to a database:
- The session ID (random unique key)
- User ID (who this belongs to)
- Roles/permissions
- Expiry time
This means the server maintains state for every logged-in user.
2. DB Query on Every Request
Every time the client makes a request with a session ID, the server must:
- Receive the session ID
- Query the database to fetch user info, roles, expiry
- Perform validation
- Then serve the request
This adds latency to every single API call.
3. Distributed System Problem
In modern microservices, you might have multiple servers, multiple DB clusters (master-slave replication). Consider this scenario:
1Client request hits Server A → queries DB Cluster 1 ✅2Client next request hits Server B → queries DB Cluster 2 (might be slightly behind in sync) ⚠️All databases must be kept in sync. This is complex and failure-prone. If the session DB goes down, all users are logged out.
All DB clusters must sync the session table. JWT eliminates this entire problem.
5. JWT vs Session ID Comparison
| Property | Session ID | JWT |
|---|---|---|
| State | Stateful (DB stores session) | Stateless (token is self-contained) |
| Storage | Server-side DB/cache | Client-side (token itself) |
| DB lookup on each request | Yes — always | No — never (for basic validation) |
| Distributed systems | Complex (DB sync required) | Simple (any server validates independently) |
| Expiry | Stored in DB | Baked into the token (exp claim) |
| Revocation | Easy (delete DB row) | Hard (token is valid until expiry) |
| Size | Tiny (just an ID) | Larger (encoded header + payload + sig) |
| Security | Server controls everything | Token validity must be verified carefully |
6. JWT Structure The Three Parts
A JWT token looks like this when transmitted:
1eyJhbGciOiJSUzI1NiIsInR5cCI6IkpXVCJ9.eyJzdWIiOiIxMjM0NTY3ODkwIiwibmFtZSI6IlNocmV5YW5zaCIsImVtYWlsIjoic0BleGFtcGxlLmNvbSIsInJvbGUiOiJVU0VSIiwiaWF0IjoxNjE2MjM5MDIyLCJleHAiOjE2MTYyNDI2MjJ9.SflKxwRJSMeKKF2QT4fwpMeJf36POk6yJV_adQssw5cIt has exactly three parts, separated by dots (.):
1<Header>.<Payload>.<Signature>6.1 Part 1: Header
What is it?
The header contains metadata about the token itself — specifically information about how it was signed.
Structure
1{2 "typ": "JWT",3 "alg": "RS256"4}Fields Explained
| Field | Full Name | Description |
|---|---|---|
typ | Type | Always "JWT". Identifies this as a JWT token. |
alg | Algorithm | The signing algorithm used. Common values: RS256 (RSA + SHA-256), HS256 (HMAC + SHA-256), ES256 (ECDSA) |
Algorithm Options
| Algorithm | Type | Key Used for Signing | Key Used for Verification |
|---|---|---|---|
HS256 | Symmetric (HMAC) | Secret key | Same secret key |
RS256 | Asymmetric (RSA) | Private key | Public key |
ES256 | Asymmetric (ECDSA) | Private key | Public key |
none | Unsecured | No key | No verification ⚠️ DANGEROUS |
alg: none is extremely dangerous. See Section 12.3 for the full attack explanation. Any JWT with "alg": "none" should be immediately rejected.Additional Optional Header Fields
| Field | Name | Description |
|---|---|---|
kid | Key ID | Identifies which key was used to sign (for key rotation) |
jwk | JSON Web Key | Embeds a public key — never use this for verification (see Section 12.4) |
6.2 Part 2: Payload & Claims
What is it?
The payload is the core information section of the JWT. It contains claims — statements about the user and additional metadata.
What are Claims?
Claims are simply key-value pairs in the JSON payload that carry information. They are divided into three categories:
Category 1: Registered Claims
These are reserved, standardized claim names defined by the JWT specification (RFC 7519). They have specific, well-known meanings.
| Claim | Full Name | Description | Example Value |
|---|---|---|---|
iss | Issuer | The entity that issued (created) the JWT | "https://auth.mycompany.com" |
sub | Subject | Identifies the user (usually user ID) | "1234567" |
aud | Audience | Identifies the intended recipient(s) | "mycompany-app" |
exp | Expiration Time | Unix timestamp after which the token is invalid | 1716239022 |
nbf | Not Before | Unix timestamp before which the token must not be accepted | 1716235422 |
iat | Issued At | Unix timestamp when the token was issued | 1716235422 |
jti | JWT ID | Unique identifier for this specific token | "a1b2c3d4" |
Understanding exp vs nbf:
exp: Token is invalid after this time ("expires at")nbf: Token is invalid before this time ("not valid before")- Together they define a validity window:
nbf ≤ current_time < exp
Category 2: Public Claims
These are custom claims that can be shared and understood by multiple parties. They are not standardized but should use names that are universally understood or registered with IANA.
1{2 "email": "shreyansh@example.com",3 "country": "India",4 "city": "Bengaluru",5 "firstName": "Shreyansh",6 "lastName": "Sharma"7}Anyone reading this payload understands what email, country, city mean — no special agreement needed. These are public claims.
Category 3: Private Claims
These are custom claims understood only by specific parties (typically just the auth server that created the token). Other parties (resource servers) receive these claims but don't know what they mean.
1{2 "iam": "resource-server-1"3}Example: The auth server adds an internal claim iam for its own processing purposes. When the token reaches Resource Server 1 or Resource Server 2, they see iam in the payload but have no idea what it means. Only the auth server that created the token understands it.
This differs from public claims:
country: "India"→ Any server reading this knows what country means → Public claimiam: "resource-server-1"→ Only the auth server knows whatiammeans internally → Private claim
Full Payload Example
1{2 "iss": "https://auth.mycompany.com",3 "sub": "1234567",4 "aud": "mycompany-api",5 "exp": 1716242622,6 "nbf": 1716239022,7 "iat": 1716239022,8 "jti": "a1b2c3d4-e5f6-7890",9
10 "email": "shreyansh@example.com",11 "country": "India",12 "role": "ADMIN",13
14 "iam": "internal-service-id"15}6.3 Part 3: Signature (JWS)
What is it?
The signature is the security mechanism that proves:
- The token was created by a trusted party (authenticity)
- The token has not been tampered with since it was issued (integrity)
How the Signature is Generated
Here is the exact step-by-step process:
Step 1: Base64URL encode the header
1base64url({"alg":"RS256","typ":"JWT"})2→ eyJhbGciOiJSUzI1NiIsInR5cCI6IkpXVCJ9Step 2: Base64URL encode the payload
1base64url({"sub":"1234567","email":"s@example.com",...})2→ eyJzdWIiOiIxMjM0NTY3ODkwIiwibmFtZSI6IlNocmV5YW5zaCJ9Step 3: Create the signing input (message) Concatenate encoded header + . + encoded payload:
1eyJhbGciOiJSUzI1NiIsInR5cCI6IkpXVCJ9.eyJzdWIiOiIxMjM0NTY3ODkwIiwibmFtZSI6IlNocmV5YW5zaCJ9This entire string is your message to be signed.
Step 4: Apply the signing algorithm
| If using RSA (asymmetric) | If using HMAC (symmetric) |
|---|---|
sign(message, privateKey) | sign(message, secretKey) |
Verification uses publicKey | Verification uses same secretKey |
1signature_bytes = RSA_SHA256_Sign(message, private_key)Step 5: Base64URL encode the signature
1base64url(signature_bytes)2→ SflKxwRJSMeKKF2QT4fwpMeJf36POk6yJV_adQssw5cSignature Generation Flowchart
7. How the Final JWT Token is Assembled
After generating all three parts, the final JWT is assembled as:
1base64url(header) + "." + base64url(payload) + "." + base64url(signature)Visual Breakdown:
1eyJhbGciOiJSUzI1NiIsInR5cCI6IkpXVCJ9 ← Header (blue)2.3eyJzdWIiOiIxMjM0NTY3ODkwIiwibmFtZSI6IlNocmV5YW5zaCIsImVtYWlsIjoic0BleGFtcGxlLmNvbSIsInJvbGUiOiJVU0VSIiwiaWF0IjoxNjE2MjM5MDIyLCJleHAiOjE2MTYyNDI2MjJ9 ← Payload (orange)4.5SflKxwRJSMeKKF2QT4fwpMeJf36POk6yJV_adQssw5c ← Signature (green)How Verification Works at the Receiver
When the resource server receives this JWT:
- Split the token by
.→ getheader,payload,signature - Reconstruct the message →
encoded_header + "." + encoded_payload - Verify the signature using the appropriate key:
- If RSA:
verify(message, signature, publicKey) - If HMAC:
verify(message, signature, secretKey)
- If verification passes → signature is valid → payload was not tampered with
- Check claims: Is
expin the future? Isisstrusted? Isaudcorrect? - If all checks pass → grant access
8. JWT in HTTP Requests Bearer Token
How JWT is Transmitted
JWT is always passed from client to server in the HTTP Authorization header.
Standard Format
1GET /api/v1/user/profile HTTP/1.12Host: api.mycompany.com3Authorization: Bearer eyJhbGciOiJSUzI1NiIsInR5cCI6IkpXVCJ9.eyJzdWIiOiIxMjM0NTY3ODkwIiwibmFtZSI6IlNocmV5YW5zaCJ9.SflKxwRJSMeKKF2QT4fwpMeJf36POk6yJV_adQssw5c4Content-Type: application/jsonWhy the Authorization Header?
The Authorization HTTP header is an industry standard for transmitting credentials. It's not randomly chosen — having credentials in a dedicated, known header lets servers apply specific security logic for that header.
Why `Bearer`?
The word before the token value in the Authorization header tells the server what kind of credential is being sent:
| Scheme | Format | What it means |
|---|---|---|
Basic | Basic | Username + password encoded in Base64. Server decodes it to get username:password |
Bearer | Bearer | A token (JWT) is being passed. Server knows to treat this as a token, not a credential |
1Authorization: Basic dXNlcm5hbWU6cGFzc3dvcmQ= → username:password2Authorization: Bearer eyJhbGci... → JWT tokenBearer, never with Basic. The server has different logic paths:
- Basic → decode Base64, validate username/password
- Bearer → extract token, call auth server to validate JWT9. JWT vs JWS vs JWE Key Distinctions
This is a nuanced but important distinction, especially for interviews.
| Term | Full Name | What it means |
|---|---|---|
| JWT | JSON Web Token | The parent standard. Defines the three-part structure. Can be unsecured (no signature) or secured. |
| JWS | JSON Web Signature | JWT with a cryptographic signature applied (Part 3 contains a real signature). This is what everyone actually uses. |
| JWE | JSON Web Encryption | JWT where the payload is encrypted (not just encoded). Solves the "payload is readable" problem. |
In Practice
- 99%+ of JWT usage in the wild = JWS (signed, but payload is readable)
- JWT and JWS are used interchangeably in conversations because nobody uses JWT without a signature
- JWE is used when the payload contains sensitive data that must not be readable even if intercepted
10. Single Sign-On (SSO) with JWT
What is SSO?
Single Sign-On means: login once, access multiple applications without re-entering credentials.
How JWT Enables SSO
Why this works:
- The JWT payload contains user identity information (email, name, roles)
- Each application (App 1, App 2, App 3) can verify the same JWT against the same Auth Server
- The user doesn't need to log in separately to each app
- The payload carries enough info to identify and greet the user on each app
11. Advantages of JWT
| Advantage | Explanation |
|---|---|
| Compact | The token is small enough to fit in an HTTP header. Fast to transmit. |
| Stateless | No server-side session storage. No DB required per request. |
| Self-contained | All information (user ID, roles, expiry) is inside the token itself. |
| Digitally Signed | Signature (JWS) ensures integrity. Any tampering is detectable. |
| Built-in Expiry | exp claim provides automatic expiration. No DB cleanup needed. |
| Custom Claims | Roles, permissions, and any user data can be embedded in the payload. |
| Cross-domain/Distributed | Any server with the public key can validate. Perfect for microservices. |
| Third-Party Support | Many mature auth providers (Auth0, Keycloak, AWS Cognito) handle JWT natively. |
| Enables SSO | One token works across multiple services/domains. |
12. Challenges & Security Concerns with JWT
12.1 Challenge 1: Token Invalidation
The Problem
JWT is stateless by design. The server never stores the token. This means once a JWT is issued, it remains valid until its exp time — even if:
- The user's account is compromised
- An admin wants to ban/block a user immediately
- The user logs out
Scenario: A fraud user has a JWT valid until April 21st. Today is April 15th. How do you invalidate that token?
Solutions (with Trade-offs)
◆ Solution 1: Token Blacklist
Maintain a list of revoked token IDs (jti claim) in a cache (Redis) or DB.
1Auth Server → maintains:2 blacklisted_tokens: {3 "a1b2c3d4": { revoked_at: "2024-04-15", reason: "fraud" }4 }5
6On each request: check if jti is in blacklist → reject if foundPro: Targeted — only the specific token is invalidated Con: Requires a cache/DB lookup on every request → you've reintroduced the problem that JWT was meant to solve
◆ Solution 2: Change the Signing Key
Rotate the RSA key pair or HMAC secret. Tokens signed with the old private key will fail verification with the new public key.
Pro: All old tokens instantly invalid Con: All genuine users are also logged out. They must re-authenticate. This is a nuclear option — affects everyone, not just the fraud user.
◆ Solution 3: Short-lived Tokens (Most Popular)
Issue tokens with a very short expiry — 5 to 15 minutes. After expiry, the client must get a new token (using a refresh token, which is a longer-lived, securely stored token).
Pro: Limits the damage window to 5 minutes Con: The fraud window still exists for up to 5 minutes. Requires refresh token infrastructure.
◆ Solution 4: One-time Use Tokens
Each JWT can only be used once. The jti is tracked after first use.
Pro: Even if token is stolen, it can only be used once Con: Requires storing used jti values in cache — again, DB/cache lookup required
Most Production Systems Combine: Short-lived tokens + one-time use per request, or short-lived tokens + token blacklist for critical revocations.
12.2 Challenge 2: Payload is Encoded, Not Encrypted
The Problem
The JWT payload is Base64URL encoded, which is a completely reversible operation. Anyone who intercepts a JWT can decode the payload and read all the claims.
1# Decode JWT payload manually:2echo "eyJzdWIiOiIxMjM0NTY3ODkwIiwibmFtZSI6IlNocmV5YW5zaCJ9" | base64 -d3# Output: {"sub":"1234567890","name":"Shreyansh"}If someone intercepts your JWT, they can read: user ID, email, roles, and any other claims.
The Solution: JWE (JSON Web Encryption)
JWE encrypts the payload instead of just encoding it. Structure is different from JWS:
1JWE = base64url(header) . base64url(encrypted_key) . base64url(IV) . base64url(ciphertext) . base64url(auth_tag)- Payload is encrypted using the recipient's public key (RSA)
- Only the auth server (holding the private key) can decrypt it
- The payload is completely unreadable to anyone intercepting the token
12.3 Challenge 3: Unsecured JWT "Algorithm: None" Attack
The Problem
The JWT spec allows a special value "alg": "none" in the header, meaning no signature is applied.
1{2 "typ": "JWT",3 "alg": "none"4}A token with this header has no signature (the third part is empty):
1eyJ0eXAiOiJKV1QiLCJhbGciOiJub25lIn0.eyJzdWIiOiIxMjM0NSIsImFkbWluIjp0cnVlfQ.(Note the trailing dot with nothing after it — empty signature)
The Attack
An attacker can:
- Take a legitimate JWT
- Decode the payload
- Modify claims (e.g., change
"role": "USER"to"role": "ADMIN") - Re-encode with
"alg": "none"and no signature - Submit this modified token
If the server accepts alg: none, it will accept the forged token without any signature verification — a complete authentication bypass.
The Fix
Any JWT with "alg": "none" must be immediately rejected. The server should explicitly whitelist allowed algorithms and reject anything else.
1// Example: Spring Security JWT validation2@Bean3public JwtDecoder jwtDecoder() {4 return NimbusJwtDecoder.withPublicKey(rsaPublicKey())5 .signatureAlgorithm(SignatureAlgorithm.RS256) // Only allow RS2566 .build();7}alg: none tokens without explicit configuration is insecure.12.4 Challenge 4: JWK Injection Exploit
Background: What is JWK?
JWK (JSON Web Key) is a standard format for representing cryptographic keys as JSON. Sometimes a JWT header includes a jwk field containing the public key to use for verification:
1{2 "typ": "JWT",3 "alg": "RS256",4 "jwk": {5 "kty": "RSA",6 "n": "...", ← Modulus (part of public key)7 "e": "AQAB" ← Exponent (part of public key)8 }9}The Attack
An attacker can:
- Generate their own RSA key pair (attacker's private key + attacker's public key)
- Modify the JWT payload (e.g., elevate privileges)
- Sign the token with their own private key
- Embed their own public key in the JWT header's
jwkfield - Submit this token
If the server naively uses the public key from the jwk header field to verify the token:
- Signature verification succeeds (it was signed with the attacker's private key, verified with the attacker's public key)
- But the payload has been tampered with by the attacker
The Fix: Use Kid + Whitelisted Keys
Never use the public key provided in the JWT header's jwk field for verification.
Instead, use the kid (Key ID) claim combined with a pre-established, server-controlled list of trusted public keys.
12.5 `kid` (Key ID) & Whitelisted Public Keys
How Key ID Works
Every reputable auth server maintains a JWKS (JSON Web Key Set) endpoint — a publicly accessible URL that lists all valid public keys:
1https://auth.mycompany.com/.well-known/jwks.jsonThis returns something like:
1{2 "keys": [3 {4 "kty": "RSA",5 "kid": "key-id-001",6 "n": "...",7 "e": "AQAB"8 },9 {10 "kty": "RSA",11 "kid": "key-id-002",12 "n": "...",13 "e": "AQAB"14 }15 ]16}When the auth server issues a JWT, it includes the kid in the header:
1{2 "typ": "JWT",3 "alg": "RS256",4 "kid": "key-id-001"5}When a resource server receives this JWT, it:
- Reads the
kidfrom the header - Looks up
kid: "key-id-001"in the auth server's JWKS endpoint - Gets the corresponding trusted public key
- Verifies the JWT signature with that key
Security Properties
- The JWKS endpoint is controlled by the auth server — not the attacker
- Public keys listed there are whitelisted by the auth server
- An attacker cannot inject their public key into the auth server's JWKS without compromising the auth server itself
- This is why choosing a reputable, security-hardened auth provider (Auth0, Keycloak, AWS Cognito) is important
kid: If an attacker can somehow inject their own kid and corresponding key into the auth server's JWKS endpoint (e.g., through a vulnerability in the auth server), they could forge tokens. This is why auth servers must be hardened and regularly updated.13. Interview Notes
Common Interview Questions on JWT
Basics
| Question | Key Points to Cover |
|---|---|
| What is JWT? | Self-contained, stateless token. Header + Payload + Signature. JSON-based. |
| What are the three parts of a JWT? | Header (metadata/algo), Payload (claims), Signature (integrity proof) |
| What is the difference between authentication and authorization? | Authentication = who you are, Authorization = what you can do |
| Why is JWT called stateless? | Token carries all info; server doesn't store any session state |
JWT vs Session
| Question | Key Points |
|---|---|
| JWT vs Session ID? | Session: stateful, DB-dependent, complex in distributed systems. JWT: stateless, self-contained, distributed-friendly |
| When would you choose session over JWT? | When you need instant revocation, for simpler single-server apps |
Structure & Security
| Question | Key Points |
|---|---|
| What are registered claims in JWT? | iss, sub, aud, exp, nbf, iat, jti — standardized, predefined meaning |
| Is JWT encrypted? | No — it's Base64URL encoded (readable). Use JWE for encryption |
| What is JWS? | JWT with cryptographic signature. JWT and JWS are used interchangeably |
| What is JWE? | JWT with encrypted payload |
What is the alg: none attack? | Attacker forges token with no signature + no algorithm. Must reject these tokens |
| What is the JWK injection attack? | Attacker embeds own public key in JWT header. Never verify using key from JWT's own header |
Advanced / Tricky
| Question | Key Points |
|---|---|
| How do you implement SSO using JWT? | One auth server issues JWT. Multiple apps verify same token. User logs in once. |
| How do you invalidate a JWT before expiry? | Blacklist (jti in cache), change signing key, use short-lived tokens, use one-time tokens |
| What is the biggest challenge with JWT? | Token invalidation — no way to revoke a valid token without additional infrastructure |
What is the kid claim? | Key ID — tells the verifier which public key to use from the auth server's JWKS endpoint |
| Why are short-lived JWT tokens recommended? | Limits the damage window if a token is compromised. Typically 5–15 minutes. |
| What is JWKS? | JSON Web Key Set — auth server's public list of trusted public keys, accessible at /.well-known/jwks.json |
14. Summary
Quick Revision Bullets
- JWT = JSON Web Token. Compact, self-contained, stateless token for transmitting information securely
- Three parts:
Header.Payload.Signature(separated by dots) - Header: metadata — token type (
JWT) and signing algorithm (RS256,HS256) - Payload: claims — user info, expiry, roles. Divided into Registered, Public, and Private claims
- Signature: cryptographic proof of integrity. Generated by signing
base64url(header).base64url(payload)with a key - JWS: JWT with a real signature. Used interchangeably with JWT in practice
- JWE: JWT with encrypted payload. Use when payload confidentiality is needed
- Stateless: no server-side session. All info in the token. No DB required for validation
- Session ID was the predecessor — stateful, DB-dependent, problematic in distributed systems
- Bearer token: JWT always passed in
Authorization: Bearerheader - SSO: One JWT from one auth server works across multiple applications
- Challenge 1 — Invalidation: JWT cannot be revoked before expiry without extra infrastructure
- Solutions: Token blacklist (jti in cache/DB), change signing key, short-lived tokens, one-time use
- Challenge 2 — Payload readable: Base64 is reversible. Never put secrets in payload
- Challenge 3 — alg:none attack: Forged tokens with no signature. Always reject
alg: none - Challenge 4 — JWK injection: Never verify using public key from JWT's own
jwkheader - kid + JWKS: Secure key management. Auth server maintains whitelisted public keys at
/.well-known/jwks.json. Resource server looks up the correct key usingkid
15. Practice Questions
Easy
- What does JWT stand for? What does each letter mean?
- List the three parts of a JWT token and what each part contains.
- What is the difference between
expandnbfclaims? - What HTTP header is JWT always passed in? What keyword precedes the token?
- What does "stateless" mean in the context of JWT?
- Name three registered claims in JWT.
- What is the difference between a public claim and a private claim?
Medium
- Explain why JWT is better than Session IDs in a distributed/microservices architecture.
- What is the step-by-step process of generating a JWT signature?
- How does Single Sign-On (SSO) work using JWT?
- You are designing an API. A user logs in and receives a JWT. Draw the complete request-response flow for them to access a protected resource.
- Explain the
alg: noneattack. How do you defend against it? - What is JWE? When would you use it over standard JWS?
- What is the difference between JWT, JWS, and JWE?
Hard
- A fraud user is detected. Their JWT is valid for 6 more days. What are your options to invalidate their token? Discuss the trade-offs of each approach.
- Explain the JWK injection exploit in detail. How does an attacker exploit it? What is the correct defence using
kidand JWKS? - An interviewer asks: "JWT is stateless, which means you can't invalidate tokens. But token blacklisting uses a cache, which is stateful. Isn't that contradicting the purpose of JWT?" — How do you respond?
- Your system uses RSA for JWT signing. You decide to rotate the signing keys. What is the impact on existing tokens? How do you handle a smooth key rotation without logging everyone out?
- Design a JWT-based authentication system for a banking application. Consider: security requirements, token lifetime, key management, invalidation strategy, and whether to use JWS or JWE for different token types.
- Compare and contrast JWT token invalidation strategies for: (a) a fraud case requiring immediate ban, (b) a normal user logout, (c) a compromised secret key scenario.
Practice & Implement
Apply what you learned in JWT Fundamentals
A JWT has 3 parts separated by dots: header.payload.signature (all Base64-encoded). Simulate encoding and decoding the header and payload using Java's `java.util.Base64`.
Token: eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJzdWIiOiJ1c2VyMTIzIiwicm9sZSI6IkFETUlOIn0.signature
{"alg":"HS256","typ":"JWT"}
{"sub":"user123","role":"ADMIN"}Mastery check
How well can you recall this?
Finished this lesson?