Spring Boot Security OAuth2问题:WebSecurityConfigurerAdapter致302重定向至/error
我之前也碰到过一模一样的问题——仅仅创建一个空的WebSecurityConfigurerAdapter子类,哪怕连configure方法都注释掉,都会直接搞崩OAuth2的资源服务器功能,调用接口时返回302重定向到/error,而不是预期的401无效令牌响应。
问题根源
Spring Security的配置是优先级驱动的:当你定义了一个WebSecurityConfigurerAdapter的子类,不管它有没有实际配置内容,它都会取代Spring Boot默认的OAuth2自动配置逻辑。这时候默认的资源服务器认证过滤器被覆盖,无效令牌的处理流程被打乱,转而触发了Spring Security默认的“未认证时重定向到登录页/错误页”的逻辑(也就是你看到的302)。
解决方案
有两种可行的解决方式:
直接删除空的
WebSecurityConfigurerAdapter类
如果不需要自定义安全配置,完全可以删掉这个空类,让Spring Boot的OAuth2自动配置(比如ResourceServerAutoConfiguration)正常生效,这样无效令牌时就会返回正确的401响应。正确配置
WebSecurityConfigurerAdapter以兼容OAuth2
如果确实需要自定义安全规则,一定要在configure(HttpSecurity http)方法中显式启用OAuth2资源服务器支持,示例代码如下:@Configuration @EnableWebSecurity public class SecurityConfig extends WebSecurityConfigurerAdapter { @Override protected void configure(HttpSecurity http) throws Exception { http .authorizeRequests() .anyRequest().authenticated() .and() .oauth2ResourceServer() // 启用OAuth2资源服务器功能 .jwt(); // 如果使用JWT令牌,配置JWT解析器(根据你的实际令牌类型调整) } }
补充排查建议
关于你提到的安全日志没获取有效信息的问题,可以尝试把Spring Security的日志级别调到DEBUG,在application.properties中添加:
logging.level.org.springframework.security=DEBUG
这样就能看到完整的认证流程日志,包括令牌校验、过滤器链执行的细节,更容易定位问题。
附你提到的示例信息
测试用curl请求:
curl -H "Authorization: Bearer invalid-token" http://localhost:8080/api/your-protected-endpoint预期返回
401 Unauthorized,实际返回302 Found并重定向到/error。有问题的空配置类代码:
@Configuration @EnableWebSecurity public class SecurityConfig extends WebSecurityConfigurerAdapter { // 即使注释掉configure方法,问题依然存在 /* @Override protected void configure(HttpSecurity http) throws Exception { super.configure(http); } */ }
内容的提问来源于stack exchange,提问作者Chloe

