两个WebSecurityConfigurerProviders用于两级身份验证层

时间:2019-02-05 10:00:26

标签: java spring-boot

是否可以设置两个自定义WebSecurityConfigurerProvider以便通过一个身份验证大多数端点,并通过这两个身份验证某些请求?

我希望所有端点都具有正确的api-key标头,所以我有以下配置类:

@Configuration
@EnableWebSecurity
@Order(1)
public class FirstLevelSecurityConfig extends WebSecurityConfigurerAdapter {

    @Override
    protected void configure(HttpSecurity httpSecurity) throws Exception {
        AuthFilter authFilter = new AuthFilter(principalRequestHeader);
        authFilter.setAuthenticationManager(new AuthenticationManager() {

            @Override
            public Authentication authenticate(Authentication authentication) throws AuthenticationException {
                if (!someCondition()) {
                    throw new BadCredentialsException("The API key was not found or not the expected value.");
                }
                authentication.setAuthenticated(true);
                return authentication;
            }

        });

        httpSecurity
                .csrf().disable()
                .addFilter(authFilter).authorizeRequests()
                .antMatchers(HttpMethod.OPTIONS, "/**").permitAll()
                .antMatchers(HttpMethod.GET, "/**").authenticated()
                .antMatchers(HttpMethod.POST, "/**").authenticated()
                .and()
                .sessionManagement().sessionCreationPolicy(SessionCreationPolicy.STATELESS);
    }

    @Bean
    public FilterRegistrationBean corsFilter() {
        // cors
    }

}

但是某些某些端点还应该存在第二个正确的标头,因此我用@Order(2)注释编写了第二个类,希望它可以工作:

@Configuration
@EnableWebSecurity
@Order(2)
public class SecondLevelSecurityConfig extends WebSecurityConfigurerAdapter {

    @Override
    protected void configure(HttpSecurity httpSecurity) throws Exception {
        AuthFilter authFilter = new AuthFilter(principalRequestHeader);
        authFilter.setAuthenticationManager(new AuthenticationManager() {

            @Override
            public Authentication authenticate(Authentication authentication) throws AuthenticationException {
                if (!someOtherCondition()) {
                    throw new BadCredentialsException("The API key was not found or not the expected value.");
                }
                authentication.setAuthenticated(true);
                return authentication;
            }

        });

        httpSecurity
                .csrf().disable()
                .addFilter(authFilter).authorizeRequests()
                .antMatchers(HttpMethod.POST, "/certainEndpoint").authenticated();
    }

}

问题在于第二个配置似乎已正确注册,但从未调用过其authentication方法。我在这里想念什么吗?

0 个答案:

没有答案