Customizing CSRF Error Page in Spring Security

Usually, when the page remains until the session expires and I try to send the POST action, the CSRF token generated by Spring Security will not match the expected server value. The error in this case is the expected result.

However, I always get the default Tomcat 403 error, which is pretty ugly. This is caused by a 403 error created by the security filter.

However, I would like to catch a specific CSRF error to perform a custom action. Namely, the following will not work, because the error occurs 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 the index page (or something else) seems like a good solution. How can I catch an invalid CSRF token error and configure a server response?

+4
1

CSRF Spring CsrfFilter. AccessDeniedHandler

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

,

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

Source: https://habr.com/ru/post/1612710/


All Articles