Chapter 9 of 12
Course Progress0 of 12 completed (0%)

Java & Spring Boot Enterprise Mastery · Chapter 9 · ~15 min · Advanced

Spring Security & Stateless JWT Authentication

Architect battle-tested enterprise authentication for modern cloud services. Master the Spring Security Filter Chain conveyor belt, author custom OncePerRequestFilters, prevent ThreadLocal SecurityContext memory bleeds, and enforce declarative method security with @PreAuthorize.

  • Trace request authentication through the Spring Security Filter Chain
  • Implement a stateless OncePerRequestFilter for bearer JWT tokens
  • Populate and clear SecurityContextHolder for authenticated principal threads
  • Protect endpoints using method security annotations (@PreAuthorize)

Spring Security & Stateless JWT Authentication: learn it visually

Architect battle-tested enterprise authentication for modern cloud services. Master the Spring Security Filter Chain conveyor belt, author custom OncePerRequestFilters, prevent ThreadLocal SecurityContext memory bleeds, and enforce declarative method security with @PreAuthorize.

Spring Security & Stateless JWT AuthenticationArchitect battle-tested enterprise authentication for modern cloud services. Master the Spring Security Filter Chain conveyor belt, author custom OncePerRequestFilters, prevent ThreadLocal SecurityContext memory bleeds, and enforce declarative method security with @PreAuthorize.UNDERSTANDSpring SecurityFOLLOW THE FLOWStateless JWTAuthenticationAPPLY ITbattle-testedauthentication cloudSpring Security & Stateless JWT AuthenticationArchitect battle-tested enterprise authentication for modern cloud services. Master the Spring Security Filter Chain conveyor belt, author custom OncePerRequestFilters, prevent ThreadLocal SecurityContext memory bleeds, and enforce declarative method security with @PreAuthorize.UNDERSTANDSpring SecurityFOLLOW THE FLOWStateless JWTAuthenticationAPPLY ITbattle-testedauthentication cloud

1The Spring Security Filter Chain Architecture

Spring Security does not execute inside the DispatcherServlet. Instead, it operates at the servlet filter level through the SecurityFilterChain. Incoming HTTP requests pass through a sequence of specialized filters before they ever reach Spring MVC:

// Modern Spring Security 6 Component-Based Configuration (No WebSecurityConfigurerAdapter!)
@Configuration
@EnableWebSecurity
@EnableMethodSecurity // Activates @PreAuthorize, @PostAuthorize, @Secured
public class SecurityConfiguration {

    private final JwtAuthenticationFilter jwtFilter;

    public SecurityConfiguration(JwtAuthenticationFilter jwtFilter) {
        this.jwtFilter = jwtFilter;
    }

    @Bean
    public SecurityFilterChain securityFilterChain(HttpSecurity http) throws Exception {
        return http
            // 1. Disable CSRF (Cross-Site Request Forgery is not needed for stateless bearer tokens)
            .csrf(csrf -> csrf.disable())
            
            // 2. Set SessionCreationPolicy to STATELESS (Never store JSESSIONID in server RAM)
            .sessionManagement(sess -> sess.sessionCreationPolicy(SessionCreationPolicy.STATELESS))
            
            // 3. Define public vs protected endpoint patterns
            .authorizeHttpRequests(auth -> auth
                .requestMatchers("/api/v1/auth/**", "/actuator/health").permitAll()
                .anyRequest().authenticated()
            )
            
            // 4. Inject our custom JWT filter BEFORE the standard UsernamePasswordAuthenticationFilter
            .addFilterBefore(jwtFilter, UsernamePasswordAuthenticationFilter.class)
            .build();
    }
}
Concept Check

Why is CSRF (Cross-Site Request Forgery) protection safely disabled in a stateless REST API using JWT Bearer tokens?

2Dual Mental Model: Stateful Sessions vs Stateless JWT Bearer Tokens

Compare the architectural tradeoffs between server-bound HTTP sessions and cryptographically verifiable JWT tokens:

Wrong idea: Stateful server session cookies (JSESSIONID in server RAM)

Pod 1: Session in RAM → Pod 2: User logged out! (Requires sticky sessions)High server RAM consumption · fragile horizontal scaling · session replication latency

Storing user session states inside server memory, making horizontal scaling across multiple Kubernetes pods require sticky sessions or Redis replication.

Real system: Stateless cryptographically signed JWT bearer tokens

Header.Payload.Signature → Any Pod verifies cryptographic signature in 0.05msZero server memory · infinitely scalable · microservice & mobile friendly

Issuing self-contained JSON Web Tokens signed with HMAC-SHA256 or RSA. Any backend pod can independently verify authenticity without hitting a session store.

3Authoring OncePerRequestFilter & ThreadLocal Hygiene

Spring Security stores the active authenticated user in SecurityContextHolder, which uses a ThreadLocal variable by default. Because servlet containers (like Tomcat) recycle worker threads from a pool, failing to clear the SecurityContext in a finally block causes identity bleed:

@Component
public class JwtAuthenticationFilter extends OncePerRequestFilter {

    private final JwtTokenService tokenService;
    private final UserDetailsService userDetailsService;

    public JwtAuthenticationFilter(JwtTokenService tokenService, UserDetailsService userDetailsService) {
        this.tokenService = tokenService;
        this.userDetailsService = userDetailsService;
    }

    @Override
    protected void doFilterInternal(
        HttpServletRequest request,
        HttpServletResponse response,
        FilterChain filterChain
    ) throws ServletException, IOException {
        try {
            String authHeader = request.getHeader("Authorization");
            if (authHeader != null && authHeader.startsWith("Bearer ")) {
                String token = authHeader.substring(7);

                if (tokenService.isTokenValid(token)) {
                    String username = tokenService.extractUsername(token);
                    UserDetails userDetails = userDetailsService.loadUserByUsername(username);

                    var authToken = new UsernamePasswordAuthenticationToken(
                        userDetails, null, userDetails.getAuthorities()
                    );
                    authToken.setDetails(new WebAuthenticationDetailsSource().buildDetails(request));
                    
                    // Bind authenticated user to current thread
                    SecurityContextHolder.getContext().setAuthentication(authToken);
                }
            }
            filterChain.doFilter(request, response);
        } finally {
            // CRITICAL: Prevent ThreadLocal leakage across recycled Tomcat worker threads!
            SecurityContextHolder.clearContext();
        }
    }
}
Concept Check

What catastrophic bug occurs if SecurityContextHolder is not cleared after a request in a servlet-container environment?

4Interactive Visualizer: SecurityFilterChain & JWT Conveyor

Test how the Security Filter Chain handles valid tokens, expired tokens, and tampered signatures:

SecurityFilterChain & JWT Pipeline Conveyor

Watch a bearer token flow through OncePerRequestFilter, cryptographic signature check, and SecurityContextHolder

Spring Security 6 (Stateless)

Select Incoming Client Authorization Token:

Bearer Token Deconstruction
AUTHENTICATED
Raw: Authorization: Bearer eyJhbGciOiJSUzI1NiJ9.eyJzdWIiOiJ1c2VyLTQ4MiIsInJvbGVzIjpbIlJPTEVfQURNSU4iXX0.K8x9...
Extracted Subject:user-482 (Admin Director)
Assigned Roles:ROLE_ADMIN, ROLE_USER
Signature Verification:Signature Verified via Public RSA Key
Expiration Timestamp:Valid (Expires in 58 minutes)

SecurityFilterChain Traversal (Order & Interception):

Filter 1CorsFilterOrigins Allowed
Filter 2CsrfFilterDisabled (Stateless)
Filter 3JwtAuthFilterToken Accepted
Target Handler@RestControllerPrincipal: user-482 [ROLE_ADMIN]

5Method Security with @PreAuthorize Expressions

Spring Security's @EnableMethodSecurity empowers developers to colocate fine-grained authorization rules directly on service and controller methods using Spring Expression Language (SpEL):

@Service
public class PayrollService {

    // Only users with ROLE_ADMIN or HR_SPECIALIST may view salaries
    @PreAuthorize("hasAnyRole('ADMIN', 'HR_SPECIALIST')")
    public BigDecimal getExecutiveCompensation(Long executiveId) {
        return compensationRepo.findSalary(executiveId);
    }

    // Dynamic Parameter Expression: Users can only view their OWN tax documents unless ADMIN
    @PreAuthorize("hasRole('ADMIN') or #employeeId == authentication.principal.id")
    public TaxDocument getW2Form(Long employeeId, int taxYear) {
        return taxRepo.findForm(employeeId, taxYear);
    }
}

6Code Bug Hunt: Unvalidated JWT Expiry & Context Bleed

The JwtAuthenticationFilter below fails to validate token expiration and omits the mandatory cleanup of SecurityContextHolder. Fix the filter to validate the token and ensure clean thread hygiene:

Fix Unvalidated JWT Expiry & ThreadLocal Context Bleed
Java

🎯 Find and fix the bugs in the code above, then press Run & verify to test your solution.

Need a hint?
  • Never trust claims in an unverified token. Call jwtTokenService.isTokenValid(token) or verify expiration before populating the UsernamePasswordAuthenticationToken.
  • In thread-pooled servlet containers, SecurityContextHolder uses a ThreadLocal store. Wrap filterChain.doFilter(request, response) in a try-finally block and invoke SecurityContextHolder.clearContext() in finally to prevent authentication context from bleeding into subsequent requests on the same thread.

7Chapter Knowledge Challenge

Verify your mastery of Spring Security and stateless authentication:

Concept Check 1 of 2
1

What is the difference between an Authentication and an Access Token (JWT) in Spring Security?

Concept Check 2 of 2
2

Why should public endpoints (like login or signup) be exempted in HttpSecurity authorizeHttpRequests?

8Recap

  • Spring Security processes requests through the SecurityFilterChain before they reach Spring MVC's DispatcherServlet.
  • Stateless authentication eliminates server RAM session overhead by validating cryptographically signed JWT Bearer tokens.
  • Always wrap filter chain execution in try ... finally { SecurityContextHolder.clearContext(); } to prevent ThreadLocal identity leaks across pooled worker threads.
  • Use @PreAuthorize with SpEL expressions to colocate fine-grained, parameter-aware access control directly with domain methods.

Ready for Chapter 10? Mark this chapter as complete to proceed:

Enjoying this free lesson? Your support helps us build more free animated chapters.

Support Us