Spring Boot添加OAuth2资源服务器后测试端点返回401/403
问题根因
运行时通过curl访问正常,说明你的安全配置本身逻辑正确;单元测试返回401、自定义路径匹配规则不生效、CSRF/Logout禁用配置看起来失效,核心原因是测试上下文没有加载你自定义的SecurityWebFilterChain配置,实际生效的是Spring Boot OAuth2资源服务器自动配置的默认安全规则:所有端点需要认证,因此未携带JWT的测试请求直接被拦截返回401。
解决步骤
修正测试上下文配置
- 如果你用
@WebFluxTest做Controller层切片测试,需要显式导入你的安全配置类,避免切片过滤掉自定义安全Bean:
@WebFluxTest(PostController::class) @Import(WebSecurityConfig::class) // 替换为你自己定义的安全配置类名 class PostControllerTest { @Autowired private lateinit var client: WebTestClient // 原有测试逻辑不变 }- 如果你不需要切片测试,直接使用全上下文启动测试,添加
@AutoConfigureWebTestClient注解即可自动加载所有配置包括安全规则:
@SpringBootTest(webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT) @AutoConfigureWebTestClient class PostControllerTest { @Autowired private lateinit var client: WebTestClient // 原有测试逻辑不变 }- 如果你是手动构建WebTestClient实例,必须显式绑定Spring Security过滤器链,否则不会加载自定义安全规则:
@Autowired private lateinit var springSecurityFilterChain: SecurityWebFilterChain val client = WebTestClient.bindToController(postController) .webFilter<WebHttpHandlerBuilder>(springSecurityFilterChain) .build()- 如果你用
避免过滤器链优先级冲突
给你自定义的springWebFilterChainBean添加@Order(Ordered.HIGHEST_PRECEDENCE)注解,强制自定义过滤器链优先级高于Spring Boot自动配置的默认安全链,避免被默认配置覆盖:@Bean @Order(Ordered.HIGHEST_PRECEDENCE) fun springWebFilterChain(http: ServerHttpSecurity, reactiveJwtDecoder: ReactiveJwtDecoder): SecurityWebFilterChain = http { // 原有配置不变 }
补充说明
你日志中看到的CSRF过滤器匹配、/logout路径匹配日志属于正常现象:即使显式禁用对应功能,过滤器链中仍会保留基础的路径匹配判断逻辑,只要日志输出Did not match/No matches found就说明不会拦截当前请求,不需要额外处理。
配置生效后,你设置为permitAll的/posts端点不需要携带JWT即可正常通过单元测试,无需提前添加JWT模拟逻辑。
内容的提问来源于stack exchange,提问作者Hantsy
相关产品推荐
相关产品推荐

