使用 @restcontrolleradvice 结合 @exceptionhandler 可以捕获授权失败异常。针对 spring security,通常需处理 accessdeniedexception(已认证但无权限)和 authenticationexception 的子类如 badcredentialsexception(未认证),通过返回自定义的 json 响应来统一处理。

如何区分并处理未认证与无权限异常
在 Spring Boot 中,未认证(如密码错误、Token 无效)和无权限(如访问被禁用的接口)由不同的异常类型表示。未认证通常抛出 AuthenticationException 及其子类,而无权限则抛出 AccessDeniedException。全局异常处理器需要分别定义这两个异常的捕获方法,以便返回不同的 HTTP 状态码和提示信息。

import org.springframework.http.HttpStatus; import org.springframework.http.ResponseEntity; import org.springframework.security.access.AccessDeniedException; import org.springframework.security.core.AuthenticationException; import org.springframework.web.bind.annotation.ExceptionHandler; import org.springframework.web.bind.annotation.RestControllerAdvice; import java.util.HashMap; import java.util.Map; @RestControllerAdvice public class GlobalExceptionHandler { @ExceptionHandler(AuthenticationException.class) public ResponseEntity<map object>> handleAuthError(AuthenticationException ex) { Map<string object> body = new HashMap(); body.put("error", "Unauthorized"); body.put("message", ex.getMessage()); return ResponseEntity.status(HttpStatus.UNAUTHORIZED).body(body); } @ExceptionHandler(AccessDeniedException.class) public ResponseEntity<map object>> handleAccessDenied(AccessDeniedException ex) { Map<string object> body = new HashMap(); body.put("error", "Forbidden"); body.put("message", ex.getMessage()); return ResponseEntity.status(HttpStatus.FORBIDDEN).body(body); } }</string></map></string></map>
上述代码展示了两个核心处理方法。当用户登录凭证不正确时,Spring Security 会抛出 AuthenticationException,此时返回 401 状态码。当用户已登录但尝试访问其角色无权访问的资源时,抛出 AccessDeniedException,返回 403 状态码。这种区分确保了前端能根据状态码准确判断是重新登录还是提示权限不足。
如何处理其他常见的安全相关异常
除了基础的认证和授权异常,实际开发中还常遇到令牌过期、非法参数等与安全相关的异常。例如,JWT 令牌过期通常会抛出 ExpiredJwtException,它属于 AuthenticationException 的范畴,但也可能需要特殊的处理逻辑,比如直接引导用户刷新 Token 或重新登录。此外,如果使用了自定义的安全过滤器链,可能会抛出特定的业务异常,这些也需要在全局处理器中进行兜底处理。

import io.jsonwebtoken.ExpiredJwtException; import org.springframework.http.HttpStatus; import org.springframework.http.ResponseEntity; import org.springframework.security.access.AccessDeniedException; import org.springframework.security.core.AuthenticationException; import org.springframework.web.bind.annotation.ExceptionHandler; import org.springframework.web.bind.annotation.RestControllerAdvice; import java.util.HashMap; import java.util.Map; @RestControllerAdvice public class GlobalExceptionHandler { @ExceptionHandler(ExpiredJwtException.class) public ResponseEntity<map object>> handleExpiredJwt(ExpiredJwtException ex) { Map<string object> body = new HashMap(); body.put("error", "Token Expired"); body.put("message", "Please login again"); return ResponseEntity.status(HttpStatus.UNAUTHORIZED).body(body); } @ExceptionHandler(Exception.class) public ResponseEntity<map object>> handleGeneralError(Exception ex) { Map<string object> body = new HashMap(); body.put("error", "Internal Server Error"); body.put("message", "An unexpected error occurred"); return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body(body); } }</string></map></string></map>
在处理 JWT 过期时,虽然它也是认证问题,但明确抛出 ExpiredJwtException 可以让前端知道具体原因是令牌失效而非账号密码错误。同时,必须保留一个通用的 Exception 捕获器作为兜底,防止未预见的异常导致系统崩溃或暴露敏感堆栈信息。这样构建的异常处理体系既覆盖了标准的安全流程,也具备足够的灵活性应对特定场景。
基于 AccessDeniedException 的具体处理结果是什么
当触发 AccessDeniedException 时,程序会进入对应的 handleAccessDenied 方法,最终向客户端返回一个包含 error 和 message 字段的 JSON 对象,且 HTTP 状态码固定为 403 Forbidden。这意味着请求被服务器拒绝,但不是因为身份验证失败,而是因为当前用户不具备执行该操作所需的权限。











