Spring Security的FailureHandler触发时机
今天遇到一个问题,场景是在查询数据库的过程中,想要将查询过程中出现的错误和异常进行抛出,并交由SpringSecurity 自定义的失败处理器FailureHandler处理,本以为只要抛出异常就会被SpringSecurity的异常过滤器链拦截,结果不管怎么处理都没有实现
后来看了以下SpringSecurity的异常处理源码,发现SpringSecurity只处理框架异常处理类AuthenticationException的异常
具体源码如下 AbstractAuthenticationProcessingFilter的doFilter方法
public void doFilter(ServletRequest req, ServletResponse res, FilterChain chain) throws IOException, ServletException {
HttpServletRequest request = (HttpServletRequest)req;
HttpServletResponse response = (HttpServletResponse)res;
if (!this.requiresAuthentication(request, response)) {
chain.doFilter(request, response);
} else {
if (this.logger.isDebugEnabled()) {
this.logger.debug("Request is to process authentication");
}
Authentication authResult;
try {
authResult = this.attemptAuthentication(request, response);
if (authResult == null) {
return;
}
this.sessionStrategy.onAuthentication(authResult, request, response);
} catch (InternalAuthenticationServiceException var8) {
this.logger.error("An internal error occurred while trying to authenticate the user.", var8);
this.unsuccessfulAuthentication(request, response, var8);
return;
//对AuthenticationException进行处理
} catch (AuthenticationException var9) {
this.unsuccessfulAuthentication(request, response, var9);
return;
}
if (this.continueChainBeforeSuccessfulAuthentication) {
chain.doFilter(request, response);
}
this.successfulAuthentication(request, response, chain, authResult);
}
}
由此可以得出结论,想要被SpringSecurity处理异常,就要抛出一个继承了AuthenticationException的异常即可
20201126备注
继承AuthenticationException需要是SpringSecurity包下的