我正在使用Spring MVC @ControllerAdvice
并@ExceptionHandler
处理REST Api的所有异常。对于Web mvc控制器抛出的异常,它工作正常,但对于Spring Security自定义过滤器抛出的异常,它不工作,因为它们在调用控制器方法之前运行。
我有一个自定义的spring安全过滤器,它执行基于令牌的身份验证:
public class AegisAuthenticationFilter extends GenericFilterBean {
...
public void doFilter(ServletRequest req, ServletResponse res, FilterChain chain) throws IOException, ServletException {
try {
...
} catch(AuthenticationException authenticationException) {
SecurityContextHolder.clearContext();
authenticationEntryPoint.commence(request, response, authenticationException);
}
}
}
使用此自定义入口点:
@Component("restAuthenticationEntryPoint")
public class RestAuthenticationEntryPoint implements AuthenticationEntryPoint{
public void commence(HttpServletRequest request, HttpServletResponse response, AuthenticationException authenticationException) throws IOException, ServletException {
response.sendError(HttpServletResponse.SC_UNAUTHORIZED, authenticationException.getMessage());
}
}
并使用此类来全局处理异常:
@ControllerAdvice
public class RestEntityResponseExceptionHandler extends ResponseEntityExceptionHandler {
@ExceptionHandler({ InvalidTokenException.class, AuthenticationException.class })
@ResponseStatus(value = HttpStatus.UNAUTHORIZED)
@ResponseBody
public RestError handleAuthenticationException(Exception ex) {
int errorCode = AegisErrorCode.GenericAuthenticationError;
if(ex instanceof AegisException) {
errorCode = ((AegisException)ex).getCode();
}
RestError re = new RestError(
HttpStatus.UNAUTHORIZED,
errorCode,
"...",
ex.getMessage());
return re;
}
}
我需要做的就是返回一个详细的JSON正文,即使对于spring security AuthenticationException也是如此。有没有办法让Spring Security AuthenticationEntryPoint和Spring MVC @ExceptionHandler一起工作?
我正在使用Spring Security 3.1.4和Spring MVC 3.2.4。
(@)ExceptionHandler
仅当请求由处理时,才能工作DispatcherServlet
。但是,此异常在此之前发生,因为它由抛出Filter
。因此,您将永远无法使用来处理此异常(@)ExceptionHandler
。