如何禁用我网站中特定页面的 csrf 保护?

How to disable csrf protection for particular pages in my website?

使用 CSRF 保护,以便其他网站发出的任何请求都不会影响我的网站造成伤害。 spring security csrf文档中说csrf是申请put post patch delete requests.

但据我了解,login/signup表单不需要csrf保护,因为它们已经需要用户名和密码形式的凭据,即使这样的请求是从另一个网站发出的,也会有没有坏处,因为用户只会登录。

但由于登录通常是 post 请求,默认情况下 spring 将自动在此处应用 csrf。这意味着我需要将 csrf 令牌生成参数作为隐藏输入字段添加到我的表单中,如下所示:

<form th:action="@{/login}" method="post">    
    <fieldset>
        <input type="hidden" 
             th:name="${_csrf.parameterName}" 
             th:value="${_csrf.token}" />
    </fieldset>
    ...
</form>

如果我不添加这个,403 Forbidden error 就会来。但是如果我像这样禁用这个 csrf ..:[=​​12=]

@Override
protected void configure(HttpSecurity http) throws Exception {
    http.csrf().disable();
}

然后网站所有页面都失去了csrf保护。如何将 csrf 应用于某些页面而不应用于其他页面,即使它们发出 post 请求?

我正在使用 Spring Boot + Spring Security + thymeleaf

您可以在 configure(HttpSecurity http)

中使用 .csrf().ignoringAntMatchers("/login")

csrf().ignoringAntMatchers("String")

允许指定不应使用 CSRF 保护的 HttpServletRequest,即使它们匹配 requireCsrfProtectionMatcher(RequestMatcher)。

For example, the following configuration will ensure CSRF protection ignores:

  • Any GET, HEAD, TRACE, OPTIONS (this is the default)
  • We also explicitly state to ignore any request that starts with "/sockjs/"
    http
          .csrf()
              .ignoringAntMatchers("/sockjs/**")
              .and()
          ...

.csrf().ignoringRequestMatchers(requestMatchers)

Allows specifying HttpServletRequests that should not use CSRF Protectioneven if they match the requireCsrfProtectionMatcher(RequestMatcher).

For example, the following configuration will ensure CSRF protection ignores:

  • Any GET, HEAD, TRACE, OPTIONS (this is the default)
  • We also explicitly state to ignore any request that has a "X-Requested-With: XMLHttpRequest" header
http
     .csrf()
         .ignoringRequestMatchers(request -> "XMLHttpRequest".equals(request.getHeader("X-Requested-With")))
         .and()