在Spring Security中自定义CSRF错误页面

usr*_*ΛΩΝ 5 spring spring-security csrf-protection

通常,当页面一直待到会话到期并且我尝试提交POST操作时,Spring Security生成的CSRF令牌将不匹配服务器的预期值.在这种情况下,错误是预期的结果.

但是,我总是得到默认的Tomcat 403错误,这是非常难看的.它是由安全筛选器抛出的403错误引起的.

但是,我想拦截特定的CSRF错误以执行自定义操作.即,以下操作无效,因为错误比MVC管道早得多

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

    return "redirect:/index.jsp";
}
Run Code Online (Sandbox Code Playgroud)

重定向到索引页面(或其他)似乎是一个很好的解决方案.如何拦截错误的CSRF令牌错误并自定义服务器响应?

Mar*_*ski 4

为了检查 CSRF Spring Security 使用CsrfFilter. 如果令牌丢失或无效,则使用 AccessDeniedHandler

if (missingToken) {
                accessDeniedHandler.handle(request, response,
                        new MissingCsrfTokenException(actualToken));
            }
            else {
                accessDeniedHandler.handle(request, response,
                        new InvalidCsrfTokenException(csrfToken, actualToken));
            }
Run Code Online (Sandbox Code Playgroud)

因此,处理此错误的一种方法可能是此处理程序的自己实现

@Override
  public void configure(HttpSecurity http) throws Exception {
    HttpSecurity http = http.exceptionHandling().accessDeniedHandler(myAccessDeniedHandler);
}
Run Code Online (Sandbox Code Playgroud)