Skip to main content

Welcome to a Grasp lesson

Create a free account to keep studying and create your own study path.

Lesson 37

JWT Validation with Custom Security Filters

This lesson is built with resources from youtube.com, josealopez.dev and 1 more site.

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.

Spring Security Filter Chain – Request Flow
This diagram shows a request flowing through the Spring Security Filter Chain. Our custom JWT filter will be one of these blocks, intercepting the request to perform authentication before it reaches the controller.

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 the subject claim, which holds the username.
  • isTokenValid: This is our main validation method. It checks two things:
    1. Does the username in the token match the user loaded from the database?
    2. Is the token expired?

3. Implementing the JwtAuthenticationFilter

Now for the main event. We'll create our custom filter.

  1. Create a new class named JwtAuthenticationFilter in a new package: com.example.blogplatform.config. We place it in config as it's part of the security configuration infrastructure.
  2. Make it a @Component so Spring can manage it.
  3. Extend OncePerRequestFilter, a convenient base class that guarantees the filter is executed only once per request.
  4. Inject the JwtService and UserDetailsService using 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:

  1. It checks for the Authorization header. If it's missing or doesn't start with Bearer , it immediately passes the request down the filter chain and does nothing else.
  2. It extracts the username from the token.
  3. It checks SecurityContextHolder.getContext().getAuthentication() == null. This is an important optimization to ensure we only perform this work once per request.
  4. If the token is valid, it creates a UsernamePasswordAuthenticationToken. This object is Spring Security's standard implementation of the Authentication principal.
  5. This is the most critical step: SecurityContextHolder.getContext().setAuthentication(authToken) tells Spring Security "The user for this request is authenticated as authToken."
  6. 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.

  1. Inject your JwtAuthenticationFilter into SecurityConfig.java.
  2. 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

  1. Start/Restart your application.
  2. Attempt to access without a token: In Postman, send a GET request to http://localhost:8080/api/v1/demo. You should receive a 403 Forbidden response. This is our filter chain in action, specifically the default exception handling, because no Authentication was found.
  3. Get a valid token: Send a POST request to http://localhost:8080/api/auth/login with valid credentials to get an access token.
  4. Access with a valid token: Create a new GET request in Postman for http://localhost:8080/api/v1/demo.
    • Go to the Authorization tab.
    • Select Type: Bearer Token.
    • Paste your accessToken into 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.

  1. In your IDE, set a breakpoint on the first line inside the doFilterInternal method of your JwtAuthenticationFilter.
  2. Run the application in Debug mode.
  3. In Postman, re-send the successful GET request to /api/v1/demo with the Bearer token.
  4. Your IDE will pause execution at the breakpoint. Step through the code line by line:
    • Watch authHeader get populated from the request.
    • See the jwt string get extracted.
    • Step into jwtService.extractUsername and see the token being parsed.
    • Observe the userDetails being loaded from the database.
    • See the authToken object being created.
    • The final, crucial step: watch the SecurityContextHolder get populated with your authToken.

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:

  • OncePerRequestFilter is the standard way to implement custom security logic that should run for every request.
  • The filter's primary responsibility is to populate the SecurityContextHolder with an Authentication object if the request is valid.
  • The flow is: Extract Token -> Validate Signature & Claims -> Load User -> Set Security Context.
  • We use addFilterBefore in our SecurityConfig to insert our custom filter into Spring's FilterChain at 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.