Search code examples
springspring-bootspring-security

Multiple WebSecurityConfigurerAdapter and Filter Chains


I am trying to configure several authentication types for my application using a separate WebSecurityConfigurerAdapter for each type of authentication.

The general idea is to use the WebSecurityConfigurerAdapter configure(HttpSecurity http) method to match a url pattern and do all of the authentication using a dedicated proprietary filter (which includes the authorization).

@Configuration
@EnableWebSecurity
public class DemoMultipleWebSecurityConfigurerAdapter {

    @Order(1)
    @Configuration
    public static class BasicSecurityAdapter extends WebSecurityConfigurerAdapter {

        @Override
        public void configure(HttpSecurity http) throws Exception {
            String endpointPattern = "/api/basic/**";
            http.requestMatchers().antMatchers(endpointPattern);
            http.csrf().ignoringAntMatchers(endpointPattern);
            http.authorizeRequests().antMatchers(endpointPattern).authenticated();


            http.addFilterBefore(new MyBasicAuthFilter(), LogoutFilter.class);
        }
    }

    @Order(2)
    @Configuration
    public static class SSOSecurityAdapter extends WebSecurityConfigurerAdapter {
        @Override
        public void configure(HttpSecurity http) throws Exception {
            String endpointPattern = "/api/sso/**";
            http.requestMatchers().antMatchers(endpointPattern);
            http.csrf().ignoringAntMatchers(endpointPattern);
            http.authorizeRequests().antMatchers(endpointPattern).authenticated();


            http.addFilterBefore(new MySSOAuthFilter(), LogoutFilter.class);
        }
    }
}

During initialization I can see that each WebSecurityConfigurerAdapter is getting a different instance of HttpSecurity to configure (which is suppose to have its own filter chain) however during runtime the filter chain that is called is always the one created for the first WebSecurityConfigurerAdapter no matter which endpoint I call.

According to the documentation Spring is supposed to use the HttpSecurity instances in order to find the correct filter chain to filter on (according to the url pattern).

Any ideas on what I am doing wrong? (I am using Spring 1.5.6-RELEASE to test this)


Solution

  • You don't need multiple WebSecurityConfigurerAdapter; just configure the filters such that they only act for matching URL patterns. In other words, add all the filters, but make the filters act conditionally.