我有一个自定义的GenericFilterBean,用于在系统中对端点进行许可。
public class UserAccessUrlFilter extends GenericFilterBean {
@Override
public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain)
throws IOException, ServletException {
if (request instanceof HttpServletRequest) {
HttpServletRequest req = (HttpServletRequest) request;
HttpServletResponse res = (HttpServletResponse) response;
//some logic that calls chain.doFilter(request, response); if the user can continue
res.sendError(HttpServletResponse.SC_UNAUTHORIZED,
"User not authorised to access this service.");
return;
}
chain.doFilter(request, response);
}
}
问题是,如果抛出此未经授权的错误,我想显示一个自定义错误页面。
根据找到的教程here,我需要实现一个自定义错误控制器,具体操作如下:
@Controller
public class CustomErrorController implements ErrorController {
private Logger logger = LoggerFactory.getLogger(CustomErrorController.class);
@RequestMapping("/error")
public String handleError(HttpServletRequest request) {
logger.info("Resolving custom error display");
Object status = request.getAttribute(RequestDispatcher.ERROR_STATUS_CODE);
if (status != null) {
Integer statusCode = Integer.valueOf(status.toString());
logger.info("Error code: {}", statusCode);
if(statusCode == HttpStatus.UNAUTHORIZED.value()) {
return "error-401";
}
if(statusCode == HttpStatus.NOT_FOUND.value()) {
return "error-404";
}
else if(statusCode == HttpStatus.INTERNAL_SERVER_ERROR.value()) {
return "error-500";
}
}
return "error";
}
@Override
public String getErrorPath() {
return "/error";
}
}
我能够确认它对于在应用程序中其他位置抛出的任何错误500响应均能很好地工作,但是由于某种原因404和401给了我一个通用页面,仅指出“ HTTP状态401 –未经授权” 显然,它甚至没有浏览我在过滤器中设置的错误消息,该错误消息被添加到安全配置类中:
.addFilterAfter(new UserAccessUrlFilter(), BasicAuthenticationFilter.class)
我尝试了各种教程和方法,包括尝试使用@ControllerAdvice和@ExceptionHandler组合,但是似乎没有任何东西可以捕获这些401错误。 我正在将Thymeleaf 5.0用作模板引擎。不知道这是否有效。