Spring Security 6.0接口仅返回200/403,其他状态码被覆盖问题排查
问题原因
从日志能明确看到:当接口抛出异常后,Tomcat会自动转发请求到/error端点生成标准化错误响应,但你的Security配置仅允许/v1/resource/*路径匿名访问,/error路径不在许可范围内,被Spring Security拦截后返回403。
解决方案
修改Security配置,将/error路径加入无需认证的列表;同时建议把/v1/resource/*改为/v1/resource/**(双星号匹配多级子路径,更适配REST接口的常见场景):
@Configuration @EnableWebSecurity class SecurityConfig { @Bean fun filterChain(http: HttpSecurity): SecurityFilterChain { http.authorizeHttpRequests { auth -> auth.requestMatchers("/v1/resource/**", "/error").permitAll() .anyRequest().authenticated() // 其他路径需认证,可根据实际需求调整 } return http.build() } }
补充说明
- 你之前用
http.exceptionHandling().disable()能得到正确状态码但返回HTML,是因为禁用异常处理后,Spring Security不再拦截/error的转发流程,但也跳过了Spring Boot的BasicErrorController对错误响应的JSON格式化处理,直接返回了Tomcat默认的HTML错误页面。 - 确保全局异常处理器(如
RestResponseEntityExceptionHandler)正常工作,这样异常会被正确转换为JSON格式的错误响应,再通过/error端点返回给客户端。
内容的提问来源于stack exchange,提问作者Daniel
相关产品推荐
相关产品推荐

