JWT in Spring Boot
Implementing JWT authentication filter, JwtService, issuing and validating tokens end-to-end
- Build a JwtAuthenticationFilter that validates tokens on every request
- Issue signed tokens on successful login
- Integrate JWT with SecurityContextHolder
Table of Contents
- JWT Recap — What Is JWT?
- Implementation Roadmap
- Why Spring Boot Has No Built-In JWT Support
- Spring Security Architecture Deep Dive
- How We Extend the Framework for JWT
- Required Dependencies
- Step 1 — User Creation
- Step 2 — Token Generation
- Step 3 — Token Validation
- Step 4 — Refresh Token
- Step 5 — Role-Based Authorization
- Complete Architecture Summary
- Common Mistakes
- Best Practices
- Interview Notes
- Practice Questions
- Summary Revision Bullets
1. JWT Recap What Is JWT?
Overview
JWT (JSON Web Token) is a stateless authentication method. "Stateless" means the server does not maintain any session or authentication state between requests. Each request carries all the information the server needs to verify the requester's identity.
Structure
A JWT token has three parts, separated by dots (.):
1<Header>.<Payload>.<Signature>Example token (abbreviated):
1eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ92.3eyJzdWIiOiJ1c2VyMSIsImV4cCI6MTcwMDAwMDAwMH04.5SflKxwRJSMeKKF2QT4fwpMeJf36POk6yJV_adQssw5cPart 1 Header
Metadata about the token. Primarily:
- Algorithm used for signing (e.g.,
HS256for HMAC-SHA256) - Token type (
JWT)
Stored as Base64Url encoded JSON.
Part 2 Payload (Claims)
The actual data carried by the token. Common fields:
| Field | Description |
|---|---|
sub | Subject — typically the username or user ID |
iat | Issued At — timestamp when token was created |
exp | Expiration time |
iss | Issuer |
| Email, role | Custom application-specific data |
The payload is also Base64Url encoded (NOT encrypted — do not store sensitive secrets here).
Claim types:
- Registered claims — standardized (
sub,exp,iat,iss) - Public claims — custom, should be registered with IANA
- Private claims — custom agreement between parties
Part 3 Signature
Created by:
- Taking the encoded header + encoded payload
- Signing them using the algorithm from the header and a secret key
1HMACSHA256(2 base64UrlEncode(header) + "." + base64UrlEncode(payload),3 secret4)Purpose: Ensures integrity. If anyone tampers with the payload (e.g., changes role from USER to ADMIN), the signature will no longer match when verified, and the token will be rejected.
2. Implementation Roadmap
The complete JWT implementation consists of four steps:
| Step | Endpoint | Description |
|---|---|---|
| 1 | POST /api/user-register | Create user in database with hashed password |
| 2 | POST /generate-token | Validate credentials → return JWT access token + refresh token |
| 3 | GET /api/users (any restricted) | Pass JWT in header → validate → allow/deny |
| 4 | POST /refresh-token | Use refresh token (from cookie) → generate new access token |
3. Why Spring Boot Has No Built-In JWT Support
Spring Boot provides ready-made implementations for:
- Form-based login —
UsernamePasswordAuthenticationFilter - HTTP Basic Authentication —
BasicAuthenticationFilter
But not for JWT. The reason is that JWT requirements vary significantly across applications:
| Concern | Varies By Application |
|---|---|
| Payload content | Different apps store different claims |
| Signing algorithm | HS256, RS256, ES256… |
| Token expiry | 5 min, 15 min, 1 hour… |
| Refresh strategy | Some apps don't need refresh |
| Refresh token storage | Cookie, body, local storage… |
4. Spring Security Architecture Deep Dive
Understanding the Spring Security filter chain is essential before implementing JWT. This section explains the exact flow and the key behavior we exploit to add JWT support.
4.1 The Filter Chain
When any HTTP request arrives:
4.2 Key Components Explained
Filter (Security Filter)
- The request enters the Security Filter Chain
- Multiple filters exist in sequence (e.g.,
SecurityContextPersistenceFilter,UsernamePasswordAuthenticationFilter,BasicAuthenticationFilter,AuthorizationFilter) - Each filter is responsible for a specific authentication method
- Critical behavior: The filter creates an Authentication object from the request data (username/password, session ID, or JWT token)
Authentication Object
Authenticationis an interface- Different filters create different implementations:
- Form login →
UsernamePasswordAuthenticationToken - Basic auth → uses
UsernamePasswordAuthenticationTokentoo - JWT (custom) →
JwtAuthenticationToken(we create this) - At creation time,
authenticated = false - After successful verification,
authenticated = true
AuthenticationManager (ProviderManager)
AuthenticationManageris an interfaceProviderManageris its implementation- It holds a list of AuthenticationProviders
- For each incoming Authentication object, it iterates the list, calls
support()on each provider - The provider that returns
truefromsupport()gets the request delegated to it
1// Simplified ProviderManager internal logic (from Spring Security source)2for (AuthenticationProvider provider : providers) {3 if (!provider.supports(authentication.getClass())) {4 continue;5 }6 result = provider.authenticate(authentication);7 // ...8}AuthenticationProvider
- Performs the actual authentication
DaoAuthenticationProvider— standard provider that:
- Hashes the incoming password
- Loads user from DB via
UserDetailsService - Compares the hashed passwords
- Returns a fully authenticated
Authenticationobject
SecurityContextHolder
- After successful authentication, the
Authenticationobject is stored here - This makes the authenticated user accessible throughout the request lifecycle — including in controllers
4.3 What We Must Notice
5. How We Extend the Framework for JWT
The extension strategy:
Three Things We Must Create
| What | Why |
|---|---|
| Custom Filter | Intercepts the right requests, creates the Authentication object |
| Custom Authentication Token | A new type the custom provider can identify |
| Custom AuthenticationProvider | Understands and validates our custom token |
And one thing we must update:
| What | Why |
|---|---|
| ProviderManager's provider list | So it knows our provider exists and can delegate to it |
6. Required Dependencies
Add these to pom.xml:
1<!-- JWT API — provides interfaces -->2<dependency>3 <groupId>io.jsonwebtoken</groupId>4 <artifactId>jjwt-api</artifactId>5 <version>0.11.5</version>6</dependency>7
8<!-- JWT Implementation — implements the API interfaces -->9<dependency>10 <groupId>io.jsonwebtoken</groupId>11 <artifactId>jjwt-impl</artifactId>12 <version>0.11.5</version>13 <scope>runtime</scope>14</dependency>15
16<!-- Jackson JSON processor — required for parsing JWT payload (JSON key-value pairs) -->17<dependency>18 <groupId>io.jsonwebtoken</groupId>19 <artifactId>jjwt-jackson</artifactId>20 <version>0.11.5</version>21 <scope>runtime</scope>22</dependency>Why three dependencies?
| Dependency | Role |
|---|---|
jjwt-api | Defines the interfaces and APIs you program against |
jjwt-impl | Provides the actual implementation (token signing, parsing, etc.) |
jjwt-jackson | Handles JSON serialization/deserialization of the payload |
7. Step 1 User Creation
Overview
Before any JWT flow can work, users must exist in the database. We expose a registration endpoint.
API
1POST /api/user-register2Body: { "username": "u1", "password": "123", "role": "ROLE_USER" }Key Components
Entity
1@Entity2@Table(name = "user_register")3public class UserRegister {4 @Id5 @GeneratedValue(strategy = GenerationType.IDENTITY)6 private Long id;7 private String username;8 private String password; // stored hashed9 private String role;10 // getters/setters11}Controller
1@RestController2@RequestMapping("/api")3public class UserController {4
5 @Autowired6 private UserRegisterRepository userRepository;7
8 @Autowired9 private PasswordEncoder passwordEncoder;10
11 @PostMapping("/user-register")12 public String registerUser(@RequestBody UserRegister user) {13 // Hash the password before saving14 user.setPassword(passwordEncoder.encode(user.getPassword()));15 userRepository.save(user);16 return "User is registered successfully";17 }18}UserDetailsService Implementation
Spring Security needs to know how to load users from our database. We implement UserDetailsService and override loadUserByUsername:
1@Service2public class CustomUserDetailsService implements UserDetailsService {3
4 @Autowired5 private UserRegisterRepository userRepository;6
7 @Override8 public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {9 UserRegister user = userRepository.findByUsername(username)10 .orElseThrow(() -> new UsernameNotFoundException("User not found: " + username));11
12 return User.builder()13 .username(user.getUsername())14 .password(user.getPassword())15 .roles(user.getRole())16 .build();17 }18}UserDetailsService must be implemented — you tell Spring how to fetch user data from your specific database structure.After Registration
The database now contains:
| id | username | password (hashed) | role |
|---|---|---|---|
| 1 | u1 | $2a$10$... | ROLE_USER |
8. Step 2 Token Generation
Overview
The user sends their username and password. We validate them against the database. If valid, we generate and return a JWT access token (and a refresh token).
The `OncePerRequestFilter`
All our custom filters extend OncePerRequestFilter:
1public abstract class OncePerRequestFilter extends GenericFilterBean {2 // Guarantees the filter executes at most once per request3 protected abstract void doFilterInternal(4 HttpServletRequest request,5 HttpServletResponse response,6 FilterChain filterChain7 ) throws ServletException, IOException;8}OncePerRequestFilter ensures a filter runs exactly once per request, even if the filter chain internally re-invokes filters. Always extend this for custom filters.8.1 LoginRequest DTO
1public class LoginRequest {2 private String username;3 private String password;4 // getters/setters5}8.2 JWT Utility Class
1@Component2public class JwtUtil {3
4 // WARNING: In production, store this in environment variables or a secrets manager5 private static final String SECRET_KEY = "your-very-secure-secret-key-at-least-256-bits";6
7 /**8 * Generate a JWT token.9 * @param username the subject (user identifier)10 * @param expiryMinutes token validity duration in minutes11 * @return signed JWT string12 */13 public String generateToken(String username, long expiryMinutes) {14 return Jwts.builder()15 .setSubject(username) // payload: "sub"16 .setIssuedAt(new Date()) // payload: "iat"17 .setExpiration(new Date(System.currentTimeMillis()18 + expiryMinutes * 60 * 1000)) // payload: "exp"19 .signWith(getSigningKey(), SignatureAlgorithm.HS256) // header: algorithm20 .compact();21 }22
23 /**24 * Validate a JWT token and extract the username (subject).25 * @param token the JWT string26 * @return username if valid27 * @throws BadCredentialsException if token is invalid or expired28 */29 public String validateAndExtractUsername(String token) {30 try {31 Claims claims = Jwts.parserBuilder()32 .setSigningKey(getSigningKey())33 .build()34 .parseClaimsJws(token)35 .getBody();36
37 String username = claims.getSubject();38 if (username == null) {39 throw new BadCredentialsException("Invalid JWT token");40 }41 return username;42 } catch (JwtException e) {43 throw new BadCredentialsException("Invalid JWT token: " + e.getMessage());44 }45 }46
47 private Key getSigningKey() {48 byte[] keyBytes = Decoders.BASE64.decode(SECRET_KEY);49 return Keys.hmacShaKeyFor(keyBytes);50 }51}Why HMAC (Symmetric Key)?
HMAC-SHA256 uses the same secret key to both sign (when generating a token) and verify (when validating a token). This means:
- Only the server knows the key
- The server can verify its own tokens
| Algorithm Type | Key Usage | Use When |
|---|---|---|
| HMAC (HS256) | Same key for sign & verify | Single server or all services share the secret |
| RSA (RS256) | Private key signs, public key verifies | Microservices, external token verification |
8.3 JWT Authentication Filter (Token Generation)
1public class JwtAuthenticationFilter extends OncePerRequestFilter {2
3 private final AuthenticationManager authenticationManager;4 private final JwtUtil jwtUtil;5
6 public JwtAuthenticationFilter(AuthenticationManager authenticationManager, JwtUtil jwtUtil) {7 this.authenticationManager = authenticationManager;8 this.jwtUtil = jwtUtil;9 }10
11 @Override12 protected void doFilterInternal(13 HttpServletRequest request,14 HttpServletResponse response,15 FilterChain filterChain) throws ServletException, IOException {16
17 // Step 1: Only handle the generate-token endpoint18 if (!request.getServletPath().equals("/generate-token")) {19 filterChain.doFilter(request, response); // Not our concern, pass along20 return;21 }22
23 // Step 2: Read username and password from request body24 LoginRequest loginRequest = new ObjectMapper()25 .readValue(request.getInputStream(), LoginRequest.class);26
27 // Step 3: Create a standard UsernamePasswordAuthenticationToken28 // (DaoAuthenticationProvider knows how to handle this)29 UsernamePasswordAuthenticationToken authToken =30 new UsernamePasswordAuthenticationToken(31 loginRequest.getUsername(),32 loginRequest.getPassword()33 );34
35 // Step 4: Delegate to AuthenticationManager36 // → ProviderManager iterates providers37 // → DaoAuthenticationProvider.support() returns true38 // → DaoAuthenticationProvider validates against DB39 Authentication authentication = authenticationManager.authenticate(authToken);40
41 // Step 5: Authentication successful → generate JWT token42 String accessToken = jwtUtil.generateToken(43 authentication.getName(), // username44 15 // 15 minutes45 );46
47 // Step 6: Return access token in Authorization header48 response.setHeader("Authorization", "Bearer " + accessToken);49
50 // Step 7: Generate and send refresh token (in cookie)51 String refreshToken = jwtUtil.generateToken(52 authentication.getName(),53 7 * 24 * 60 // 7 days in minutes54 );55
56 Cookie refreshCookie = new Cookie("refresh-token", refreshToken);57 refreshCookie.setHttpOnly(true); // Prevent JavaScript access58 refreshCookie.setSecure(true); // HTTPS only59 refreshCookie.setPath("/refresh-token"); // Only sent to this endpoint60 response.addCookie(refreshCookie);61
62 // Step 8: Do NOT chain further — we've already sent the response63 // No filterChain.doFilter() call here64 }65}Line-by-Line Explanation
| Line | What it does |
|---|---|
request.getServletPath().equals("/generate-token") | Ensures this filter ONLY activates for the token generation endpoint. Other requests skip this filter. |
new ObjectMapper().readValue(...) | Reads the JSON request body and maps it to LoginRequest |
new UsernamePasswordAuthenticationToken(username, password) | Creates an Authentication object — authenticated = false at this point |
authenticationManager.authenticate(authToken) | Passes to ProviderManager → DaoAuthenticationProvider → validates credentials against DB |
jwtUtil.generateToken(...) | Creates the signed JWT token |
response.setHeader("Authorization", "Bearer " + accessToken) | Returns access token to client |
No filterChain.doFilter() | We don't need to reach the controller — we've sent our response |
Why Use `UsernamePasswordAuthenticationToken` Here?
We're reusing the same token type that form-based login uses — intentionally. This means DaoAuthenticationProvider (which already knows how to validate username/password against the database) will handle it. We get all that validation logic for free.
8.4 Security Configuration
1@Configuration2@EnableWebSecurity3public class SecurityConfig {4
5 @Autowired6 private CustomUserDetailsService userDetailsService;7
8 @Autowired9 private PasswordEncoder passwordEncoder;10
11 @Autowired12 private JwtUtil jwtUtil;13
14 @Bean15 public SecurityFilterChain securityFilterChain(HttpSecurity http) throws Exception {16
17 // Create the authentication filter (token generation)18 JwtAuthenticationFilter authFilter =19 new JwtAuthenticationFilter(authenticationManager(), jwtUtil);20
21 // Create the validation filter (token validation for protected endpoints)22 JwtValidationFilter validationFilter =23 new JwtValidationFilter(authenticationManager());24
25 http26 .csrf(csrf -> csrf.disable())27 .sessionManagement(session ->28 session.sessionCreationPolicy(SessionCreationPolicy.STATELESS)) // No sessions29 .authorizeHttpRequests(auth -> auth30 .requestMatchers("/api/user-register", "/generate-token").permitAll()31 .requestMatchers("/api/users").hasRole("USER")32 .anyRequest().authenticated()33 )34 // Add JWT auth filter BEFORE UsernamePasswordAuthenticationFilter35 .addFilterBefore(authFilter, UsernamePasswordAuthenticationFilter.class)36 // Add validation filter AFTER the auth filter37 .addFilterAfter(validationFilter, JwtAuthenticationFilter.class);38
39 return http.build();40 }41
42 @Bean43 public AuthenticationManager authenticationManager() {44 // Create our own ProviderManager with a specific list of providers45 DaoAuthenticationProvider daoProvider = new DaoAuthenticationProvider();46 daoProvider.setUserDetailsService(userDetailsService);47 daoProvider.setPasswordEncoder(passwordEncoder);48
49 JwtAuthenticationProvider jwtProvider =50 new JwtAuthenticationProvider(jwtUtil, userDetailsService);51
52 return new ProviderManager(List.of(daoProvider, jwtProvider));53 }54
55 @Bean56 public PasswordEncoder passwordEncoder() {57 return new BCryptPasswordEncoder();58 }59}Why Create a New `ProviderManager`?
http.formLogin() or http.httpBasic(), Spring Boot does not automatically create any AuthenticationProvider objects. You must explicitly declare which providers you want and add them to the manager.
Two approaches:
1. Create new ProviderManager (used here) — explicitly define all providers
2. Get Spring's existing AuthenticationManager and add providers to itFilter Order in the Chain
1[SecurityContextPersistenceFilter]2 ↓3[JwtAuthenticationFilter] ← we add BEFORE UsernamePasswordAuthenticationFilter4 ↓5[UsernamePasswordAuthenticationFilter]6 ↓7[JwtValidationFilter] ← we add AFTER JwtAuthenticationFilter8 ↓9[BasicAuthenticationFilter]10 ↓11[AuthorizationFilter]9. Step 3 Token Validation
Overview
When a user wants to access a protected resource, they include the JWT in the Authorization header. Our validation filter intercepts every request, extracts the token, validates it, and sets the authenticated user in the SecurityContextHolder.
9.1 Custom Authentication Token
1public class JwtAuthenticationToken extends AbstractAuthenticationToken {2
3 private final String token; // The raw JWT string4
5 public JwtAuthenticationToken(String token) {6 super(null); // No authorities yet — not authenticated7 this.token = token;8 setAuthenticated(false);9 }10
11 @Override12 public Object getCredentials() {13 return token;14 }15
16 @Override17 public Object getPrincipal() {18 return token;19 }20}Why a custom token?
We need a type that our custom JwtAuthenticationProvider can identify via support(). If we used UsernamePasswordAuthenticationToken, DaoAuthenticationProvider would try to handle it — but it can't validate a JWT.
9.2 Custom Authentication Provider
1@Component2public class JwtAuthenticationProvider implements AuthenticationProvider {3
4 private final JwtUtil jwtUtil;5 private final UserDetailsService userDetailsService;6
7 public JwtAuthenticationProvider(JwtUtil jwtUtil, UserDetailsService userDetailsService) {8 this.jwtUtil = jwtUtil;9 this.userDetailsService = userDetailsService;10 }11
12 @Override13 public Authentication authenticate(Authentication authentication)14 throws AuthenticationException {15
16 // Extract the raw JWT token17 String token = (String) authentication.getCredentials();18
19 // Validate and extract username from the token20 String username = jwtUtil.validateAndExtractUsername(token);21 // This throws BadCredentialsException if token is invalid/expired22
23 if (username == null) {24 throw new BadCredentialsException("Invalid JWT token");25 }26
27 // Load full user details from the database28 UserDetails userDetails = userDetailsService.loadUserByUsername(username);29
30 // Return a fully authenticated object31 // UsernamePasswordAuthenticationToken(principal, credentials, authorities)32 // This constructor automatically sets authenticated = true33 return new UsernamePasswordAuthenticationToken(34 userDetails,35 null,36 userDetails.getAuthorities()37 );38 }39
40 @Override41 public boolean supports(Class<?> authentication) {42 // This provider ONLY handles JwtAuthenticationToken43 return JwtAuthenticationToken.class.isAssignableFrom(authentication);44 }45}Step-by-Step Execution
ProviderManagercallssupports(JwtAuthenticationToken.class)→ returnstrueProviderManagercallsauthenticate(jwtAuthToken)- Provider extracts the raw token string from the
Authenticationobject jwtUtil.validateAndExtractUsername(token)parses and verifies the JWT signature- If valid, extracts the
sub(username) from the payload - Loads full
UserDetailsfrom the database - Returns
UsernamePasswordAuthenticationTokenwithauthenticated = trueand the user's authorities
9.3 JWT Validation Filter
1public class JwtValidationFilter extends OncePerRequestFilter {2
3 private final AuthenticationManager authenticationManager;4
5 public JwtValidationFilter(AuthenticationManager authenticationManager) {6 this.authenticationManager = authenticationManager;7 }8
9 @Override10 protected void doFilterInternal(11 HttpServletRequest request,12 HttpServletResponse response,13 FilterChain filterChain) throws ServletException, IOException {14
15 // Step 1: Extract token from Authorization header16 String token = extractToken(request);17
18 if (token != null) {19 // Step 2: Create custom Authentication object (not yet authenticated)20 JwtAuthenticationToken jwtAuthToken = new JwtAuthenticationToken(token);21
22 // Step 3: Delegate to AuthenticationManager23 // → ProviderManager finds JwtAuthenticationProvider (support() = true)24 // → Provider validates token and returns authenticated object25 Authentication authentication = authenticationManager.authenticate(jwtAuthToken);26
27 // Step 4: Store authenticated object in SecurityContextHolder28 // Now controllers and other filters have access to the authenticated user29 SecurityContextHolder.getContext().setAuthentication(authentication);30 }31
32 // Step 5: Continue the filter chain33 // (unlike token generation filter, we DO need to reach the controller)34 filterChain.doFilter(request, response);35 }36
37 private String extractToken(HttpServletRequest request) {38 String authHeader = request.getHeader("Authorization");39 if (authHeader != null && authHeader.startsWith("Bearer ")) {40 return authHeader.substring(7); // Remove "Bearer " prefix41 }42 return null;43 }44}Key Difference From Token Generation Filter
| Token Generation Filter | Token Validation Filter |
|---|---|
Calls filterChain.doFilter() = No | Calls filterChain.doFilter() = Yes |
Only handles /generate-token | Handles ALL requests |
| Generates and returns token | Validates token, sets security context |
| Response sent from filter | Request continues to Controller |
Validation Flow
Invalid Token Scenario
If the token is invalid (tampered, expired, or malformed):
jwtUtil.validateAndExtractUsername(token)throwsBadCredentialsException- The exception propagates up
- The filter chain stops
- Spring Security returns 403 Forbidden
- The controller is never reached
10. Step 4 Refresh Token
Overview
Access tokens are intentionally short-lived (15 minutes in our example). After expiry, forcing users to re-enter their credentials is a poor user experience. The solution is a refresh token — a long-lived token that can be exchanged for a new access token without re-authentication.
Why Short-Lived Access Tokens?
Token Lifetime Strategy
| Token Type | Lifetime | Storage | Purpose |
|---|---|---|---|
| Access Token | 5–15 minutes | Authorization header (in-memory on client) | Access protected resources |
| Refresh Token | 7–30 days | HttpOnly Cookie | Obtain new access tokens |
10.1 Generating the Refresh Token (during `/generate-token`)
This is already shown in the JwtAuthenticationFilter above. During token generation, we create both tokens:
1// Access token — short lived, sent in header2String accessToken = jwtUtil.generateToken(username, 15);3response.setHeader("Authorization", "Bearer " + accessToken);4
5// Refresh token — long lived, sent in HttpOnly cookie6String refreshToken = jwtUtil.generateToken(username, 7 * 24 * 60); // 7 days7Cookie refreshCookie = new Cookie("refresh-token", refreshToken);8refreshCookie.setHttpOnly(true); // JS cannot read this cookie9refreshCookie.setSecure(true); // Only sent over HTTPS10refreshCookie.setPath("/refresh-token"); // Only sent when this specific path is requested11response.addCookie(refreshCookie);Why Store Refresh Token in HttpOnly Cookie?
| Approach | Pros | Cons |
|---|---|---|
| HttpOnly Cookie (used here) | JS can't access it, browser manages it, path restriction | Requires HTTPS for security |
| Response body | Flexible | Client must store it (localStorage? — vulnerable to XSS) |
| localStorage | Easy client-side access | Vulnerable to XSS attacks |
The HttpOnly + Secure + Path combination:
- HttpOnly → JavaScript's
document.cookiecannot access this cookie - Secure → Cookie is only transmitted over HTTPS connections
- Path = "/refresh-token" → Browser will only include this cookie in requests to
/refresh-token, not in every API call
10.2 JWT Refresh Filter
1public class JwtRefreshFilter extends OncePerRequestFilter {2
3 private final AuthenticationManager authenticationManager;4 private final JwtUtil jwtUtil;5
6 public JwtRefreshFilter(AuthenticationManager authenticationManager, JwtUtil jwtUtil) {7 this.authenticationManager = authenticationManager;8 this.jwtUtil = jwtUtil;9 }10
11 @Override12 protected void doFilterInternal(13 HttpServletRequest request,14 HttpServletResponse response,15 FilterChain filterChain) throws ServletException, IOException {16
17 // Step 1: Only handle the refresh-token endpoint18 if (!request.getServletPath().equals("/refresh-token")) {19 filterChain.doFilter(request, response);20 return;21 }22
23 // Step 2: Extract refresh token from cookie24 // (it's NOT in the header — it was stored in HttpOnly cookie)25 String refreshToken = null;26 if (request.getCookies() != null) {27 for (Cookie cookie : request.getCookies()) {28 if ("refresh-token".equals(cookie.getName())) {29 refreshToken = cookie.getValue();30 break;31 }32 }33 }34
35 if (refreshToken == null) {36 response.sendError(HttpServletResponse.SC_UNAUTHORIZED, "Refresh token missing");37 return;38 }39
40 // Step 3: Validate the refresh token using the existing JWT mechanism41 // We reuse JwtAuthenticationToken — same validation logic as access token validation42 JwtAuthenticationToken jwtAuthToken = new JwtAuthenticationToken(refreshToken);43
44 Authentication authentication = authenticationManager.authenticate(jwtAuthToken);45 // → JwtAuthenticationProvider.support() = true46 // → Validates the refresh token47 // → Returns authenticated object with username48
49 // Step 4: Generate a new ACCESS token50 String newAccessToken = jwtUtil.generateToken(51 authentication.getName(), // username from validated refresh token52 15 // 15 minutes53 );54
55 // Step 5: Return new access token in Authorization header56 response.setHeader("Authorization", "Bearer " + newAccessToken);57
58 // Step 6: Do NOT proceed to controller59 // The job is done — we've issued a new token60 }61}Reusing Existing Infrastructure
Notice that the refresh filter:
- Reuses
JwtAuthenticationToken(no new class needed) - Reuses
JwtAuthenticationProvider(it validates any JWT, access or refresh) - Reuses
JwtUtil.generateToken()(same method) - Only creates a new access token (refresh token remains the same in the cookie)
10.3 Adding Refresh Filter to Security Config
1// In SecurityFilterChain bean:2JwtRefreshFilter refreshFilter = new JwtRefreshFilter(authenticationManager(), jwtUtil);3
4http5 // ... other config ...6 .addFilterAfter(refreshFilter, JwtValidationFilter.class);Final Filter Order
1[SecurityContextPersistenceFilter]2 ↓3[JwtAuthenticationFilter] → handles /generate-token4 ↓5[UsernamePasswordAuthenticationFilter]6 ↓7[JwtValidationFilter] → validates token for ALL requests8 ↓9[JwtRefreshFilter] → handles /refresh-token10 ↓11[BasicAuthenticationFilter]12 ↓13[AuthorizationFilter]10.4 Refresh Token Flow
11. Step 5 Role-Based Authorization
Overview
Once token validation is working, authorization (restricting endpoints by role) is simple — Spring Security handles it through the existing AuthorizationFilter.
Configuration
1.authorizeHttpRequests(auth -> auth2 .requestMatchers("/api/user-register", "/generate-token").permitAll()3 .requestMatchers("/api/users").hasRole("USER")4 .requestMatchers("/api/admin").hasRole("ADMIN")5 .anyRequest().authenticated()6)How It Works
After JwtValidationFilter stores the Authentication object in SecurityContextHolder, the AuthorizationFilter (at the end of the chain) reads that authentication object and checks whether the user's roles match the required roles for the endpoint.
Example Scenarios
| User Role | Endpoint | Result |
|---|---|---|
ROLE_USER | /api/users (requires USER) | ✅ 200 OK |
ROLE_ADMIN | /api/users (requires USER) | ❌ 403 Forbidden |
ROLE_ADMIN | /api/admin (requires ADMIN) | ✅ 200 OK |
| Any | No token | ❌ 401 Unauthorized |
| Any | Expired/invalid token | ❌ 403 Forbidden |
12. Complete Architecture Summary
Full Request Flow Diagram
Token Generation (`/generate-token`)
Token Validation (any protected endpoint)
Component Map
13. Common Mistakes
Mistake 1 Calling `filterChain.doFilter()` When You Shouldn't
1// ❌ WRONG — in token generation filter2filterChain.doFilter(request, response);3// This continues to the controller unnecessarily after sending the token4
5// ✅ CORRECT — just return6response.setHeader("Authorization", "Bearer " + accessToken);7// No doFilter call — we're doneMistake 2 Storing Secret Key in Source Code
1// ❌ WRONG2private static final String SECRET_KEY = "mysecretkey";3
4// ✅ CORRECT5@Value("${jwt.secret}")6private String secretKey;7// And in application.properties (encrypted or from environment):8// jwt.secret=${JWT_SECRET_ENV_VAR}Mistake 3 Not Adding the Filter to the Chain
1// ❌ WRONG — filter created but never added2JwtAuthenticationFilter filter = new JwtAuthenticationFilter(...);3// It will never run!4
5// ✅ CORRECT6http.addFilterBefore(filter, UsernamePasswordAuthenticationFilter.class);Mistake 4 Forgetting to Add the Custom Provider to ProviderManager
1// ❌ WRONG — JwtAuthenticationProvider not in the list2return new ProviderManager(List.of(daoProvider));3// JwtAuthenticationToken will never be handled!4
5// ✅ CORRECT6return new ProviderManager(List.of(daoProvider, jwtProvider));Mistake 5 Using `@Component` on Custom Filters Without Controlling Registration
@Component, Spring Boot automatically registers it in the filter chain in addition to your manual addFilterBefore(). This causes the filter to run twice per request.
Either:
- Don't use @Component on filters (create them as beans manually in SecurityConfig)
- Or use @Bean of type FilterRegistrationBean with setEnabled(false) to prevent auto-registrationMistake 6 Long-Lived Access Tokens
1// ❌ WRONG — access token for 30 days2jwtUtil.generateToken(username, 30 * 24 * 60);3
4// ✅ CORRECT — short-lived access token, long-lived refresh token5jwtUtil.generateToken(username, 15); // 15 minutes for access6jwtUtil.generateToken(username, 7 * 24 * 60); // 7 days for refreshMistake 7 Storing Refresh Token in localStorage
1// ❌ WRONG2localStorage.setItem('refreshToken', token); // Vulnerable to XSS3
4// ✅ CORRECT5// Store in HttpOnly cookie managed by the browser14. Best Practices
| Practice | Reason |
|---|---|
| Use short-lived access tokens (5–15 min) | Limits damage from token theft |
| Store refresh tokens in HttpOnly cookies | Prevents XSS access |
Set Secure flag on refresh cookie | Ensures HTTPS only |
Set Path on refresh cookie | Limits which requests carry the cookie |
| Store secret key in environment variables | Prevents accidental exposure |
Use OncePerRequestFilter | Prevents duplicate filter execution |
Use SessionCreationPolicy.STATELESS | Ensures no sessions are created (truly stateless) |
| Validate token before checking role | Fail fast on invalid credentials |
| Use HTTPS in production | Protects tokens in transit |
| Rotate signing keys periodically | Limits impact of key compromise |
| Consider a token blocklist for logout | Enables token revocation (adds statefulness) |
15. Interview Notes
Q: Why doesn't Spring Boot provide built-in JWT support?
JWT requirements vary by application: what's in the payload, which signing algorithm, what expiry, whether refresh tokens are needed, etc. Spring Boot provides the framework; engineers implement JWT on top.
Q: What is `OncePerRequestFilter` and why do we use it?
It guarantees a filter executes at most once per HTTP request, even if the filter chain internally re-invokes filters. Always extend it for custom security filters.
Q: How does `ProviderManager` decide which provider handles a request?
It iterates its list of AuthenticationProvider instances and calls support(Class> authentication) on each. The first provider that returns true receives the authenticate() call.
Q: What's the difference between an access token and a refresh token?
Access tokens are short-lived (minutes) and used to access resources. Refresh tokens are long-lived (days/weeks) and used only to obtain new access tokens. Keeping access tokens short-lived limits the window of risk if they're stolen.
Q: Can a JWT token be revoked before expiry?
In a pure stateless JWT system, no. Once issued, a JWT is valid until it expires. To enable revocation, you need a server-side token blocklist (a database or cache of invalidated token IDs), which adds a degree of statefulness.
Q: What does `authenticated = false` mean when an `Authentication` object is first created?
It means the credentials haven't been verified yet. The filter creates the object with the user-supplied data but marks it as not yet authenticated. The provider verifies the data and returns a new object with authenticated = true.
Q: Why is HMAC a symmetric key algorithm?
HMAC (Hash-based Message Authentication Code) uses the same secret key to both generate and verify the signature. All services validating the token must have the secret key. RSA is asymmetric — a private key signs, a public key verifies — useful when multiple services need to verify tokens without having signing capability.
Q: What happens if the JWT payload is tampered with?
The signature will no longer match. During validation, Jwts.parserBuilder() recalculates the expected signature and compares. If they don't match, it throws a SignatureException, which we catch and convert to a BadCredentialsException, rejecting the request.
Q: Where should the JWT secret key be stored in production?
In environment variables, application properties with encryption, or a dedicated secrets manager (AWS Secrets Manager, HashiCorp Vault, Azure Key Vault). Never in source code.
16. Practice Questions
Easy
- What are the three parts of a JWT token?
- What does
OncePerRequestFilterguarantee? - What is the role of
AuthenticationManagerin Spring Security? - What does
DaoAuthenticationProviderdo when it receives aUsernamePasswordAuthenticationToken? - Why must
UserDetailsServicebe implemented manually?
Medium
- Explain the flow when a user calls
/generate-tokenwith valid credentials. - Why do we create a custom
JwtAuthenticationTokeninstead of reusingUsernamePasswordAuthenticationTokenfor JWT validation? - What would happen if you added
filterChain.doFilter()at the end of the token generation filter? - Why is
SessionCreationPolicy.STATELESSimportant for JWT-based authentication? - Explain how
ProviderManagerselects whichAuthenticationProviderto use.
Hard
- Describe how you would implement JWT token revocation (logout) without breaking statelessness.
- What security vulnerabilities exist if the refresh token is stored in
localStorageinstead of anHttpOnlycookie? - Explain how RSA-based JWT signing differs from HMAC and when you would choose RSA over HMAC.
- How would you implement role-based access control at the method level (not just at the URL level) using Spring Security annotations?
- Design a system where the access token expires in 15 minutes but the user can stay logged in for 30 days with no interruption.
17. Summary Revision Bullets
- JWT = stateless authentication with three parts: Header (algorithm metadata) · Payload (claims/data) · Signature (integrity guarantee)
- Spring Boot has no built-in JWT — engineers implement it using the existing Security framework
- Filter → creates
Authenticationobject → AuthenticationManager (ProviderManager) → iterates providers, callssupport()→ matching AuthenticationProvider → validates → returns authenticated object → stored in SecurityContextHolder - Custom JWT filter extends
OncePerRequestFilter→ runs once per request guaranteed - Token generation: filter intercepts
/generate-token→ createsUsernamePasswordAuthenticationToken→DaoAuthenticationProvidervalidates against DB → generate JWT → return in header - Token validation: filter intercepts all requests → extracts Bearer token → creates
JwtAuthenticationToken→JwtAuthenticationProvidervalidates JWT signature → stores inSecurityContextHolder→ proceeds to controller - Custom
JwtAuthenticationTokenis needed soJwtAuthenticationProvider.support()can correctly identify and handle it - Refresh token: long-lived (7 days), stored in
HttpOnlycookie withSecureandPathflags → reusesJwtAuthenticationToken+JwtAuthenticationProvider→ returns new short-lived access token - Access tokens = short-lived (15 min) → limits theft risk since JWT cannot be revoked before expiry
- Secret key must never be hardcoded — use environment variables or secrets managers
- Authorization =
AuthorizationFilterreads fromSecurityContextHolder→ checks roles againstrequestMatchersconfig - Filters are added to the chain with
addFilterBefore()/addFilterAfter()— Spring doesn't auto-add custom filters ProviderManagerrequires an explicit list of providers — Spring doesn't auto-create providers unless you usehttp.formLogin()orhttp.httpBasic()
Mastery check
How well can you recall this?
Finished this lesson?