Definition
- JWT (JSON Web Token) is a compact token format with three Base64URL-encoded parts (header.payload.signature) that carries claims about the user and is signed to prevent tampering.
- Header is the first part of the JWT; it contains the signing algorithm (e.g., HS256 for HMAC-SHA256, RS256 for RSA-SHA256) and the token type (JWT).
- Payload is the second part; it contains claims: registered claims (sub, exp, iat), public claims (roles, email), and private claims (custom data like accountNumber).
- Signature is the third part; it is computed by signing (header + payload) with a secret key (HMAC) or private key (RSA), and the server verifies it on every request.
- OncePerRequestFilter is the Spring Security filter you extend to intercept every HTTP request, extract the JWT from the Authorization: Bearer header, validate it, and populate the SecurityContext.
- Refresh token is a long-lived token (stored securely, often in a database) used to obtain a new access token without requiring the user to log in again.
Think of the National Bank of India issuing an employee ID card. When Rajesh joins the bank, he goes to HR (login endpoint) with his credentials. HR verifies his identity and issues a laminated ID card (JWT) with his name, department, role, and an expiry date printed on it. The card is signed with a security hologram (signature) that only HR can produce. Every time Rajesh enters a building (API request), the security guard (JWT filter) checks the hologram, reads the card, and grants access based on the role. No one calls HR to verify Rajesh every time (stateless). If the card expires, Rajesh goes to HR with his renewal slip (refresh token) to get a new card.
Understanding the Concepts
What is a JWT and what does it look like?
A JWT is a string with three parts separated by dots: header.payload.signature. Each part is Base64URL-encoded. The header specifies the algorithm. The payload carries claims about the user. The signature ensures the token has not been modified.
package com.bank.security;
import java.util.Base64;
public class JwtStructureDemo {
public static void main(String[] args) {
// Example JWT (for demonstration only, not a real secret)
String jwt = "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9" +
".eyJzdWIiOiJyYWplc2giLCJyb2xlIjoiTUFOQUdFUiIsImFjY291bnQiOiJTQVYyMDAxIiwiZXhwIjoxNzUzMDAwMDAwfQ" +
".SIGNATURE_PLACEHOLDER";
String[] parts = jwt.split("\\.");
System.out.println("JWT has " + parts.length + " parts:");
System.out.println();
String header = new String(Base64.getUrlDecoder().decode(parts[0]));
System.out.println("1. Header: " + header);
String payload = new String(Base64.getUrlDecoder().decode(parts[1]));
System.out.println("2. Payload: " + payload);
System.out.println("3. Signature: " + parts[2]);
System.out.println();
System.out.println("The signature is: HMAC-SHA256(base64(header) + '.' + base64(payload), secretKey)");
}
}
Expected output:
JWT has 3 parts:
1. Header: {"alg":"HS256","typ":"JWT"}
2. Payload: {"sub":"rajesh","role":"MANAGER","account":"SAV2001","exp":1753000000}
3. Signature: SIGNATURE_PLACEHOLDER
The signature is: HMAC-SHA256(base64(header) + '.' + base64(payload), secretKey)
How does the JWT authentication flow work?
The flow has two phases: login (get the token) and subsequent requests (use the token).
- Client sends POST /api/auth/login with username and password.
- Server validates credentials against the database.
- Server creates a JWT with the user's claims and signs it.
- Server returns the JWT in the response body.
- Client stores the JWT (localStorage, cookie, or memory).
- For every subsequent request, client sends: Authorization: Bearer
. - Server's JWT filter extracts the token, validates the signature and expiration, and sets the SecurityContext.
- The request proceeds to the controller with the authenticated user available.
package com.bank.security;
public class JwtFlowDemo {
public static void main(String[] args) {
System.out.println("JWT Authentication Flow:");
System.out.println();
System.out.println("Phase 1: Login");
System.out.println(" 1. POST /api/auth/login {username: 'rajesh', password: '***'}");
System.out.println(" 2. Server: validate credentials against database");
System.out.println(" 3. Server: create JWT {sub: 'rajesh', role: 'MANAGER', exp: +15min}");
System.out.println(" 4. Server: sign JWT with HMAC-SHA256(secret)");
System.out.println(" 5. Response: {token: 'eyJhbG...'}");
System.out.println();
System.out.println("Phase 2: Authenticated Requests");
System.out.println(" 6. GET /api/accounts/SAV2001");
System.out.println(" Header: Authorization: Bearer eyJhbG...");
System.out.println(" 7. JwtFilter: extract token from header");
System.out.println(" 8. JwtFilter: validate signature and expiration");
System.out.println(" 9. JwtFilter: set SecurityContext (user=rajesh, role=MANAGER)");
System.out.println(" 10. Controller: processes request with authenticated user");
}
}
Expected output:
JWT Authentication Flow:
Phase 1: Login
1. POST /api/auth/login {username: 'rajesh', password: '***'}
2. Server: validate credentials against database
3. Server: create JWT {sub: 'rajesh', role: 'MANAGER', exp: +15min}
4. Server: sign JWT with HMAC-SHA256(secret)
5. Response: {token: 'eyJhbG...'}
Phase 2: Authenticated Requests
6. GET /api/accounts/SAV2001
Header: Authorization: Bearer eyJhbG...
7. JwtFilter: extract token from header
8. JwtFilter: validate signature and expiration
9. JwtFilter: set SecurityContext (user=rajesh, role=MANAGER)
10. Controller: processes request with authenticated user
How do you implement a JWT utility class?
The JWT utility class handles token creation, parsing, and validation. It uses the jjwt library (JSON Web Token for Java).
package com.bank.security;
import io.jsonwebtoken.Claims;
import io.jsonwebtoken.JwtException;
import io.jsonwebtoken.Jwts;
import io.jsonwebtoken.security.Keys;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
import javax.crypto.SecretKey;
import java.nio.charset.StandardCharsets;
import java.time.Instant;
import java.time.temporal.ChronoUnit;
import java.util.Date;
@Component
public class JwtUtil {
private final SecretKey key;
private final long expirationMinutes;
public JwtUtil(
@Value("${jwt.secret}") String secret,
@Value("${jwt.expiration-minutes:15}") long expirationMinutes) {
this.key = Keys.hmacShaKeyFor(secret.getBytes(StandardCharsets.UTF_8));
this.expirationMinutes = expirationMinutes;
}
public String generateToken(String username, String role) {
Instant now = Instant.now();
return Jwts.builder()
.subject(username)
.claim("role", role)
.issuedAt(Date.from(now))
.expiration(Date.from(now.plus(expirationMinutes, ChronoUnit.MINUTES)))
.signWith(key)
.compact();
}
public Claims parseToken(String token) {
return Jwts.parser()
.verifyWith(key)
.build()
.parseSignedClaims(token)
.getPayload();
}
public boolean isValid(String token) {
try {
parseToken(token);
return true;
} catch (JwtException e) {
System.out.println("Invalid JWT: " + e.getMessage());
return false;
}
}
public String getUsername(String token) {
return parseToken(token).getSubject();
}
public String getRole(String token) {
return parseToken(token).get("role", String.class);
}
}
package com.bank;
import com.bank.security.JwtUtil;
public class JwtUtilDemo {
public static void main(String[] args) {
var jwtUtil = new JwtUtil("NationalBankOfIndia2025SecretKeyForHMACSHA256Signing", 15);
String token = jwtUtil.generateToken("rajesh", "MANAGER");
System.out.println("Generated token: " + token.substring(0, 50) + "...");
System.out.println("Token length: " + token.length() + " characters");
System.out.println();
System.out.println("Username: " + jwtUtil.getUsername(token));
System.out.println("Role: " + jwtUtil.getRole(token));
System.out.println("Valid: " + jwtUtil.isValid(token));
System.out.println();
System.out.println("Tampered token:");
String tampered = token.substring(0, token.length() - 5) + "XXXXX";
System.out.println("Valid: " + jwtUtil.isValid(tampered));
}
}
Expected output:
Generated token: eyJhbGciOiJIUzI1NiJ9.eyJzdWIiOiJyYWplc2...
Token length: 182 characters
Username: rajesh
Role: MANAGER
Valid: true
Tampered token:
Invalid JWT: JWT signature does not match locally computed signature.
Valid: false
How do you implement the JWT filter in Spring Security?
The JWT filter extends OncePerRequestFilter and intercepts every HTTP request. It extracts the token from the Authorization header, validates it, and populates the SecurityContext.
package com.bank.security;
import jakarta.servlet.FilterChain;
import jakarta.servlet.ServletException;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.stereotype.Component;
import org.springframework.web.filter.OncePerRequestFilter;
import java.io.IOException;
import java.util.List;
@Component
public class JwtAuthenticationFilter extends OncePerRequestFilter {
private final JwtUtil jwtUtil;
public JwtAuthenticationFilter(JwtUtil jwtUtil) {
this.jwtUtil = jwtUtil;
}
@Override
protected void doFilterInternal(
HttpServletRequest request,
HttpServletResponse response,
FilterChain filterChain) throws ServletException, IOException {
String authHeader = request.getHeader("Authorization");
if (authHeader != null && authHeader.startsWith("Bearer ")) {
String token = authHeader.substring(7);
if (jwtUtil.isValid(token)) {
String username = jwtUtil.getUsername(token);
String role = jwtUtil.getRole(token);
var authorities = List.of(new SimpleGrantedAuthority("ROLE_" + role));
var authentication = new UsernamePasswordAuthenticationToken(
username, null, authorities);
SecurityContextHolder.getContext().setAuthentication(authentication);
System.out.println("JWT authenticated: user=" + username + ", role=" + role);
}
}
filterChain.doFilter(request, response);
}
}
Expected output:
GET /api/accounts/SAV2001 with valid JWT:
JWT authenticated: user=rajesh, role=MANAGER
Response: 200 OK
GET /api/accounts/SAV2001 without JWT:
(no authentication set)
Response: 401 Unauthorized
GET /api/accounts/SAV2001 with expired JWT:
Invalid JWT: JWT expired at 2025-07-01T10:00:00Z
Response: 401 Unauthorized
How do you configure Spring Security for JWT?
The SecurityFilterChain configuration disables session creation (stateless), permits the login endpoint, requires authentication for everything else, and adds the JWT filter before the UsernamePasswordAuthenticationFilter.
package com.bank.config;
import com.bank.security.JwtAuthenticationFilter;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.config.annotation.authentication.configuration.AuthenticationConfiguration;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.http.SessionCreationPolicy;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.security.web.SecurityFilterChain;
import org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter;
@Configuration
public class SecurityConfig {
private final JwtAuthenticationFilter jwtFilter;
public SecurityConfig(JwtAuthenticationFilter jwtFilter) {
this.jwtFilter = jwtFilter;
}
@Bean
public SecurityFilterChain filterChain(HttpSecurity http) throws Exception {
return http
.csrf(csrf -> csrf.disable())
.sessionManagement(session ->
session.sessionCreationPolicy(SessionCreationPolicy.STATELESS))
.authorizeHttpRequests(auth -> auth
.requestMatchers("/api/auth/**").permitAll()
.requestMatchers("/api/admin/**").hasRole("ADMIN")
.anyRequest().authenticated())
.addFilterBefore(jwtFilter, UsernamePasswordAuthenticationFilter.class)
.build();
}
@Bean
public PasswordEncoder passwordEncoder() {
return new BCryptPasswordEncoder();
}
@Bean
public AuthenticationManager authenticationManager(
AuthenticationConfiguration config) throws Exception {
return config.getAuthenticationManager();
}
}
Expected output:
Security configuration:
/api/auth/** -> permitAll (login, register)
/api/admin/** -> ROLE_ADMIN required
everything else -> authenticated (valid JWT required)
Sessions: STATELESS (no HttpSession)
JWT filter: runs before UsernamePasswordAuthenticationFilter
What is a complete banking project with JWT authentication?
Project structure
jwt-auth-service/
├── pom.xml
└── src/
└── main/
├── java/
│ └── com/
│ └── bank/
│ ├── JwtAuthApp.java
│ ├── config/
│ │ └── SecurityConfig.java
│ ├── controller/
│ │ ├── AuthController.java
│ │ └── AccountController.java
│ ├── dto/
│ │ ├── LoginRequest.java
│ │ └── LoginResponse.java
│ ├── model/
│ │ └── BankUser.java
│ ├── repository/
│ │ └── BankUserRepository.java
│ └── security/
│ ├── JwtUtil.java
│ ├── JwtAuthenticationFilter.java
│ └── BankUserDetailsService.java
└── resources/
└── application.properties
pom.xml
<?xml version="1.0" encoding="UTF-8"?syn-kw">>
syn-kw"><project xmlns="http://maven.apache.org/POM/4.0.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0
http://maven.apache.org/xsd/maven-4.0.0.xsd"syn-kw">>
syn-kw"><modelVersionsyn-kw">>4.0.0syn-kw"></modelVersionsyn-kw">>
syn-kw"><parentsyn-kw">>
syn-kw"><groupIdsyn-kw">>org.springframework.bootsyn-kw"></groupIdsyn-kw">>
syn-kw"><artifactIdsyn-kw">>spring-boot-starter-parentsyn-kw"></artifactIdsyn-kw">>
syn-kw"><versionsyn-kw">>3.4.7syn-kw"></versionsyn-kw">>
syn-kw"></parentsyn-kw">>
syn-kw"><groupIdsyn-kw">>com.banksyn-kw"></groupIdsyn-kw">>
syn-kw"><artifactIdsyn-kw">>jwt-auth-servicesyn-kw"></artifactIdsyn-kw">>
syn-kw"><versionsyn-kw">>1.0.0syn-kw"></versionsyn-kw">>
syn-kw"><propertiessyn-kw">>
syn-kw"><java.versionsyn-kw">>25syn-kw"></java.versionsyn-kw">>
syn-kw"></propertiessyn-kw">>
syn-kw"><dependenciessyn-kw">>
syn-kw"><dependencysyn-kw">>
syn-kw"><groupIdsyn-kw">>org.springframework.bootsyn-kw"></groupIdsyn-kw">>
syn-kw"><artifactIdsyn-kw">>spring-boot-starter-websyn-kw"></artifactIdsyn-kw">>
syn-kw"></dependencysyn-kw">>
syn-kw"><dependencysyn-kw">>
syn-kw"><groupIdsyn-kw">>org.springframework.bootsyn-kw"></groupIdsyn-kw">>
syn-kw"><artifactIdsyn-kw">>spring-boot-starter-securitysyn-kw"></artifactIdsyn-kw">>
syn-kw"></dependencysyn-kw">>
syn-kw"><dependencysyn-kw">>
syn-kw"><groupIdsyn-kw">>org.springframework.bootsyn-kw"></groupIdsyn-kw">>
syn-kw"><artifactIdsyn-kw">>spring-boot-starter-data-jpasyn-kw"></artifactIdsyn-kw">>
syn-kw"></dependencysyn-kw">>
syn-kw"><dependencysyn-kw">>
syn-kw"><groupIdsyn-kw">>io.jsonwebtokensyn-kw"></groupIdsyn-kw">>
syn-kw"><artifactIdsyn-kw">>jjwt-apisyn-kw"></artifactIdsyn-kw">>
syn-kw"><versionsyn-kw">>0.12.6syn-kw"></versionsyn-kw">>
syn-kw"></dependencysyn-kw">>
syn-kw"><dependencysyn-kw">>
syn-kw"><groupIdsyn-kw">>io.jsonwebtokensyn-kw"></groupIdsyn-kw">>
syn-kw"><artifactIdsyn-kw">>jjwt-implsyn-kw"></artifactIdsyn-kw">>
syn-kw"><versionsyn-kw">>0.12.6syn-kw"></versionsyn-kw">>
syn-kw"><scopesyn-kw">>runtimesyn-kw"></scopesyn-kw">>
syn-kw"></dependencysyn-kw">>
syn-kw"><dependencysyn-kw">>
syn-kw"><groupIdsyn-kw">>io.jsonwebtokensyn-kw"></groupIdsyn-kw">>
syn-kw"><artifactIdsyn-kw">>jjwt-jacksonsyn-kw"></artifactIdsyn-kw">>
syn-kw"><versionsyn-kw">>0.12.6syn-kw"></versionsyn-kw">>
syn-kw"><scopesyn-kw">>runtimesyn-kw"></scopesyn-kw">>
syn-kw"></dependencysyn-kw">>
syn-kw"><dependencysyn-kw">>
syn-kw"><groupIdsyn-kw">>com.h2databasesyn-kw"></groupIdsyn-kw">>
syn-kw"><artifactIdsyn-kw">>h2syn-kw"></artifactIdsyn-kw">>
syn-kw"><scopesyn-kw">>runtimesyn-kw"></scopesyn-kw">>
syn-kw"></dependencysyn-kw">>
syn-kw"></dependenciessyn-kw">>
syn-kw"></projectsyn-kw">>
LoginRequest.java and LoginResponse.java (Java 25 records)
package com.bank.dto;
public record LoginRequest(String username, String password) {}
package com.bank.dto;
public record LoginResponse(String token, String username, String role, long expiresInMinutes) {}
AuthController.java
package com.bank.controller;
import com.bank.dto.LoginRequest;
import com.bank.dto.LoginResponse;
import com.bank.security.JwtUtil;
import org.springframework.http.ResponseEntity;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
@RestController
@RequestMapping("/api/auth")
public class AuthController {
private final AuthenticationManager authenticationManager;
private final JwtUtil jwtUtil;
public AuthController(AuthenticationManager authenticationManager, JwtUtil jwtUtil) {
this.authenticationManager = authenticationManager;
this.jwtUtil = jwtUtil;
}
@PostMapping("/login")
public ResponseEntity<LoginResponse> login(@RequestBody LoginRequest request) {
Authentication auth = authenticationManager.authenticate(
new UsernamePasswordAuthenticationToken(request.username(), request.password()));
String role = auth.getAuthorities().stream()
.map(GrantedAuthority::getAuthority)
.findFirst()
.orElse("ROLE_USER")
.replace("ROLE_", "");
String token = jwtUtil.generateToken(request.username(), role);
return ResponseEntity.ok(new LoginResponse(token, request.username(), role, 15));
}
}
How to test
# Step 1: Start the application
cd jwt-auth-service
mvn spring-boot:run
# Step 2: Login to get a JWT
curl -X POST http://localhost:8080/api/auth/login \
-H "Content-Type: application/json" \
-d '{"username": "rajesh", "password": "password123"}'
# Step 3: Use the JWT to access a protected endpoint
curl -X GET http://localhost:8080/api/accounts/SAV2001 \
-H "Authorization: Bearer eyJhbGciOiJIUzI1NiJ9..."
# Step 4: Try without JWT (should get 401)
curl -X GET http://localhost:8080/api/accounts/SAV2001
Expected output:
# Login response:
{"token":"eyJhbGciOiJIUzI1NiJ9...","username":"rajesh","role":"MANAGER","expiresInMinutes":15}
# Authenticated request:
JWT authenticated: user=rajesh, role=MANAGER
{"accountNumber":"SAV2001","holderName":"Priya Sharma","balance":50000}
# Unauthenticated request:
{"status":401,"error":"Unauthorized"}
What are common mistakes with JWT authentication?
Wrong: storing the secret key in source code
package com.bank.security;
public class WrongSecretStorage {
public static void main(String[] args) {
// WRONG: secret key hardcoded in Java file
System.out.println("WRONG: String secret = 'mySecretKey123' in source code");
System.out.println();
System.out.println("Problems:");
System.out.println(" 1. Secret is visible in version control (Git)");
System.out.println(" 2. Same secret across all environments (dev, staging, prod)");
System.out.println(" 3. Cannot rotate the secret without code change");
System.out.println(" 4. Anyone with repo access can forge tokens");
}
}
Expected output:
WRONG: String secret = 'mySecretKey123' in source code
Problems:
1. Secret is visible in version control (Git)
2. Same secret across all environments (dev, staging, prod)
3. Cannot rotate the secret without code change
4. Anyone with repo access can forge tokens
Correct: load secret from environment variable
package com.bank.security;
public class CorrectSecretStorage {
public static void main(String[] args) {
// CORRECT: secret from environment / secrets manager
System.out.println("CORRECT: load secret from environment variable or secrets manager");
System.out.println();
System.out.println("application.properties:");
System.out.println(" jwt.secret=${JWT_SECRET}");
System.out.println();
System.out.println("Production:");
System.out.println(" export JWT_SECRET=$(aws secretsmanager get-secret-value ...)");
System.out.println(" Or use Spring Cloud Vault, AWS Secrets Manager, or Azure Key Vault");
System.out.println();
System.out.println("Key requirements:");
System.out.println(" 1. At least 256 bits (32 bytes) for HS256");
System.out.println(" 2. Different secret per environment");
System.out.println(" 3. Rotation plan without downtime");
}
}
Expected output:
CORRECT: load secret from environment variable or secrets manager
application.properties:
jwt.secret=${JWT_SECRET}
Production:
export JWT_SECRET=$(aws secretsmanager get-secret-value ...)
Or use Spring Cloud Vault, AWS Secrets Manager, or Azure Key Vault
Key requirements:
1. At least 256 bits (32 bytes) for HS256
2. Different secret per environment
3. Rotation plan without downtime
What should a senior or principal engineer know?
At the senior level, you should understand HS256 vs RS256, token expiration strategy, and how to handle token revocation (which JWT does not natively support since it is stateless).
At the principal level, think about:
- RS256 vs HS256: HS256 uses a shared secret (both parties need the same key). RS256 uses a public/private key pair (auth server signs with private key, resource servers verify with public key). RS256 is better for microservices because resource servers never need the private key.
- Token revocation: JWTs are stateless, so you cannot "invalidate" a token. Options: short expiration (15 min), blacklist in Redis, or version claim that increments on logout.
- Refresh token rotation: when the client uses a refresh token, issue a new refresh token and invalidate the old one. This limits the damage of a stolen refresh token.
- Claims minimization: put only what you need in the JWT payload. Every claim increases token size, and the token is sent with every request.
- HTTPS only: JWTs must only travel over HTTPS. Over HTTP, anyone on the network can steal the token.
package com.bank;
public class JwtSecurityChecklist {
public static void main(String[] args) {
System.out.println("JWT Security Checklist for National Bank:");
System.out.println();
System.out.println("1. Use RS256 for microservices (public key verification)");
System.out.println("2. Access token: 15 minutes, Refresh token: 7 days");
System.out.println("3. Store refresh tokens in database with user binding");
System.out.println("4. Rotate refresh tokens on each use");
System.out.println("5. Secret key: minimum 256 bits, loaded from secrets manager");
System.out.println("6. HTTPS only, no tokens in URLs or query params");
System.out.println("7. Minimal claims: sub, role, exp (no PII like email/phone)");
System.out.println("8. Token blacklist in Redis for forced logout");
System.out.println("9. Rate limit login endpoint to prevent brute force");
System.out.println("10. Log failed JWT validations for security monitoring");
}
}
Expected output:
JWT Security Checklist for National Bank:
1. Use RS256 for microservices (public key verification)
2. Access token: 15 minutes, Refresh token: 7 days
3. Store refresh tokens in database with user binding
4. Rotate refresh tokens on each use
5. Secret key: minimum 256 bits, loaded from secrets manager
6. HTTPS only, no tokens in URLs or query params
7. Minimal claims: sub, role, exp (no PII like email/phone)
8. Token blacklist in Redis for forced logout
9. Rate limit login endpoint to prevent brute force
10. Log failed JWT validations for security monitoring
What are common interview follow-up questions?
- Where should the client store the JWT? (For SPAs: in-memory (most secure, lost on refresh), HttpOnly cookie (secure, prevents XSS access), or localStorage (convenient but vulnerable to XSS). For mobile apps: secure storage like Android Keystore or iOS Keychain.)
- Can you put sensitive data in the JWT payload? (No. The payload is Base64-encoded, not encrypted. Anyone can decode it and read the claims. Never put passwords, credit card numbers, or personal data in the payload.)
- What happens when the JWT expires? (The server returns 401 Unauthorized. The client uses the refresh token to get a new access token. If the refresh token is also expired, the user must log in again.)
- How is JWT different from session-based authentication? (Sessions store state on the server (in memory or Redis). JWT is stateless: the server stores nothing. Sessions scale poorly without sticky sessions or shared session store. JWT scales easily because any server can validate the token.)
- Can you invalidate a specific JWT before it expires? (Not directly, because JWT is stateless. Common workarounds: maintain a blacklist of revoked token IDs (jti claim) in Redis, or increment a user-specific version number in the database and check it on every request.)
Visual Overview
JWT Authentication Flow
========================
┌──────────┐ ┌──────────────┐
│ Client │ │ Server │
│ (Mobile/ │ │ (Spring Boot)│
│ Browser)│ │ │
└────┬─────┘ └──────┬───────┘
│ │
│ POST /api/auth/login │
│ {username, password} │
│ ─────────────────────────────────────> │
│ │
│ Validate credentials│
│ Create JWT │
│ Sign with secret │
│ │
│ 200 OK {token: "eyJ..."} │
│ <───────────────────────────────────── │
│ │
│ Store token │
│ │
│ GET /api/accounts/SAV2001 │
│ Authorization: Bearer eyJ... │
│ ─────────────────────────────────────> │
│ │
│ JwtFilter: │
│ Extract token │
│ Verify signature │
│ Check expiration │
│ Set SecurityContext
│ │
│ 200 OK {account data} │
│ <───────────────────────────────────── │
│ │
JWT Token Structure
====================
eyJhbGciOiJIUzI1NiJ9.eyJzdWIiOiJyYWplc2giLCJyb2xlIjoiTUFOQUdFUiJ9.HMAC_SIGNATURE
├──────────────────┤ ├──────────────────────────────────────────────┤ ├──────────────┤
Header Payload Signature
{"alg":"HS256"} {"sub":"rajesh","role":"MANAGER","exp":...} HMAC-SHA256(...)
Key Takeaway
JWT authentication is a stateless, token-based mechanism that eliminates server-side session storage. The client authenticates once with credentials, receives a signed JWT containing user claims, and sends that token in the Authorization header for every subsequent request. The server validates the signature and expiration on each request without looking up any session. This makes horizontal scaling straightforward because any server instance can validate the token.
The JWT has three parts: a header (algorithm and type), a payload (claims like username, role, and expiration), and a signature (computed by signing the header and payload with a secret key). If anyone modifies the payload, the signature becomes invalid and the server rejects the token. The payload is Base64-encoded, not encrypted, so never put sensitive data like passwords or credit card numbers in it.
In our National Bank of India jwt-auth-service, we implemented the complete flow: an AuthController that validates credentials and returns a JWT, a JwtUtil that creates and parses tokens with the jjwt library, a JwtAuthenticationFilter that intercepts every request and sets the SecurityContext, and a SecurityConfig that enforces stateless sessions and JWT-based authentication.
At the senior level, choose between HS256 (shared secret, simpler) and RS256 (public/private key, better for microservices). At the principal level, implement refresh token rotation, maintain a Redis blacklist for forced logout, use short-lived access tokens (15 minutes) with long-lived refresh tokens (7 days), and load secrets from a secrets manager rather than configuration files.
Remember one sentence: JWT is a signed, self-contained token that carries user claims in its payload, is validated by verifying the signature on every request, and eliminates the need for server-side session storage.
---