我正在使用Spring MVC @ControllerAdvice并@ExceptionHandler处理REST Api的所有异常.它适用于Web mvc控制器抛出的异常,但它不适用于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);
}
}
}
Run Code Online (Sandbox Code Playgroud)
使用此自定义入口点:
@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());
}
}
Run Code Online (Sandbox Code Playgroud)
并使用此类来处理全局异常:
@ControllerAdvice
public class RestEntityResponseExceptionHandler extends ResponseEntityExceptionHandler {
@ExceptionHandler({ InvalidTokenException.class, AuthenticationException.class })
@ResponseStatus(value = HttpStatus.UNAUTHORIZED) …Run Code Online (Sandbox Code Playgroud)