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.
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();
}
}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)
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
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();
}
}
}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
Select Incoming Client Authorization Token:
SecurityFilterChain Traversal (Order & Interception):
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:
🎯 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 theUsernamePasswordAuthenticationToken. - In thread-pooled servlet containers,
SecurityContextHolderuses aThreadLocalstore. WrapfilterChain.doFilter(request, response)in atry-finallyblock and invokeSecurityContextHolder.clearContext()infinallyto prevent authentication context from bleeding into subsequent requests on the same thread.
7Chapter Knowledge Challenge
Verify your mastery of Spring Security and stateless authentication:
What is the difference between an Authentication and an Access Token (JWT) in Spring Security?
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: