例如,当用户即将访问管理员页面时,我想捕获 spring boot 访问被拒绝异常。
我的 GlobalExceptionHandler (@ControllerAdvice) 中有这个异常处理程序
@ExceptionHandler(AccessDeniedException.class)
@ResponseStatus(HttpStatus.FORBIDDEN)
public String handleAccessDenied(AccessDeniedException e, Model model) {
model.addAttribute("errorMessage", e.getMessage());
return "error";
}
我尝试使用 CustomAccessDeniedHandler:
@Component
public class CustomAccessDeniedHandler implements AccessDeniedHandler {
@Override
public void handle(HttpServletRequest request, HttpServletResponse response, AccessDeniedException accessDeniedException) throws IOException, ServletException {
throw accessDeniedException;
}
}
在我的 SecurityConfig 中我将其添加到我的 filterChain 中:
.exceptionHandling(eh -> eh.accessDeniedHandler(customAccessDeniedHandler))
现在我的终端出现“访问被拒绝”:org.springframework.security.authorization.AuthorizationDeniedException:访问被拒绝
我想用我的 GlobalExceptionHandler 捕获此异常(尝试使用 ExceptionHandler 中的 AuthorizationDeniedException)
注意:我不使用 JWT
我错过了什么?
Spring Security在请求到达任何控制器之前就抛出
AccessDeniedException
了,因此无法捕获它。FilterSecurityInterceptor
@ControllerAdvice
相反,您可以尝试在内部处理它
AccessDeniedHandler
。在您的代码中,异常再次抛出,因此它没有在任何地方被捕获。尝试更改处理程序来执行如下操作:
然后添加一个控制器来处理
/access-denied
:这样,您就可以显示带有您的消息的自定义错误页面。