Исключения безопасности Spring обрабатываются ExceptionTranslationFilter
. Вы можете создать собственный фильтр, который обрабатывает AuthenticationException
и добавить его после ExceptionTranslationFilter
. Безопасность Spring по умолчанию Порядок фильтров .
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.
Вот пример кода, с которого можно начать:
@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);
}
....