首页 > 解决方案 > Spring security 和 keyclock - ServerHttpSecurity 错误

问题描述

我正在尝试将 Spring Security 添加到我的 Spring Boot 应用程序中。我创建了新的 SecurityConfig 类,并添加了以下代码:

@Configuration
@EnableWebSecurity
public class SecurityConfig {

    @Bean
    public SecurityWebFilterChain configSecurity(ServerHttpSecurity http) {
        return http
            .authorizeExchange(exchange -> exchange.matchers(EndpointRequest.toAnyEndpoint()).permitAll().anyExchange().authenticated())
            .oauth2ResourceServer(ServerHttpSecurity.OAuth2ResourceServerSpec::jwt)
            .build();
    }

}

当我尝试启动应用程序时,出现错误:

2021-04-08 08:58:47.828 INFO 3040 --- [main] ossweb.DefaultSecurityFilterChain:将使用 [org.springframework.security.web.context.request.async.WebAsyncManagerIntegrationFilter@6089c1e3, org.springframework 保护任何请求。 security.web.context.SecurityContextPersistenceFilter@4bba628, org.springframework.security.web.header.HeaderWriterFilter@47b4fcd5, org.springframework.security.web.csrf.CsrfFilter@439acac0, org.springframework.security.web.authentication.logout。 LogoutFilter@6af447b6, org.springframework.security.oauth2.server.resource.web.BearerTokenAuthenticationFilter@5679e464, org.springframework.security.web.savedrequest.RequestCacheAwareFilter@4420f4d4, org.springframework.security.web.servletapi.SecurityContextHolderAwareRequestFilter@517594dd, org.springframework.security.web.authentication。AnonymousAuthenticationFilter@67231d8d, org.springframework.security.web.session.SessionManagementFilter@59b5251d, org.springframework.security.web.access.ExceptionTranslationFilter@7d6b0636, org.springframework.security.web.access.intercept.FilterSecurityInterceptor@4b50ebea]

2021-04-08 08:58:47.883 WARN 3040 --- [main] ConfigServletWebServerApplicationContext:在上下文初始化期间遇到异常-取消刷新尝试:org.springframework.beans.factory.UnsatisfiedDependencyException:创建名称为“configSecurity”的bean时定义在类路径资源[it/config/SecurityConfig.class]:通过方法'configSecurity'参数0表示的不满足的依赖关系;嵌套异常是 org.springframework.beans.factory.NoSuchBeanDefinitionException:没有“org.springframework.security.config.web.server.ServerHttpSecurity”类型的合格 bean 可用:预计至少有 1 个有资格作为自动装配候选者的 bean。依赖注释:{}

和:


应用程序无法启动


说明:it.config.SecurityConfig 中方法 configSecurity 的参数 0 需要找不到类型为“org.springframework.security.config.web.server.ServerHttpSecurity”的 bean。

行动:考虑在你的配置中定义一个“org.springframework.security.config.web.server.ServerHttpSecurity”类型的bean。

你知道怎么解决吗?

在我的依赖之下:

<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-security</artifactId>
</dependency>
<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-oauth2-resource-server</artifactId>
</dependency>

标签: springspring-securityspring-security-oauth2

解决方案


尝试使用以下注释 bean 所在的类:

@Configuration
@EnableWebSecurity

另外,确保 bean 是公开的 - 看看是否所有这些都修复了它?如果没有 - 您能否提供异常的完整堆栈跟踪。

谢谢,本


推荐阅读