0

我有一个安全配置类,其中有一个 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();
}
4

1 回答 1

0

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

}
于 2021-05-17T08:34:59.923 回答