我正在尝试将过滤器链添加到我的 Spring Boot 应用程序中,如下所示。
@Bean
public SecurityFilterChain filterChain(HttpSecurity http, MyTokenIntrospector myTokenIntrospector) throws Exception {
return http
.httpBasic(AbstractHttpConfigurer::disable)
.formLogin(AbstractHttpConfigurer::disable)
.authorizeHttpRequests(
authorizeHttpRequests -> authorizeHttpRequests
.requestMatchers("/actuator/health").permitAll()
.dispatcherTypeMatchers(DispatcherType.ERROR).permitAll()
.requestMatchers(HttpMethod.OPTIONS).permitAll() //for csrf OPTIONS queries
.anyRequest().authenticated()
)
.csrf(AbstractHttpConfigurer::disable)
.addFilterAfter(new MyAuthExtractorFilter(), BearerTokenAuthenticationFilter.class)
.oauth2ResourceServer(oauth2 -> oauth2
.bearerTokenResolver(new MyBasicTokenResolver())
.opaqueToken(opaqueToken -> opaqueToken.introspector(myTokenIntrospector))
.authenticationEntryPoint(new BasicAuthenticationEntryPoint())
)
.sessionManagement(sessionManager -> sessionManager.sessionCreationPolicy(SessionCreationPolicy.STATELESS))
.build();
}
我注意到 Spring Boot 调用的过滤器链与我上面定义的过滤器链不同。我总是可以将
@Order(1)
放在 bean 上,但我想知道为什么定义了另一个过滤器链。
当我在下面的块中的
org.springframework.security.WebSecurityConfiguration
中放置断点时,我可以看到2
中定义了this.securityFilterChains
过滤器链。其中一个是我定义的,另一个似乎是某种默认值。
有没有办法告诉spring只使用我定义的过滤器链?或者我需要申请
Order(1)
才能使用我的吗?
public Filter springSecurityFilterChain() throws Exception {
boolean hasFilterChain = !this.securityFilterChains.isEmpty();
if (!hasFilterChain) {
this.webSecurity.addSecurityFilterChainBuilder(() -> {
this.httpSecurity.authorizeHttpRequests((authorize) -> {
((AuthorizeHttpRequestsConfigurer.AuthorizedUrl)authorize.anyRequest()).authenticated();
});
this.httpSecurity.formLogin(Customizer.withDefaults());
this.httpSecurity.httpBasic(Customizer.withDefaults());
return (SecurityFilterChain)this.httpSecurity.build();
});
}
在 SecurityConfig 类上使用“@Configuration”和“@EnableWebSecurity”注释。
基本上,如果您的自定义SecurityConfig带有@Configuration和@EnableWebSecurity注释,Spring Boot将自动检测并使用它。所以这应该有帮助。