找不到 ServerHttpSecurity bean

问题描述

我有一个 Security 配置类,其中包含一个 SecurityWebFilterChain bean。这个 bean 需要一个 ServerHttpSecuirty 实例,但 spring 说它找不到任何这种类型的 bean,尽管在外部库 (org.springframework.security.config.annotation.web.reactive.ServerHttpSecurityConfiguration) 中创建了一个。我在 github 页面上看到过这个问题,他们说尝试不同的版本,但我使用的是 spring boot 2.4.5,所以它应该可以工作。

我的安全配置类:

@Configuration
public class SecurityConfig {
@Bean
SecurityWebFilterChain springWebFilterChain(ServerHttpSecurity http,JwtTokenProvider tokenProvider,ReactiveAuthenticationManager reactiveAuthenticationManager) {
    final String TAG_SERVICES = "/api/**";

    return http.csrf(ServerHttpSecurity.CsrfSpec::disable)
            .httpBasic(ServerHttpSecurity.HttpBasicSpec::disable)
            .authenticationManager(reactiveAuthenticationManager)
            .securityContextRepository(NoOpServerSecurityContextRepository.getInstance())
            .authorizeExchange(it -> it
                    .pathMatchers(HttpMethod.POST,TAG_SERVICES).hasAnyRole("USER","ADMIN")
                    .pathMatchers(HttpMethod.PUT,"ADMIN")
                    .pathMatchers(HttpMethod.GET,"ADMIN")
                    .pathMatchers(HttpMethod.DELETE,"ADMIN")
                    .pathMatchers(TAG_SERVICES).authenticated()
                    .anyExchange().permitAll()
            )
            .addFilterat(new JwtTokenAuthenticationFilter(tokenProvider),SecurityWebFiltersOrder.HTTP_BASIC)
            .build();


}

}

我的应用类

@ConfigurationPropertiesScan

@SpringBootApplication(exclude={DataSourceAutoConfiguration.class}) 公共类 TestPlatformBackendApplication {

public static void main(String[] args) {
    SpringApplication.run(TestPlatformBackendApplication.class,args);
}

}

外部库 Bean:

@Bean({"org.springframework.security.config.annotation.web.reactive.HttpSecurityConfiguration.httpSecurity"})
@Scope("prototype")
ServerHttpSecurity httpSecurity() {
    ServerHttpSecurityConfiguration.ContextAwareServerHttpSecurity http = new ServerHttpSecurityConfiguration.ContextAwareServerHttpSecurity();
    return http.authenticationManager(this.authenticationManager()).headers().and().logout().and();
}

解决方法

正如评论中推荐的 Toerktumlare (1,2),我将 @EnableWebFluxSecurity 添加到我的安全配置中:

@Configuration
@EnableWebFluxSecurity
public class SecurityConfig {

但我还在 @SpringBootApplication 注释中的排除项中添加了以下内容。

@ConfigurationPropertiesScan
    @SpringBootApplication(exclude={DataSourceAutoConfiguration.class,SecurityAutoConfiguration.class,ManagementWebSecurityAutoConfiguration.class})
    public class TestPlatformBackendApplication {

    public static void main(String[] args) {
        SpringApplication.run(TestPlatformBackendApplication.class,args);
    }

}