Spring Security非安全路由抛自定义异常返回403 Forbidden如何处理
Spring Security忽略路由抛出异常返回403的解决方案
问题原因
- 当Controller抛出未被捕获的运行时异常时,Spring MVC会默认将请求转发到
/error内置路径生成错误响应 - 你仅配置了业务接口的放行规则,
/error路径没有加入放行列表,被Spring Security拦截后返回403状态码,和原接口抛出的自定义异常无关
解决方案(三选一即可,推荐前两种结合使用)
方案1:将/error路径加入放行列表
修改WebSecurityConfig.java中的忽略路由配置:
private final String[] IGNORE_ROUTES = new String[] { "/api/users/register", "/api/users/login", "/error" };
方案2:配置全局异常处理器,直接捕获异常返回自定义格式
新增全局异常处理类,异常会被直接捕获返回,不会触发/error转发:
@RestControllerAdvice public class GlobalExceptionHandler { @ExceptionHandler(RuntimeException.class) public Map<String, Object> handleRuntimeException(RuntimeException e) { Map<String, Object> result = new HashMap<>(); result.put("code", 500); result.put("message", e.getMessage()); return result; } }
方案3:清理重复的放行配置
你当前同时配置了WebSecurity层面的忽略和HttpSecurity层面的放行,属于冗余配置,保留其中一种即可:
- 如果希望接口完全跳过Spring Security过滤器链:保留
web.ignoring().antMatchers(IGNORE_ROUTES); - 如果希望接口走过滤器链但无需鉴权:删除
WebSecurity的configure方法,仅保留HttpSecurity中的antMatchers(IGNORE_ROUTES).permitAll()配置
内容的提问来源于stack exchange,提问作者Girish Arora
相关产品推荐
相关产品推荐

