What is the best way to handle Invalid CSRF token found in the request when session times out in Spring security

The easiest way I found to handle invalidate CSRF token when session times out at the login page is one of the followings:

  1. Redirect the request again to the login page again vi CustomAccessDeniedHandler:

    static class CustomAccessDeniedHandler extends AccessDeniedHandlerImpl{
    
    
    
    
        @Override
        public void handle(HttpServletRequest request,
                HttpServletResponse response,
    
      AccessDeniedException accessDeniedException)
        throws IOException, ServletException {
    if (accessDeniedException instanceof MissingCsrfTokenException
            || accessDeniedException instanceof InvalidCsrfTokenException) {
    
        if(request.getRequestURI().contains("login")){
            response.sendRedirect(request.getContextPath()+"/login");                                        
        }
    }
    
    super.handle(request, response, accessDeniedException);
    
    
    
     }
    }
    
  2. Add refresh header as Neil McGuigan suggested:

<meta http-equiv="refresh" content="${pageContext.session.maxInactiveInterval}">

  1. Furthermore you must create a bean for the new CustomAccessDeniedHandler and register it. The following example shows this for Java config.

In any config class:

@Bean
public AccessDeniedHandler accessDeniedHandler() {
    return new CustomAccessDeniedHandler();
}

In your security config modify the configure method as follows:

@Override
protected void configure(final HttpSecurity http) throws Exception {
    http
      // ...
      .and()
      .exceptionHandling().accessDeniedHandler(accessDeniedHandler());
}

Also see here.

a more Optimum solution will be for Spring security to handle this situation in their framework.