Hello! Welcome back to the course.
In our last lesson, we successfully built a login endpoint that authenticates a user and generates JWT access and refresh tokens. This is a huge step, but right now, those tokens are just strings. They don't grant any access. Today, we'll change that.
This lesson's goal is to implement a custom security filter to validate JWTs from incoming requests and set the authentication context. We will build the component that acts as the gatekeeper for our protected API endpoints, inspecting each request for a valid token and establishing the user's identity.
MERN-to-Spring Mapping: Middleware vs. Filters
In your MERN stack experience, you've used middleware in Express.js to protect routes. You would write a function that extracts a JWT from the Authorization header, verifies it, and if valid, attaches the user's information to the request object before calling next().
Spring Security uses an almost identical concept called a Filter Chain. Every incoming web request passes through a series of Filters. Each filter has a specific job: handling CORS, preventing CSRF attacks, or, in our case, validating a JWT.
Our task is to create a custom filter and insert it into this chain.
1. Understanding the Core Concepts
Before we write code, it's crucial to understand the architectural components we'll be using. This will make debugging much easier.
Spring Security Architecture Principles by Daniel Garnier-Moiroux @ Spring I/O 2024
This presentation by a Spring Security engineer, Daniel Garnier-Moiroux, provides an excellent explanation of the framework's core principles. We'll focus on the parts about Filters and the Authentication object.
Please watch these two segments: Filters and the Filter Chain (08:55 - 11:18): Focus on what a Filter is, how it interacts with the request and response, and how the chain is processed. This explains the doFilter method and the nested stack traces you'll see while debugging. The Authentication Object (22:01 - 26:07): Pay close attention to the purpose of the Authentication object, its components (principal, authorities), and its home inside the SecurityContextHolder. This is the object we will create to represent a successfully authenticated user.
The key takeaway is that our filter's job is to create a valid Authentication object and place it in the SecurityContextHolder. Once it's there, Spring Security considers the user authenticated for the duration of the request.
2. Enhancing the JwtService for Validation
Our current JwtService can only generate tokens. Let's add the methods needed to parse and validate them.
Update your JwtService.java with the following methods. You'll need to add imports for Claims, Function, and UserDetails.
// In com/example/blogplatform/service/JwtService.java
// ... (existing methods and fields)
public String extractUsername(String token) {
return extractClaim(token, Claims::getSubject);
}
public <T> T extractClaim(String token, Function<Claims, T> claimsResolver) {
final Claims claims = extractAllClaims(token);
return claimsResolver.apply(claims);
}
public boolean isTokenValid(String token, UserDetails userDetails) {
final String username = extractUsername(token);
return (username.equals(userDetails.getUsername())) && !isTokenExpired(token);
}
private boolean isTokenExpired(String token) {
return extractExpiration(token).before(new Date());
}
private Date extractExpiration(String token) {
return extractClaim(token, Claims::getExpiration);
}
private Claims extractAllClaims(String token) {
return Jwts.parser()
.verifyWith(getSignInKey())
.build()
.parseSignedClaims(token)
.getPayload();
}
// ... (getSignInKey method)
Code Breakdown:
extractAllClaims: This is the new core parsing method. It uses the same secret key to verify the token's signature and then extracts the entire payload (the "claims"). If the signature is invalid or the token is malformed, it will throw an exception.extractUsername: A convenience method to get thesubjectclaim, which holds the username.isTokenValid: This is our main validation method. It checks two things:- Does the username in the token match the user loaded from the database?
- Is the token expired?
3. Implementing the JwtAuthenticationFilter
Now for the main event. We'll create our custom filter.
- Create a new class named
JwtAuthenticationFilterin a new package:com.example.blogplatform.config. We place it inconfigas it's part of the security configuration infrastructure. - Make it a
@Componentso Spring can manage it. - Extend
OncePerRequestFilter, a convenient base class that guarantees the filter is executed only once per request. - Inject the
JwtServiceandUserDetailsServiceusing constructor injection.
package com.example.blogplatform.config;
import com.example.blogplatform.service.JwtService;
import jakarta.servlet.FilterChain;
import jakarta.servlet.ServletException;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import lombok.RequiredArgsConstructor;
import org.springframework.lang.NonNull;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.web.authentication.WebAuthenticationDetailsSource;
import org.springframework.stereotype.Component;
import org.springframework.web.filter.OncePerRequestFilter;
import java.io.IOException;
@Component
@RequiredArgsConstructor
public class JwtAuthenticationFilter extends OncePerRequestFilter {
private final JwtService jwtService;
private final UserDetailsService userDetailsService;
@Override
protected void doFilterInternal(
@NonNull HttpServletRequest request,
@NonNull HttpServletResponse response,
@NonNull FilterChain filterChain
) throws ServletException, IOException {
final String authHeader = request.getHeader("Authorization");
final String jwt;
final String username;
// 1. Check for JWT in the header
if (authHeader == null || !authHeader.startsWith("Bearer ")) {
filterChain.doFilter(request, response); // If no token, pass to the next filter
return;
}
jwt = authHeader.substring(7); // "Bearer ".length()
// 2. Extract username from token
username = jwtService.extractUsername(jwt);
// 3. Check if user is already authenticated for this request thread
if (username != null && SecurityContextHolder.getContext().getAuthentication() == null) {
UserDetails userDetails = this.userDetailsService.loadUserByUsername(username);
// 4. Validate token against user details
if (jwtService.isTokenValid(jwt, userDetails)) {
// 5. Create Authentication object and set it in the SecurityContext
UsernamePasswordAuthenticationToken authToken = new UsernamePasswordAuthenticationToken(
userDetails,
null, // Credentials are not needed as we use JWT
userDetails.getAuthorities()
);
authToken.setDetails(
new WebAuthenticationDetailsSource().buildDetails(request)
);
SecurityContextHolder.getContext().setAuthentication(authToken);
}
}
// 6. Pass to the next filter in the chain
filterChain.doFilter(request, response);
}
}
This implementation is the heart of our stateless authentication. Let's break down the logic in doFilterInternal:
- It checks for the
Authorizationheader. If it's missing or doesn't start withBearer, it immediately passes the request down the filter chain and does nothing else. - It extracts the username from the token.
- It checks
SecurityContextHolder.getContext().getAuthentication() == null. This is an important optimization to ensure we only perform this work once per request. - If the token is valid, it creates a
UsernamePasswordAuthenticationToken. This object is Spring Security's standard implementation of theAuthenticationprincipal. - This is the most critical step:
SecurityContextHolder.getContext().setAuthentication(authToken)tells Spring Security "The user for this request is authenticated asauthToken." - Finally,
filterChain.doFilter()passes the request and response objects to the next filter in the chain. If you forget this line, your request will hang and never reach the controller.
4. Plugging the Filter into the SecurityFilterChain
Creating the filter isn't enough; we need to tell Spring Security to use it. We do this in our SecurityConfig class.
- Inject your
JwtAuthenticationFilterintoSecurityConfig.java. - Add it to the HTTP security configuration using
addFilterBefore.
// In com/example/blogplatform/config/SecurityConfig.java
// ... (imports)
import org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter;
@Configuration
@EnableWebSecurity
@RequiredArgsConstructor
public class SecurityConfig {
private final JwtAuthenticationFilter jwtAuthFilter; // Inject our filter
private final UserDetailsService userDetailsService;
@Bean
public SecurityFilterChain securityFilterChain(HttpSecurity http) throws Exception {
http
.csrf(AbstractHttpConfigurer::disable)
.authorizeHttpRequests(req ->
req.requestMatchers("/api/auth/**").permitAll()
.anyRequest().authenticated()
)
.sessionManagement(session -> session.sessionCreationPolicy(SessionCreationPolicy.STATELESS))
.authenticationProvider(authenticationProvider()) // We'll add this provider soon
.addFilterBefore(jwtAuthFilter, UsernamePasswordAuthenticationFilter.class); // This is the key line
return http.build();
}
// ... (rest of the class)
}
By calling addFilterBefore(jwtAuthFilter, UsernamePasswordAuthenticationFilter.class), we are explicitly telling Spring Security to run our custom JWT filter before its built-in filter that handles username/password form logins. This ensures that for every request, we first check for a valid Bearer token.
5. Runtime Observation and Debugging
Let's see our gatekeeper in action.
1. Create a Protected Endpoint
First, we need something to protect. Let's create a simple test controller.
Create a new controller DemoController.java in your controller package.
package com.example.blogplatform.controller;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
@RestController
@RequestMapping("/api/v1/demo")
public class DemoController {
@GetMapping
public ResponseEntity<String> sayHello() {
return ResponseEntity.ok("Hello from a secured endpoint!");
}
}
Our SecurityConfig specifies anyRequest().authenticated(), so this endpoint at /api/v1/demo is automatically protected.
2. Test the Flow
- Start/Restart your application.
- Attempt to access without a token: In Postman, send a
GETrequest tohttp://localhost:8080/api/v1/demo. You should receive a403 Forbiddenresponse. This is our filter chain in action, specifically the default exception handling, because noAuthenticationwas found. - Get a valid token: Send a
POSTrequest tohttp://localhost:8080/api/auth/loginwith valid credentials to get an access token. - Access with a valid token: Create a new
GETrequest in Postman forhttp://localhost:8080/api/v1/demo.- Go to the Authorization tab.
- Select Type: Bearer Token.
- Paste your
accessTokeninto the Token field. - Send the request.
This time, you should get a 200 OK response with the body "Hello from a secured endpoint!". Success!
Debugging Exercise: See the Magic Happen
Your "debugging-first" preference is a great way to learn. Let's apply it.
- In your IDE, set a breakpoint on the first line inside the
doFilterInternalmethod of yourJwtAuthenticationFilter. - Run the application in Debug mode.
- In Postman, re-send the successful
GETrequest to/api/v1/demowith the Bearer token. - Your IDE will pause execution at the breakpoint. Step through the code line by line:
- Watch
authHeaderget populated from the request. - See the
jwtstring get extracted. - Step into
jwtService.extractUsernameand see the token being parsed. - Observe the
userDetailsbeing loaded from the database. - See the
authTokenobject being created. - The final, crucial step: watch the
SecurityContextHolderget populated with yourauthToken.
- Watch
This exercise provides direct, runtime proof of how a request is authenticated in a stateless Spring Boot application.
Conclusion
Excellent work! You have now implemented the most critical piece of JWT security in a Spring Boot application. You've bridged the gap between generating a token and actually using it to secure your API.
Key Takeaways:
OncePerRequestFilteris the standard way to implement custom security logic that should run for every request.- The filter's primary responsibility is to populate the
SecurityContextHolderwith anAuthenticationobject if the request is valid. - The flow is: Extract Token -> Validate Signature & Claims -> Load User -> Set Security Context.
- We use
addFilterBeforein ourSecurityConfigto insert our custom filter into Spring'sFilterChainat the correct position.
Preview of the Next Lesson:
We can now identify who a user is. The next logical step is to control what they can do. In the next lesson, we will secure endpoints based on user roles (e.g., USER, ADMIN) using method-level security with @PreAuthorize. This will allow us to build features that are only accessible to certain types of users.