首页 > 解决方案 > 未找到 ServerHttpSecurity bean

问题描述

我有一个安全配置类,其中有一个 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, TAG_SERVICES).hasAnyRole("USER","ADMIN")
                    .pathMatchers(HttpMethod.GET, TAG_SERVICES).hasAnyRole("USER","ADMIN")
                    .pathMatchers(HttpMethod.DELETE, TAG_SERVICES).hasAnyRole("USER","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();
}

标签: springspring-bootspring-webfluxwebflux

解决方案


正如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);
    }

}

推荐阅读