在系统中通常有这样的情况,我们在发送ajax请求时,由于长时间没操作系统,用户登录的session超时了,因此通过ajax得到的结果 ,直接就是登录页面的html代码,而不是跳转到登录页面或者是提示用户,登录已超时。
那么,解决的方案就明显了,就是要在spring返回登录页面之前 ,判断该请求是否为ajax请求,是则返回信息,提示用户登录已超时。
我们知道,在处理我们自定义的认证过滤器时,如果抛出一个AccessDeniedException, spring security就会帮我们跳转到登录页上,那么spring security是如何拦截并跳转到?
这个我们得看下spring security的ExceptionTranslationFilter过滤器,它就是用于处理该过滤器之后的过滤器中所产生的异常并完成跳转的。
这也就是,为什么我们自定义的认证过滤器,要配置在ExceptionTranslationFilter过滤器之后,才能被spring security拦截并响应。
接下来就先了解下ExceptionTranslationFilter是怎样去处理的:
public void doFilter(ServletRequest req, ServletResponse res, FilterChain chain)
throws IOException, ServletException {
HttpServletRequest request = (HttpServletRequest) req;
HttpServletResponse response = (HttpServletResponse) res;
try {
chain.doFilter(request, response);
logger.debug("Chain processed normally");
}
catch (IOException ex) {
throw ex;
}
catch (Exception ex) {
// Try to extract a SpringSecurityException from the stacktrace
Throwable[] causeChain = throwableAnalyzer.determineCauseChain(ex);
RuntimeException ase = (AuthenticationException)
throwableAnalyzer.getFirstThrowableOfType(AuthenticationException.class, causeChain);
if (ase == null) {
ase = (AccessDeniedException)throwableAnalyzer.getFirstThrowableOfType(AccessDeniedException.class, causeChain);
}
if (ase != null) {
// 获取安全异常,并进行异常处理
handleSpringSecurityException(request, response, c