Spring Security Filter Chain Interview Questions and Answers

Master Spring Security Filter Chain with interview questions covering SecurityFilterChain, FilterChainProxy, OncePerRequestFilter, UsernamePasswordAuthenticationFilter, JWT filters, request lifecycle, custom filters, and production best practices.


Introduction

The Security Filter Chain is the heart of Spring Security.

Every HTTP request entering a Spring Boot application first passes through a chain of security filters before reaching the DispatcherServlet and Controllers.

These filters are responsible for

  • Authentication
  • Authorization
  • JWT Validation
  • Session Management
  • CSRF Protection
  • CORS Processing
  • Exception Handling
  • Anonymous Authentication
  • Security Context Management

One of the most common Spring Security interview questions is:

"Explain the complete Security Filter Chain."

Understanding this flow is essential for debugging authentication problems and designing secure enterprise applications.


Security Filter Chain Architecture

flowchart LR

Client --> ServletContainer

ServletContainer --> FilterChainProxy

FilterChainProxy --> SecurityFilterChain

SecurityFilterChain --> DispatcherServlet

DispatcherServlet --> Controller

Controller --> Service

Service --> Database

Controller --> Response

Response --> Client

Q1. What is the Security Filter Chain?

Answer

The Security Filter Chain is a collection of servlet filters executed for every HTTP request.

Responsibilities

  • Authenticate users
  • Authorize requests
  • Validate JWT tokens
  • Prevent CSRF attacks
  • Manage sessions
  • Populate SecurityContext

Every request must pass through this chain before reaching business logic.


Q2. What is FilterChainProxy?

FilterChainProxy is the central Spring Security filter registered with the servlet container.

Responsibilities

  • Receive incoming requests.
  • Select the appropriate SecurityFilterChain.
  • Execute configured filters in order.

FilterChainProxy

flowchart LR

Request --> FilterChainProxy

FilterChainProxy --> SecurityFilterChain1

FilterChainProxy --> SecurityFilterChain2

SecurityFilterChain1 --> DispatcherServlet

Applications may have multiple filter chains for different URL patterns.


Q3. What is SecurityFilterChain?

SecurityFilterChain defines which security filters apply to specific requests.

Example

@Bean
SecurityFilterChain security(
        HttpSecurity http)
        throws Exception {

    return http.build();

}

Spring Boot automatically registers this bean.


Q4. What are the important filters?

Common filters include

  • SecurityContextHolderFilter
  • CorsFilter
  • CsrfFilter
  • LogoutFilter
  • UsernamePasswordAuthenticationFilter
  • BearerTokenAuthenticationFilter
  • AnonymousAuthenticationFilter
  • ExceptionTranslationFilter
  • AuthorizationFilter

These filters execute in a predefined order.


Q5. What is UsernamePasswordAuthenticationFilter?

It authenticates login requests containing username and password.

Workflow

  1. Extract credentials.
  2. Create Authentication object.
  3. Delegate to AuthenticationManager.
  4. Store authentication in SecurityContextHolder.

Login Flow

sequenceDiagram
Client->>UsernamePasswordAuthenticationFilter: Username & Password
UsernamePasswordAuthenticationFilter->>AuthenticationManager: Authenticate
AuthenticationManager-->>UsernamePasswordAuthenticationFilter: Success
UsernamePasswordAuthenticationFilter->>SecurityContextHolder: Store Authentication

Q6. What is OncePerRequestFilter?

OncePerRequestFilter guarantees execution once per HTTP request.

It is commonly extended when creating custom filters.

Typical use cases

  • JWT validation
  • Correlation IDs
  • Request logging
  • Tenant resolution

Example

public class JwtFilter
extends OncePerRequestFilter {

}

Q7. How is JWT validated?

A custom JWT filter usually executes before authentication.

Workflow

  1. Read Authorization header.
  2. Extract Bearer token.
  3. Validate signature.
  4. Load user.
  5. Store authentication in SecurityContext.

JWT Filter Flow

flowchart LR

AuthorizationHeader --> JwtFilter

JwtFilter --> JwtValidation

JwtValidation --> UserDetailsService

UserDetailsService --> SecurityContextHolder

Q8. How are Exceptions handled?

Security exceptions are handled by

  • ExceptionTranslationFilter
  • AuthenticationEntryPoint
  • AccessDeniedHandler

Responses

Scenario HTTP Status
Not authenticated 401 Unauthorized
Access denied 403 Forbidden

Q9. Can we create custom filters?

Yes.

Custom filters can be inserted before or after existing filters.

Example

http.addFilterBefore(
        jwtFilter,
        UsernamePasswordAuthenticationFilter.class
);

Typical use cases

  • JWT
  • API Keys
  • Audit Logging
  • Correlation IDs

Q10. Security Filter Chain Best Practices

Keep Filters Lightweight

Avoid business logic.


Use OncePerRequestFilter

Prevent duplicate execution.


Validate JWT Before Authorization

Authenticate users first.


Never Access Database Repeatedly

Cache user details when appropriate.


Log Security Events

Support auditing and troubleshooting.


Banking Example

flowchart TD

MobileApp --> JwtFilter

JwtFilter --> AuthenticationFilter

AuthenticationFilter --> AuthorizationFilter

AuthorizationFilter --> PaymentController

PaymentController --> PaymentService

PaymentService --> PostgreSQL

Each filter performs a dedicated responsibility before business processing begins.


Common Interview Questions

  • What is the Security Filter Chain?
  • What is FilterChainProxy?
  • What is SecurityFilterChain?
  • Explain the important Spring Security filters.
  • What is UsernamePasswordAuthenticationFilter?
  • What is OncePerRequestFilter?
  • How is JWT validated?
  • How are security exceptions handled?
  • How do you create custom filters?
  • Security Filter Chain best practices?

Quick Revision

Topic Summary
FilterChainProxy Delegates requests to filter chains
SecurityFilterChain Collection of security filters
UsernamePasswordAuthenticationFilter Login authentication
OncePerRequestFilter Executes once per request
JWT Filter Validates bearer tokens
SecurityContextHolder Stores authenticated user
ExceptionTranslationFilter Handles security exceptions
AuthenticationEntryPoint Returns HTTP 401
AccessDeniedHandler Returns HTTP 403
Custom Filter Extend security pipeline

Complete Security Filter Chain Lifecycle

sequenceDiagram
Client->>FilterChainProxy: HTTP Request
FilterChainProxy->>CorsFilter: CORS Check
CorsFilter-->>FilterChainProxy: Continue
FilterChainProxy->>JwtFilter: Validate Token
JwtFilter-->>FilterChainProxy: Authenticated
FilterChainProxy->>SecurityContextHolderFilter: Populate Context
SecurityContextHolderFilter-->>FilterChainProxy: Continue
FilterChainProxy->>AuthorizationFilter: Check Permissions
AuthorizationFilter-->>DispatcherServlet: Allowed
DispatcherServlet->>Controller: Execute
Controller-->>Client: HTTP Response

Production Example – Banking Payment API with JWT

A banking platform exposes

POST /api/v1/payments

Workflow

  1. Customer sends a request with:
Authorization: Bearer eyJhbGciOi...
  1. FilterChainProxy receives the request.
  2. CorsFilter validates the origin.
  3. JwtAuthenticationFilter extracts and validates the token.
  4. UserDetailsService loads customer information.
  5. Authentication is stored in SecurityContextHolder.
  6. AuthorizationFilter verifies the TRANSFER_FUNDS authority.
  7. DispatcherServlet invokes PaymentController.
  8. Payment is processed successfully.
http
    .authorizeHttpRequests(auth ->
        auth
            .requestMatchers("/api/**")
            .authenticated()
    )
    .addFilterBefore(
        jwtFilter,
        UsernamePasswordAuthenticationFilter.class
    );
flowchart LR

MobileApp --> FilterChainProxy

FilterChainProxy --> CorsFilter

CorsFilter --> JwtAuthenticationFilter

JwtAuthenticationFilter --> UserDetailsService

UserDetailsService --> SecurityContextHolder

SecurityContextHolder --> AuthorizationFilter

AuthorizationFilter --> DispatcherServlet

DispatcherServlet --> PaymentController

PaymentController --> PaymentService

PaymentService --> PostgreSQL

Common Spring Security Filters

Filter Responsibility
CorsFilter Validates cross-origin requests
CsrfFilter Prevents CSRF attacks
LogoutFilter Handles logout requests
UsernamePasswordAuthenticationFilter Processes login authentication
BearerTokenAuthenticationFilter Validates OAuth2 Bearer tokens
AnonymousAuthenticationFilter Creates anonymous authentication
ExceptionTranslationFilter Converts security exceptions into HTTP responses
AuthorizationFilter Performs authorization decisions
SecurityContextHolderFilter Manages the SecurityContext lifecycle

Filter vs Interceptor vs ControllerAdvice

Feature Filter Interceptor ControllerAdvice
Layer Servlet Spring MVC Spring MVC
Executes Before DispatcherServlet
Executes Before Controller
Access to Security Context
Handles Authentication
Handles Authorization
Handles Business Exceptions

Key Takeaways

  • The Security Filter Chain is the core of Spring Security and processes every HTTP request before it reaches application controllers.
  • FilterChainProxy is the entry point that selects and executes the appropriate SecurityFilterChain.
  • The filter chain performs authentication, authorization, JWT validation, CSRF protection, CORS processing, and exception handling.
  • UsernamePasswordAuthenticationFilter authenticates login requests, while OncePerRequestFilter is the preferred base class for custom filters such as JWT authentication.
  • Authentication results are stored in the SecurityContextHolder, making the authenticated user available throughout the request.
  • Security exceptions are translated into 401 Unauthorized or 403 Forbidden responses using ExceptionTranslationFilter.
  • Custom filters should remain lightweight and focus on cross-cutting security concerns rather than business logic.
  • Understanding the Security Filter Chain is essential for debugging authentication issues and designing secure enterprise Spring Boot applications.