Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/spring/14.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Spring 如何为我的网站中的特定页面禁用csrf保护?_Spring_Spring Boot_Spring Security_Thymeleaf_Csrf - Fatal编程技术网

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

Spring 如何为我的网站中的特定页面禁用csrf保护?,spring,spring-boot,spring-security,thymeleaf,csrf,Spring,Spring Boot,Spring Security,Thymeleaf,Csrf,使用CSRF保护,以便其他网站发出的任何请求不会影响我的网站造成伤害。spring security csrf文档中说,csrf应用于put post patch delete请求 但据我了解,登录/注册表单不需要csrf保护,因为它们已经需要用户名和密码形式的凭据,即使是从其他网站发出这样的请求,也不会有任何伤害,因为用户只需登录即可 但由于登录通常是post请求,所以默认情况下,csrf将自动应用于此处。这意味着我需要将csrf令牌生成参数作为隐藏输入字段添加到我的表单中,如下所示: <

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

但据我了解,登录/注册表单不需要csrf保护,因为它们已经需要用户名和密码形式的凭据,即使是从其他网站发出这样的请求,也不会有任何伤害,因为用户只需登录即可

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

<form th:action="@{/login}" method="post">    
    <fieldset>
        <input type="hidden" 
             th:name="${_csrf.parameterName}" 
             th:value="${_csrf.token}" />
    </fieldset>
    ...
</form>
然后所有页面都会失去网站中的csrf保护。我如何将csrf应用于某些页面而不应用于其他页面,即使他们正在发出post请求

我使用的是Spring Boot+Spring Security+thymeleaf

您可以在
配置(HttpSecurity http)
中使用
.csrf().ignoringAntMatchers(“/login”)

csrf().ignoringAntMatchers(“字符串”)

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

例如,以下配置将确保CSRF保护 忽略:

  • 任何GET、HEAD、TRACE和选项(这是默认设置)
  • 我们还明确声明忽略以“/sockjs/”开头的任何请求

.csrf().ignoringRequestMatchers(requestMatchers)

允许指定不应使用CSRF的HttpServletRequests 保护即使它们与 requireCsrfProtectionMatcher(RequestMatcher)

例如,以下配置将确保CSRF保护 忽略:

  • 任何GET、HEAD、TRACE和选项(这是默认设置)
  • 我们还明确声明忽略任何具有“X-request-With:XMLHttpRequest”头的请求
@Override
protected void configure(HttpSecurity http) throws Exception {
    http.csrf().disable();
}
    http
          .csrf()
              .ignoringAntMatchers("/sockjs/**")
              .and()
          ...
http
     .csrf()
         .ignoringRequestMatchers(request -> "XMLHttpRequest".equals(request.getHeader("X-Requested-With")))
         .and()