# Spring Security Filter Chain and JWT Authentication Flow

> Explain how Spring Security works with a filter chain, and design a stateless JWT authentication flow for a REST API.

Canonical: https://www.internhack.in/learn/interview/spring-boot-interview/spring-security-filter-chain-jwt
Last updated: 2026-11-28

Difficulty: Advanced

## Question

Explain how Spring Security works with a filter chain, and design a stateless JWT authentication flow for a REST API.

## Answer

Spring Security looks intimidating because it is big, but the core idea is simple. It is a chain of servlet filters sitting in front of your controllers. Every request passes through the chain, and if any filter decides the caller is not allowed, the request never reaches your code. Think of an airport: check-in, ID verification, baggage scan, boarding gate. Each step has one job, and you only reach the plane if all of them pass.

The entry point is a DelegatingFilterProxy that hands requests to the FilterChainProxy, which picks a SecurityFilterChain matching the URL and runs its filters in order. Important ones include SecurityContextHolderFilter, CorsFilter, CsrfFilter, UsernamePasswordAuthenticationFilter for form login, and near the end AuthorizationFilter, which enforces rules like hasRole ADMIN. The central concept is the SecurityContext, holding an Authentication object that says who the user is and what authorities they have. Authentication happens via AuthenticationManager, which delegates to AuthenticationProviders, often DaoAuthenticationProvider using a UserDetailsService to load the user and a PasswordEncoder to check the password.

In Spring Security 6 and Boot 3, you configure this by declaring a SecurityFilterChain bean and using the lambda DSL. The old WebSecurityConfigurerAdapter is removed. For a REST API with JWT, you disable CSRF, since you are not using cookies for auth, set session creation policy to STATELESS, permit the login and register endpoints, require authentication for everything else, and add your custom JWT filter before UsernamePasswordAuthenticationFilter.

The JWT flow works like this. Step one: the client posts credentials to /auth/login. Your controller calls authenticationManager.authenticate, which validates the password against the stored hash. Step two: on success the server builds a signed JWT containing the subject, roles, issued-at and expiry, signs it with a secret or private key, and returns it, often alongside a longer-lived refresh token. Step three: the client sends Authorization: Bearer token on each request. Step four: your OncePerRequestFilter extracts the header, validates the signature and expiry, builds an Authentication object, and puts it into the SecurityContextHolder. Downstream, @PreAuthorize or URL rules use those authorities. Because the server keeps no session, any instance behind a load balancer can verify the token, which is the scalability benefit.

Trade-offs you should be ready for: a JWT cannot be revoked before it expires unless you maintain a denylist or use short access-token lifetimes with refresh tokens. Keep the payload free of sensitive data because it is only base64 encoded, not encrypted. Use strong secrets from environment variables, prefer asymmetric signing such as RS256 when several services verify tokens, and validate the algorithm to avoid the alg none attack. Where the token is stored on the client matters as well: localStorage is exposed to XSS, while an HttpOnly Secure cookie is safer against XSS but then requires CSRF protection.

Also mention 401 versus 403 handling. Configure an AuthenticationEntryPoint for unauthenticated access and an AccessDeniedHandler for forbidden, returning JSON, since filter exceptions bypass @ControllerAdvice. Oh, and Spring Boot also offers oauth2-resource-server support which can validate JWTs for you with a few lines, and it is preferable when you integrate with an identity provider like Keycloak or Auth0.

## Code examples

### Stateless JWT security configuration

```
@Configuration
@EnableWebSecurity
@EnableMethodSecurity
@RequiredArgsConstructor
public class SecurityConfig {

    private final JwtAuthFilter jwtAuthFilter;

    @Bean
    SecurityFilterChain filterChain(HttpSecurity http) throws Exception {
        http.csrf(csrf -> csrf.disable())
            .sessionManagement(s -> s.sessionCreationPolicy(SessionCreationPolicy.STATELESS))
            .authorizeHttpRequests(auth -> auth
                .requestMatchers("/auth/**", "/actuator/health").permitAll()
                .requestMatchers("/api/admin/**").hasRole("ADMIN")
                .anyRequest().authenticated())
            .addFilterBefore(jwtAuthFilter, UsernamePasswordAuthenticationFilter.class);
        return http.build();
    }

    @Bean
    AuthenticationManager authenticationManager(AuthenticationConfiguration cfg) throws Exception {
        return cfg.getAuthenticationManager();
    }
}

@Component
@RequiredArgsConstructor
class JwtAuthFilter extends OncePerRequestFilter {
    private final JwtService jwtService;
    private final UserDetailsService users;

    @Override
    protected void doFilterInternal(HttpServletRequest req, HttpServletResponse res, FilterChain chain)
            throws ServletException, IOException {
        String header = req.getHeader(HttpHeaders.AUTHORIZATION);
        if (header != null && header.startsWith("Bearer ")) {
            String token = header.substring(7);
            String username = jwtService.extractUsername(token);      // validates signature + expiry
            if (username != null && SecurityContextHolder.getContext().getAuthentication() == null) {
                UserDetails user = users.loadUserByUsername(username);
                var auth = new UsernamePasswordAuthenticationToken(user, null, user.getAuthorities());
                SecurityContextHolder.getContext().setAuthentication(auth);
            }
        }
        chain.doFilter(req, res);
    }
}
```

The filter runs once per request, validates the token, and populates the SecurityContext so authorisation rules can apply.

## Key points

- Spring Security 6 uses a SecurityFilterChain bean, not WebSecurityConfigurerAdapter.
- Stateless JWT setups disable sessions and usually CSRF.
- JWTs are signed, not encrypted; do not store secrets inside.
- Filter-level failures need an AuthenticationEntryPoint, not @ControllerAdvice.

## Common follow-up questions

- How do you implement JWT refresh tokens?
- How would you revoke a JWT?
- Difference between authentication and authorisation?

## Interview tips

- Name the order: login, token issue, bearer header, filter, SecurityContext.
- Discuss trade-offs like revocation and token storage to show maturity.

## Concepts covered

Spring Security, SecurityFilterChain, JWT, OncePerRequestFilter

Previous: [Hibernate First-Level and Second-Level Cache](https://www.internhack.in/learn/interview/spring-boot-interview/spring-hibernate-caching) · Next: [Password Encoding with BCrypt in Spring Security](https://www.internhack.in/learn/interview/spring-boot-interview/spring-security-password-encoding) · [All of Spring Boot](https://www.internhack.in/learn/interview/spring-boot-interview)

## More Spring Boot questions

- [Spring Boot Actuator for Production Monitoring](https://www.internhack.in/learn/interview/spring-boot-interview/spring-boot-actuator)
- [Spring AOP: Aspects, Advice and Proxies](https://www.internhack.in/learn/interview/spring-boot-interview/spring-aop-basics)
- [Microservices with Spring Cloud: Service Discovery and API Gateway](https://www.internhack.in/learn/interview/spring-boot-interview/spring-cloud-discovery-gateway)
- [Circuit Breaker and Resilience4j](https://www.internhack.in/learn/interview/spring-boot-interview/spring-circuit-breaker-resilience4j)
- [Testing: @SpringBootTest vs @WebMvcTest vs @DataJpaTest](https://www.internhack.in/learn/interview/spring-boot-interview/spring-testing-slices)
- [Testing Controllers with MockMvc and Mockito](https://www.internhack.in/learn/interview/spring-boot-interview/spring-mockito-mockmvc-testing)

## Related

- [Learn](https://www.internhack.in/learn)
- [Interview Prep](https://www.internhack.in/learn/interview)
- [Spring Boot](https://www.internhack.in/learn/interview/spring-boot-interview)
