是否可以设置两个自定义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
方法。我在这里想念什么吗?