title: Spring security Session Timeout handling for Ajax calls redirect to login not working
body: <p>There are a lot of questions like <a href="https://stackoverflow.com/questions/24730917/spring-security-session-timeout-handling-for-ajax-calls">this one</a> similar to my question but not working. I am following <a href="https://doanduyhai.wordpress.com/2012/04/21/spring-security-part-vi-session-timeout-handling-for-ajax-calls/" rel="nofollow noreferrer">this blog</a> to redirect ajax request to login page when session timeout but in my case it is not working. here is the code </p>
  
  <pre><code>import java.io.IOException;
  
  import javax.servlet.FilterChain;
  import javax.servlet.ServletException;
  import javax.servlet.ServletRequest;
  import javax.servlet.ServletResponse;
  import javax.servlet.http.HttpServletRequest;
  import javax.servlet.http.HttpServletResponse;
  
  import org.slf4j.Logger;
  import org.slf4j.LoggerFactory;
  import org.springframework.security.access.AccessDeniedException;
  import org.springframework.security.authentication.AuthenticationTrustResolver;
  import org.springframework.security.authentication.AuthenticationTrustResolverImpl;
  import org.springframework.security.core.AuthenticationException;
  import org.springframework.security.core.context.SecurityContextHolder;
  import org.springframework.security.web.DefaultRedirectStrategy;
  import org.springframework.security.web.RedirectStrategy;
  import org.springframework.security.web.util.ThrowableAnalyzer;
  import org.springframework.security.web.util.ThrowableCauseExtractor;
  import org.springframework.web.filter.GenericFilterBean;
  
  public class AjaxTimeoutRedirectFilter extends GenericFilterBean{
  
      private static final Logger logger = LoggerFactory.getLogger(AjaxTimeoutRedirectFilter.class);
  
      private ThrowableAnalyzer throwableAnalyzer = new DefaultThrowableAnalyzer();
      private AuthenticationTrustResolver authenticationTrustResolver = new AuthenticationTrustResolverImpl();
  
      private final RedirectStrategy redirectStrategy = new DefaultRedirectStrategy();
  
      private int customSessionExpiredErrorCode = 901;
  
      @Override
      public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException
      {
          try
          {
              chain.doFilter(request, response);
  
              logger.debug("Chain processed normally");
          }
          catch (IOException ex)
          {
              throw ex;
          }
          catch (Exception ex)
          {
              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)
              {
                  if (ase instanceof AuthenticationException)
                  {
                      throw ase;
                  }
                  else if (ase instanceof AccessDeniedException)
                  {
  
                      if (authenticationTrustResolver.isAnonymous(SecurityContextHolder.getContext().getAuthentication()))
                      {
                          HttpServletRequest httpReq = (HttpServletRequest) request;
  
                          logger.info("User session expired or not logged in yet");
                          String ajaxHeader = ((HttpServletRequest) request).getHeader("X-Requested-With");
  
                          if ("XMLHttpRequest".equals(ajaxHeader))
                          {
                              logger.info("Ajax call detected, send {} error code", this.customSessionExpiredErrorCode);
  
  
                              ((HttpServletResponse)response).sendRedirect("/home/login");
  
  
  
                              return;
                          }else
                          {
  
                              ((HttpServletResponse)response).sendRedirect("/home/login");
                              logger.info("Redirect to login page");
                              return;
                          }
                      }
                      else
                      {
                          this.redirectStrategy.sendRedirect((HttpServletRequest) request, (HttpServletResponse) response,"/home/login");
                          return; 
                      }
                  }
              }
  
          }
      }
  
  
  
      private static final class DefaultThrowableAnalyzer extends ThrowableAnalyzer
      {
          /**
           * @see org.springframework.security.web.util.ThrowableAnalyzer#initExtractorMap()
           */
          protected void initExtractorMap()
          {
              super.initExtractorMap();
  
              registerExtractor(ServletException.class, new ThrowableCauseExtractor()
              {
                  public Throwable extractCause(Throwable throwable)
                  {
                      ThrowableAnalyzer.verifyThrowableHierarchy(throwable, ServletException.class);
                      return ((ServletException) throwable).getRootCause();
                  }
              });
          }
  
      }
  
      public void setCustomSessionExpiredErrorCode(int customSessionExpiredErrorCode)
      {
          this.customSessionExpiredErrorCode = customSessionExpiredErrorCode;
      }
  }
  </code></pre>
  
  <p>I have added this <code>&lt;security:custom-filter ref="ajaxTimeoutRedirectFilter" after="EXCEPTION_TRANSLATION_FILTER"/&gt;</code> and the ajaxTimeoutRedirectFilter bean in the xml configuration file but not working. When i debug it goes to redirect code but the redirect is not redirecting to login.</p>