Spring Boot中PermitAll配置后/pub接口401及带Token异常问题
Spring Boot AAD资源服务器:/pub接口带Token返回401问题排查
问题描述
我有一个Spring Boot应用,配置了AAD资源服务器,希望所有请求都能访问/pub接口。最初配置后无Token访问返回401,添加.dispatcherTypeMatchers(DispatcherType.FORWARD, DispatcherType.ERROR).permitAll()后,无Token访问/pub返回200正常,但携带Bearer Token的请求仍返回401,需排查原因。
原始配置代码:
@Configuration(proxyBeanMethods = false) @EnableWebSecurity @EnableMethodSecurity class ResourceServerConfiguration { @Bean @Throws(Exception::class) fun apiFilterChain(http: HttpSecurity): SecurityFilterChain? { http .apply(AadResourceServerHttpSecurityConfigurer.aadResourceServer()) .and() .authorizeHttpRequests() .requestMatchers("/pub").permitAll() .anyRequest().authenticated(); return http.build() } }
问题原因
核心问题在于AAD资源服务器的校验逻辑优先级:
- 应用
AadResourceServerHttpSecurityConfigurer.aadResourceServer()后,Spring Security会自动添加BearerTokenAuthenticationFilter,该过滤器会在授权规则(authorizeHttpRequests)之前执行。 - 当请求携带Token时,过滤器会优先尝试校验Token的有效性(包括issuer、audience、签名、过期时间等),只要Token不符合AAD配置要求,就会直接返回401,不会走到
permitAll的授权逻辑。 - 原配置中仅通过
authorizeHttpRequests放行/pub,但未告知AAD资源服务器跳过该路径的Token校验,导致带Token的请求被提前拦截。
解决方案
修改配置,明确让AAD资源服务器对/pub路径跳过Token校验,同时调整配置顺序确保规则优先级正确:
@Configuration(proxyBeanMethods = false) @EnableWebSecurity @EnableMethodSecurity class ResourceServerConfiguration { @Bean @Throws(Exception::class) fun apiFilterChain(http: HttpSecurity): SecurityFilterChain? { http .authorizeHttpRequests { auth -> auth .dispatcherTypeMatchers(DispatcherType.FORWARD, DispatcherType.ERROR).permitAll() .requestMatchers("/pub").permitAll() .anyRequest().authenticated() } .apply(AadResourceServerHttpSecurityConfigurer.aadResourceServer()) { // 对/pub路径跳过Token校验 this.jwt { jwt -> jwt.ignore("/pub") } } return http.build() } }
额外排查点
如果修改后仍有问题,可检查以下内容:
- 确认Token的issuer、audience与AAD应用注册配置完全匹配
- 检查Token是否过期,或签名是否有效
- 开启Spring Security debug级日志,跟踪请求拦截流程,定位具体返回401的过滤器
内容的提问来源于stack exchange,提问作者Gumaniuc Alexandru
相关产品推荐
相关产品推荐

