我正在尝试过滤在我的应用程序中进行用户身份验证期间引发的 AuthenticationException。我知道这些不能用 @ControllerAdvice 和 @ExceptionHandler 进行过滤。因此,尝试找出任何处理程序都可以解决我的问题。
已经尝试了不同的方法,例如AuthenticationFailureHandler,但它们不符合我的要求,因为我正在使用ResourceServerConfigurerAdapter。
请提出建议。
最佳答案
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
A convenient base class for @ControllerAdvice classes that wish to provide centralized exception handling across all @RequestMapping methods through @ExceptionHandler methods.
This base class provides an @ExceptionHandler method for handling internal Spring MVC exceptions.
下面是一个示例代码片段,可帮助您入门:
@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);
}
....
关于java - 过滤或处理 OAuth2 中的 AuthenticationException,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56061801/