FilterChainProxy in Spring Security 6

Table of Contents

In our previous article on DelegatingFilterProxy, we explored how it locates the FilterChainProxy filter, which is registered as a bean in the Spring web application context. In this article, we will take a deep dive into what happens after DelegatingFilterProxy hands off the request to FilterChainProxy and how it orchestrates security filtering in Spring Security.

FilterChainProxy In Spring Security 6

What is a FilterChainProxy?

FilterChainProxy, a core component of Spring Security, manages multiple security filter chains. It acts as a gatekeeper, deciding which security filters should process an incoming request based on its path. This design enables developers to configure distinct security rules for different endpoints (e.g., /api/**, /admin/**, /public/**).

Simply put, FilterChainProxy helps Spring Security decide which filters should be executed for a specific request and in what order.

How FilterChainProxy Works ?

FilterChainProxy Step-by-Step Workflow

Step-by-Step Workflow

  • Request Reaches DelegatingFilterProxy
    The request is first intercepted by DelegatingFilterProxy, which acts as a bridge between the Servlet container and Spring Security filters.
  • DelegatingFilterProxy Delegates to FilterChainProxy
    Once intercepted, the request is handed over to FilterChainProxy for security filtering.
  • Firewall Processing (HttpFirewall)
    Before further processing, HttpFirewall wraps and sanitizes the request to prevent attacks such as header injection or URL path manipulation.
  • Determine the Appropriate SecurityFilterChain
    FilterChainProxy maintains a list of SecurityFilterChain instances. It iterates through them using the matches() method to find the correct chain for the request.
  • Retrieve and Execute Filters
    Once a matching SecurityFilterChain is found, its associated security filters execute sequentially. These filters handle authentication, session management, CSRF protection, etc.
  • Request Processing Outcome
    • If all security checks pass, the request proceeds to DispatcherServlet.
    • If authentication or authorization fails, a security exception is triggered, returning an error response.

SecurityFilterChain in Spring Security

What is a SecurityFilterChain?

A SecurityFilterChain is an ordered collection of security filters applied to incoming requests based on defined criteria. It ensures that only the necessary security filters are executed for a specific request.

Here is a simplified version of the source code of the SecurityFilterChain:

public final class DefaultSecurityFilterChain implements SecurityFilterChain {

	private static final Log logger = LogFactory.getLog(DefaultSecurityFilterChain.class);

	private final RequestMatcher requestMatcher;

	private final List<Filter> filters;

	// constructors

	public RequestMatcher getRequestMatcher() {
		return this.requestMatcher;
	}

	@Override
	public List<Filter> getFilters() {
		return this.filters;
	}

	@Override
	public boolean matches(HttpServletRequest request) {
		return this.requestMatcher.matches(request);
	}

	// toString method

}

How SecurityFilterChain is Configured ?

The SecurityFilterChain is configured using the HttpSecurity object in a Spring application. Developers can define custom security rules and add necessary security filters.

public class SecurityConfig {
    @Bean
    public SecurityFilterChain filterChain(HttpSecurity http) throws Exception {
        http
            // These method calls add specific filters
            .csrf()          // Adds CsrfFilter
            .cors()          // Adds CorsFilter
            .headers()       // Adds HeaderWriterFilter
            .sessionManagement() // Adds SessionManagementFilter
            .formLogin()     // Adds UsernamePasswordAuthenticationFilter
            .logout()        // Adds LogoutFilter
            .oauth2Login()   // Adds OAuth2 related filters
            .build();       // build the SecurityFilterChain object
    }
}

Each method in the configuration adds a corresponding security filter to the filter chain. .csrf() includes CsrfFilter for CSRF protection, .cors() adds CorsFilter for handling cross-origin requests, and .headers() applies HeaderWriterFilter to manage security headers. .sessionManagement() integrates SessionManagementFilter for session handling, while .formLogin(), .logout(), and .oauth2Login() introduce UsernamePasswordAuthenticationFilter, LogoutFilter, and OAuth2LoginAuthenticationFilter, respectively, to manage authentication and session termination.

Important Security Filters in Spring Security

Spring Security provides various filters, each with a specific role. Some essential ones include:

Authentication Filters:

  • UsernamePasswordAuthenticationFilter – Handles form-based authentication.
  • BasicAuthenticationFilter – Implements HTTP Basic Authentication.
  • BearerTokenAuthenticationFilter – Supports JWT authentication.

Authorization and Context Filters:

  • SecurityContextPersistenceFilter – Manages SecurityContext across multiple requests.
  • ExceptionTranslationFilter – Converts authentication exceptions into appropriate HTTP responses.

Session and Logout Management:

  • SessionManagementFilter – Controls session creation policies.
  • LogoutFilter – Handles logout functionality.

Conclusion

FilterChainProxy actively orchestrates security in Spring Security by evaluating each incoming request, selecting the appropriate SecurityFilterChain, and triggering the necessary security filters in the correct sequence. This process ensures that authentication, authorization, session management, and other security mechanisms function seamlessly to protect the application. Next, we will explore each filter in the chain one by one and take a deep dive into their internal workings!

Would you like to dive deeper into specific Spring Security internals? Let us know in the comments!

Leave a Reply

Your email address will not be published. Required fields are marked *

Join the Tribe