Definition
- JWT (JSON Web Token) is a compact, self-contained token with three Base64URL-encoded parts: header, payload, and signature.
- Validation means verifying the signature (token was not tampered with), the
expclaim (token has not expired), theissclaim (issued by a trusted server), and theaudclaim (intended for this service). - Access token is a short-lived JWT (15-30 minutes) that authorizes API requests.
- Refresh token is a long-lived opaque token that obtains new access tokens without requiring the user to log in again.
- Key rotation is the practice of periodically changing the signing key and publishing both old and new keys via a JWKS (JSON Web Key Set) endpoint.
Think of the National Bank of India security pass. The access token is a day pass that expires at the end of the business day. The guard (API server) checks the pass has a valid stamp (signature), is not expired (expiration), and was issued by the authorized security desk (issuer). The refresh token is a permanent employee badge stored in the locker. When the day pass expires, you show the badge to get a new day pass without going through the full background check again. Key rotation is like changing the stamp design every quarter: passes with the old stamp are still valid until they expire, but new passes use the new stamp.
Understanding the Concepts
How does JWT validation work?
When a client sends a request with a JWT in the Authorization header, the server performs these validation steps:
- Parse the token into header, payload, and signature.
- Read the
alg(algorithm) andkid(key ID) from the header. - Fetch the public key from the JWKS endpoint using the
kid. - Verify the signature using the public key and algorithm.
- Check
exp(expiration): reject if the token has expired. - Check
iss(issuer): reject if not from the trusted authorization server. - Check
aud(audience): reject if not intended for this service. - Extract claims (user ID, roles) and proceed with the request.
package com.bank.security;
import java.time.Instant;
import java.util.Base64;
public class JWTValidationDemo {
public static void main(String[] args) {
// Simulated JWT payload (decoded)
String header = "{\"alg\":\"RS256\",\"kid\":\"key-2025-q1\"}";
String payload = "{" +
"\"sub\":\"rajesh\"," +
"\"iss\":\"https://auth.nationalbank.in\"," +
"\"aud\":\"transfer-service\"," +
"\"exp\":" + (Instant.now().getEpochSecond() + 1800) + "," +
"\"roles\":[\"CUSTOMER\",\"TRANSFER\"]}";
System.out.println("JWT Validation Steps:");
System.out.println();
System.out.println("1. Parse header: " + header);
System.out.println("2. Algorithm: RS256, Key ID: key-2025-q1");
System.out.println("3. Fetch public key from JWKS endpoint");
System.out.println("4. Verify signature: VALID");
System.out.println("5. Check exp: " + Instant.now().plusSeconds(1800) + " (not expired)");
System.out.println("6. Check iss: https://auth.nationalbank.in (trusted)");
System.out.println("7. Check aud: transfer-service (correct)");
System.out.println("8. Extract claims: sub=rajesh, roles=[CUSTOMER, TRANSFER]");
System.out.println();
System.out.println("Result: Token is valid. Proceed with request.");
}
}
JWT Validation Steps:
1. Parse header: {"alg":"RS256","kid":"key-2025-q1"}
2. Algorithm: RS256, Key ID: key-2025-q1
3. Fetch public key from JWKS endpoint
4. Verify signature: VALID
5. Check exp: 2025-01-15T11:30:00Z (not expired)
6. Check iss: https://auth.nationalbank.in (trusted)
7. Check aud: transfer-service (correct)
8. Extract claims: sub=rajesh, roles=[CUSTOMER, TRANSFER]
Result: Token is valid. Proceed with request.
How do access tokens and refresh tokens work together?
Access tokens are short-lived (15-30 minutes). When they expire, the client uses the refresh token to get a new access token without asking the user to log in again.
package com.bank.security;
import java.time.Instant;
import java.time.temporal.ChronoUnit;
public class TokenLifecycleDemo {
public static void main(String[] args) {
Instant now = Instant.now();
System.out.println("Token Lifecycle:");
System.out.println();
System.out.println("1. Rajesh logs in with username + password");
System.out.println("2. Auth server returns:");
System.out.println(" Access token: expires " + now.plus(30, ChronoUnit.MINUTES));
System.out.println(" Refresh token: expires " + now.plus(7, ChronoUnit.DAYS));
System.out.println();
System.out.println("3. Rajesh makes API calls with the access token");
System.out.println(" Authorization: Bearer <access_token>");
System.out.println();
System.out.println("4. After 30 minutes, access token expires");
System.out.println(" API returns 401 Unauthorized");
System.out.println();
System.out.println("5. Client sends refresh token to /auth/refresh");
System.out.println(" Server validates refresh token");
System.out.println(" Server issues new access token + new refresh token");
System.out.println(" Old refresh token is invalidated (rotation)");
System.out.println();
System.out.println("6. Rajesh continues without logging in again");
}
}
Token Lifecycle:
1. Rajesh logs in with username + password
2. Auth server returns:
Access token: expires 2025-01-15T11:00:00Z
Refresh token: expires 2025-01-22T10:30:00Z
3. Rajesh makes API calls with the access token
Authorization: Bearer <access_token>
4. After 30 minutes, access token expires
API returns 401 Unauthorized
5. Client sends refresh token to /auth/refresh
Server validates refresh token
Server issues new access token + new refresh token
Old refresh token is invalidated (rotation)
6. Rajesh continues without logging in again
How does key rotation work?
Key rotation changes the signing key periodically. The authorization server publishes its public keys at a JWKS (JSON Web Key Set) endpoint. During rotation, both the old and new keys are published, so tokens signed with the old key remain valid until they expire.
package com.bank.security;
public class KeyRotationDemo {
public static void main(String[] args) {
System.out.println("Key Rotation Timeline:");
System.out.println();
System.out.println("Week 1: Active key = key-2025-q1");
System.out.println(" JWKS: [key-2025-q1]");
System.out.println(" All tokens signed with key-2025-q1");
System.out.println();
System.out.println("Week 13: Rotation starts");
System.out.println(" New key generated: key-2025-q2");
System.out.println(" JWKS: [key-2025-q2, key-2025-q1] (both published)");
System.out.println(" New tokens signed with key-2025-q2");
System.out.println(" Old tokens with key-2025-q1 still validate");
System.out.println();
System.out.println("Week 14: Grace period ends");
System.out.println(" All old tokens have expired (max 30 min lifetime)");
System.out.println(" Remove key-2025-q1 from JWKS");
System.out.println(" JWKS: [key-2025-q2]");
}
}
Key Rotation Timeline:
Week 1: Active key = key-2025-q1
JWKS: [key-2025-q1]
All tokens signed with key-2025-q1
Week 13: Rotation starts
New key generated: key-2025-q2
JWKS: [key-2025-q2, key-2025-q1] (both published)
New tokens signed with key-2025-q2
Old tokens with key-2025-q1 still validate
Week 14: Grace period ends
All old tokens have expired (max 30 min lifetime)
Remove key-2025-q1 from JWKS
JWKS: [key-2025-q2]
How is symmetric (HS256) different from asymmetric (RS256) signing?
| Aspect | HS256 (HMAC) | RS256 (RSA) |
|---|---|---|
| Key type | Shared secret | Private key (sign) + Public key (verify) |
| Who can sign | Anyone with the secret | Only the auth server (has private key) |
| Who can verify | Anyone with the secret | Any service (public key is shared) |
| Key distribution | Secret must be shared carefully | Public key is published openly |
| Use case | Single service | Microservices (decentralized validation) |
| Banking recommendation | Not recommended | Recommended |
package com.bank.security;
public class SigningAlgorithmDemo {
public static void main(String[] args) {
System.out.println("HS256 (symmetric):");
System.out.println(" Auth server signs with: shared_secret");
System.out.println(" Transfer service verifies with: shared_secret");
System.out.println(" Problem: transfer service can forge tokens!");
System.out.println();
System.out.println("RS256 (asymmetric):");
System.out.println(" Auth server signs with: private_key (kept secret)");
System.out.println(" Transfer service verifies with: public_key (from JWKS)");
System.out.println(" Transfer service CANNOT forge tokens (no private key)");
System.out.println();
System.out.println("For banking microservices, always use RS256.");
}
}
HS256 (symmetric):
Auth server signs with: shared_secret
Transfer service verifies with: shared_secret
Problem: transfer service can forge tokens!
RS256 (asymmetric):
Auth server signs with: private_key (kept secret)
Transfer service verifies with: public_key (from JWKS)
Transfer service CANNOT forge tokens (no private key)
For banking microservices, always use RS256.
What are common mistakes with JWT?
Mistake 1: Using long-lived access tokens
Wrong: access tokens that last 24 hours. If stolen, the attacker has a full day.
Correct: short-lived access tokens (15-30 min) with refresh tokens for renewal.
package com.bank.security;
public class TokenExpiryMistakeDemo {
public static void main(String[] args) {
System.out.println("WRONG: Access token expires in 24 hours");
System.out.println(" Token stolen -> attacker has 24 hours of access");
System.out.println(" Cannot revoke (JWT is self-contained)");
System.out.println();
System.out.println("CORRECT: Access token expires in 15 minutes");
System.out.println(" Token stolen -> attacker has 15 minutes");
System.out.println(" Refresh token stored in HttpOnly cookie");
System.out.println(" Refresh token can be revoked server-side");
}
}
WRONG: Access token expires in 24 hours
Token stolen -> attacker has 24 hours of access
Cannot revoke (JWT is self-contained)
CORRECT: Access token expires in 15 minutes
Token stolen -> attacker has 15 minutes
Refresh token stored in HttpOnly cookie
Refresh token can be revoked server-side
How do you handle token revocation?
JWTs are stateless and self-contained. Once issued, you cannot invalidate them until they expire. For banking, you need a revocation mechanism.
package com.bank.security;
import java.util.Set;
import java.util.concurrent.ConcurrentHashMap;
public class TokenRevocationDemo {
// Token blacklist (use Redis in production)
private static final Set<String> blacklist = ConcurrentHashMap.newKeySet();
static boolean isRevoked(String tokenId) {
return blacklist.contains(tokenId);
}
static void revoke(String tokenId) {
blacklist.add(tokenId);
System.out.println("Token revoked: " + tokenId);
}
public static void main(String[] args) {
String tokenId = "jti-abc-123";
System.out.println("Before revocation:");
System.out.println(" Is revoked: " + isRevoked(tokenId));
// User logs out or admin revokes
revoke(tokenId);
System.out.println("\nAfter revocation:");
System.out.println(" Is revoked: " + isRevoked(tokenId));
System.out.println(" Next request with this token: 401 Unauthorized");
}
}
Before revocation:
Is revoked: false
Token revoked: jti-abc-123
After revocation:
Is revoked: true
Next request with this token: 401 Unauthorized
What should a senior engineer know?
- JWK thumbprint. Each key in the JWKS has a unique thumbprint (SHA-256 of the key parameters). Use the kid claim in the JWT header to select the correct key from the JWKS for validation.
- Token binding. Bind tokens to a specific client by including a fingerprint of the client's TLS certificate in the token. This prevents token theft: a stolen token only works from the original client.
- Refresh token rotation. Every time a refresh token is used, issue a new one and invalidate the old one. If an attacker steals a refresh token and the legitimate user also uses it, the reuse detection triggers and both tokens are invalidated.
- Claims minimization. Include only the minimum necessary claims in the JWT. Do not put the user's email, address, or phone number in the token. Tokens travel over the network and are stored in browsers.
- JWKS caching. Cache the JWKS response for 5-15 minutes. On a kid miss (key not found in cache), refetch the JWKS once. This handles key rotation while minimizing requests to the authorization server.
What are common interview follow-up questions?
- What is the difference between a JWT and a session cookie?
- How do you prevent JWT token theft in a browser?
- What claims should a banking JWT contain?
- How do you handle token validation in a microservices architecture?
- What is the
nonealgorithm attack and how do you prevent it?
Visual Overview
JWT Validation Flow
====================
Client API Server JWKS Endpoint
────── ────────── ─────────────
│ Authorization: │ │
│ Bearer <JWT> ──> │ Parse JWT │
│ │ Read kid from header │
│ │ Fetch public key ──> │ Returns key set
│ │ Verify signature │
│ │ Check exp, iss, aud │
│ │ Extract claims │
│ 200 OK <── │ Process request │
Access + Refresh Token Flow
============================
1. Login: user/pass ──> Auth Server ──> {access_token, refresh_token}
2. API call: access_token ──> API Server ──> 200 OK
3. Expired: access_token ──> API Server ──> 401
4. Refresh: refresh_token ──> Auth Server ──> {new_access, new_refresh}
5. Continue: new_access ──> API Server ──> 200 OK
Key Rotation
=============
Before: JWKS: [key-q1] Tokens signed with key-q1
During: JWKS: [key-q2, key-q1] New tokens: key-q2, old tokens: key-q1
After: JWKS: [key-q2] Old tokens expired, key-q1 removed
Key Takeaway
JWT validation is the gatekeeper for every API request in a banking application. Before processing a transfer or balance check, the server verifies the token's signature (it was not tampered with), expiration (it has not expired), issuer (it came from the trusted authorization server), and audience (it was meant for this service). If any check fails, the request is rejected.
Short-lived access tokens limit the damage from token theft. If an attacker steals an access token that expires in 15 minutes, they have a narrow window. Refresh tokens extend the user's session without requiring re-authentication: the client exchanges the refresh token for a new access token. Refresh token rotation invalidates the old token on each use, creating a detection mechanism for theft.
Key rotation is essential for long-running banking systems. You cannot use the same signing key forever. During rotation, both the old and new keys are published in the JWKS endpoint. Tokens signed with the old key remain valid until they expire. After the grace period, the old key is removed.
RS256 is the correct algorithm for microservices. The authorization server holds the private key and signs tokens. Every other service holds the public key and validates tokens. No service except the auth server can forge tokens. HS256 shares a single secret with every service, which means any compromised service can create valid tokens for the entire system.
One sentence to remember: validate the signature, check the expiration, use short-lived access tokens with refresh token rotation, and rotate signing keys quarterly with both keys in the JWKS during the transition.
---