Spring 安全异常由ExceptionTranslationFilter 处理。您可以创建一个处理AuthenticationException 的自定义过滤器并将其添加到ExceptionTranslationFilter 之后。默认 Spring 安全 Filter Ordering.
public class AuthenticationExceptionFilter extends GenericFilterBean {
@Override
public void doFilter(final ServletRequest request, final ServletResponse response, final FilterChain chain) throws IOException, ServletException {
try {
chain.doFilter(request, response);
} catch (final Exception exception) {
if (exception instanceof AuthenticationException) {
this.logger.debug("Authentication exception occurred; redirecting to authentication entry point", exception);
}
if(exception instanceof AccessDeniedException) {
....
}
// Check ExceptionTranslationFilter#handleSpringSecurityException(...)
}
您可以通过重写WebSecurityConfigurerAdapter 的配置方法以编程方式注册过滤器。
@Configuration
public class CustomWebSecurityConfigurerAdapter extends WebSecurityConfigurerAdapter {
@Override
protected void configure(HttpSecurity http) throws Exception {
http.addFilterAfter(new AuthenticationExceptionFilter(), ExceptionTranslationFilter.class);
}
对于所有 @RequestMapping 的集中式异常处理:
查看ResponseEntityExceptionHandler
@ControllerAdvice 类的方便基类
提供跨所有@RequestMapping 的集中式异常处理
方法通过@ExceptionHandler 方法。
这个基类提供了一个@ExceptionHandler 方法来处理
内部 Spring MVC 异常。
这里有一个示例代码 sn-p 可以帮助您入门:
@ControllerAdvice
public class ExceptionHandler extends ResponseEntityExceptionHandler {
....
@ExceptionHandler({Exception.class})
public ResponseEntity<Object> handleCustomException(final CustomException exception, final WebRequest request) {
return handleExceptionInternal(exception,
ErrorOutputDto.create(exception.getErrorIdentifier(), exception.getMessage()),
new HttpHeaders(),
HttpStatus.UNAUTHORIZED,
request);
}
....