Session timeout leads to Access Denied in Spring MVC when CSRF integration with Spring Security

前端 未结 2 1166
终归单人心
终归单人心 2021-01-02 04:46

I have Integrated CSRF token with Spring Security in my Spring MVC Project. Everything work properly with CSRF token, token will be send from client side to server side. <

2条回答
  •  青春惊慌失措
    2021-01-02 05:36

    The question is a bit old, but answers are always useful.

    First, this is a known issue with session-backed CSRF tokens, as described in the docs: CSRF Caveats - Timeouts.

    To solve it, use some Javascript to detect imminent timeouts, use a session-independent CSRF token repository or create a custom AccessDeniedHandler route. I chose the latter:

    Config XML:

    
        
        
    
    
    
        
    
    

    MyAccessDeniedHandler:

    public class MyAccessDeniedHandler implements AccessDeniedHandler {
        /* ... */
        @Override
        public void handle(HttpServletRequest request, HttpServletResponse response, AccessDeniedException exception)
                throws IOException, ServletException {
            if (exception instanceof MissingCsrfTokenException) {
                /* Handle as a session timeout (redirect, etc).
                Even better if you inject the InvalidSessionStrategy
                used by your SessionManagementFilter, like this:
                invalidSessionStrategy.onInvalidSessionDetected(request, response);
                */
            } else {
                /* Redirect to a error page, send HTTP 403, etc. */
            }
        }
    }
    

    Alternatively, you can define the custom handler as a DelegatingAccessDeniedHandler:

    
        
            
                
                    
                        
                    
                
            
        
        
            
                
            
        
    
    

提交回复
热议问题