@EnableResourceServer在Spring WebFlux项目中无法正常运行
嘿,我来帮你解决这个问题!你遇到的这个异常其实是典型的技术栈不匹配导致的,咱们一步步拆解和解决:
问题根源
你的应用是基于Spring WebFlux的响应式应用(选了Reactive Web依赖),属于非Servlet环境;但你添加的@EnableResourceServer是Spring Security OAuth2为传统Servlet环境设计的注解,它会自动尝试创建javax.servlet.Filter相关的Bean——而WebFlux环境根本没有Servlet容器,自然就抛出了找不到Filter的异常。
另外,你引入的spring-security-oauth2-autoconfigure依赖也是为Servlet环境服务的自动配置包,和WebFlux响应式体系完全不兼容。
解决步骤
要在WebFlux应用中实现OAuth2资源服务器功能,得用Spring Security提供的响应式专属支持,具体操作如下:
1. 清理不兼容的内容
- 从pom.xml中删掉
spring-security-oauth2-autoconfigure依赖; - 把启动类上的
@EnableResourceServer注解移除。
2. 添加正确的响应式依赖
在pom.xml中替换成WebFlux兼容的OAuth2资源服务器依赖:
<dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-oauth2-resource-server</artifactId> </dependency>
3. 配置响应式安全规则
创建一个安全配置类,用WebFlux的方式定义资源服务器规则,替代原来的@EnableResourceServer:
import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import org.springframework.security.config.annotation.web.reactive.EnableWebFluxSecurity; import org.springframework.security.config.web.server.ServerHttpSecurity; import org.springframework.security.web.server.SecurityWebFilterChain; @Configuration @EnableWebFluxSecurity public class SecurityConfig { @Bean public SecurityWebFilterChain springSecurityFilterChain(ServerHttpSecurity http) { http .authorizeExchange(exchanges -> exchanges // 这里可以根据你的需求配置哪些路径需要认证,哪些放行 .anyExchange().authenticated() ) .oauth2ResourceServer(oauth2 -> oauth2 // 如果你的认证服务器用JWT令牌,用这个配置;如果是不透明令牌,换成.opaqueToken() .jwt() ); return http.build(); } }
4. 配置认证服务器信息
在application.yml(或properties)里添加认证服务器的相关配置:
- 如果用JWT令牌,配置JWKS端点:
spring: security: oauth2: resourceserver: jwt: jwk-set-uri: https://你的认证服务器地址/.well-known/jwks.json
- 如果用不透明令牌(需要调用认证服务器接口校验令牌),配置:
spring: security: oauth2: resourceserver: opaque-token: introspection-uri: https://你的认证服务器地址/oauth2/introspect client-id: 你的资源服务器客户端ID client-secret: 你的资源服务器客户端密钥
验证
重新构建并启动应用,现在应该不会再出现Servlet Filter相关的异常,你的响应式应用也能正常作为OAuth2资源服务器,校验来自认证服务器的令牌了。
内容的提问来源于stack exchange,提问作者Rob Worsnop
相关产品推荐
相关产品推荐

