javaspringspring-security

how does spring security order multiple SecurityFilterChain?


I'm learning spring security and feeling confused by the order of multiple SecurityFilterChain.

below are snippet from spring security reference

@Configuration
@EnableWebSecurity
public class SecurityConfig {

    @Bean
    public SecurityFilterChain filterChain(HttpSecurity http) throws Exception {
        http
            .csrf(Customizer.withDefaults())
            .authorizeHttpRequests(authorize -> authorize
                .anyRequest().authenticated()
            )
            .httpBasic(Customizer.withDefaults())
            .formLogin(Customizer.withDefaults());
        return http.build();
    }

}

and it states the order would be:

First, the CsrfFilter is invoked to protect against CSRF attacks.

Second, the authentication filters are invoked to authenticate the request.

Third, the AuthorizationFilter is invoked to authorize the request.

it do not explain why, and really conflict to my understanding that it would execute in sequential order we arrange: csrf first, then authorizeHttpRequests, then httpBasic, then formLogin

below is a related post but not really answer my question why the snippet in reference would execute like that. stackoverflow how-does-spring-security-order-multiple-SecurityFilterChain


Solution

  • The reason for this order is that certain security operations need to happen before others. Even though you configure the filters in a certain order in your code, Spring Security will rearrange them into a logical execution order when it builds the final filter chain.

    For example:

    1. CSRF protection needs to be applied early to prevent CSRF attacks on any operations. If CSRF protection is applied after authentication or authorization, an attacker could potentially bypass authentication or trigger unauthorized actions before the CSRF check occurs.

    2. Authentication needs to happen before authorization, as you need to know who the user is before you can decide what they're allowed to do. If authentication happens after authorization, you'd be trying to authorize actions for an unknown user, which doesn't make sense logically.

    3. Authorization is typically one of the last steps in the chain. it determines what authenticated users are allowed to do.If authorization is done before authentication, you'd be making access control decisions without knowing who the user is, which could lead to security holes