Search code examples
springspring-securitycsrf-protection

Customizing CSRF error page in Spring Security


Normally when a page is left until session expiration and I try to submit a POST action, the CSRF token generated by Spring Security will not be matching the server's expected value. An error is the expected result in this case.

However, I always get the default Tomcat 403 error which is pretty ugly. It is caused by the 403 error thrown by the security filter.

However, I would like to intercept the specific CSRF error in order to perform a custom action. Namely, the following won't work because the error is thrown much earlier than the MVC pipeline

@ExceptionHandler(CsrfException.class)
public String exception(CsrfException ex)
{
    log.error(ex.getMessage(), ex);

    return "redirect:/index.jsp";
}

Redirecting to an index page (or whatever) seems a good solution. How can I intercept the wrong CSRF token error and customize server response?


Solution

  • For checking CSRF Spring Security uses CsrfFilter. In case of missing or invalid token it uses AccessDeniedHandler

    if (missingToken) {
                    accessDeniedHandler.handle(request, response,
                            new MissingCsrfTokenException(actualToken));
                }
                else {
                    accessDeniedHandler.handle(request, response,
                            new InvalidCsrfTokenException(csrfToken, actualToken));
                }
    

    So one way to handle this error may be a own implementation of this handler

    @Override
      public void configure(HttpSecurity http) throws Exception {
        HttpSecurity http = http.exceptionHandling().accessDeniedHandler(myAccessDeniedHandler);
    }