【问题标题】:Spring-Boot Post request with csrf header带有 csrf 标头的 Spring-Boot Post 请求
【发布时间】:2020-12-29 11:27:02
【问题描述】:

在开发我的 Spring Boot 应用程序时,我禁用了 csrf;但现在我需要启用它。我关注了 Spring Docs here,但我不断收到“SyntaxError: Invalid header name”。在我发出 POST 请求的 javascript 文件中。我在这里做错了什么吗?

这是在我的 HTML 页面顶部的标题中,用于此功能:

<meta name="_csrf" content="${_csrf.token}"/>
<meta name="_csrf_header" content="${_csrf.headerName}"/>

这是发出请求的 JavaScript 文件:

var request = new XMLHttpRequest();
request.onreadystatechange = function() {
  if (request.readyState == XMLHttpRequest.DONE) {
      location.reload();
  }
}

// Headers for CSRF protection
var token = $("meta[name='_csrf']").attr("content");
var header = $("meta[name='_csrf_header']").attr("content");

request.open("POST", "/admin/delete-email");
request.setRequestHeader(header, token);  <-- This line throws syntax error.
request.send(formData);

这里是安全配置:

@Override
public void configure(HttpSecurity http) throws Exception {
  // The following snippet opens the entire app
  // http.authorizeRequests().antMatchers("/**").permitAll();

  //http.csrf().disable();
  http.authorizeRequests()
    .antMatchers("/admin/**")
    .hasRole("ADMIN")
    .antMatchers("/db/**")
    .hasRole("ADMIN")
    .and()
    .formLogin()
    .permitAll()
    .and()
    .httpBasic();
  }

我在使用表单发出 POST 请求时也收到 403 错误:

<form method="POST" enctype="multipart/form-data" action="/admin/add-email">
    <td class="tg-0pky"><input type="text" name="employeeId"/></td>
    <td class="tg-0pky"><input type="text" name="email"/></td>
    <td class="tg-0pky"><input type="submit" value="Upload"/></td>
    <input type="hidden" name="${_csrf.parameterName}" value="${_csrf.token}"/>
</form>

【问题讨论】:

    标签: javascript java spring-boot csrf


    【解决方案1】:

    想通了。由于我使用的是 Thymeleaf,我需要使用 th: 命名空间。

    <meta th:name="_csrf" th:content="${_csrf.token}"/>
    <meta th:name="_csrf_header" th:content="${_csrf.headerName}"/>
    

    <form method="POST" enctype="multipart/form-data" action="/admin/add-email">
      <td class="tg-0pky"><input type="text" name="employeeId"/></td>
      <td class="tg-0pky"><input type="text" name="email"/></td>
      <td class="tg-0pky"><input type="submit" value="Upload"/></td>
      <input type="hidden" th:name="${_csrf.parameterName}" th:value="${_csrf.token}"/>
    </form>
    

    【讨论】:

      猜你喜欢
      • 2020-09-29
      • 2019-12-26
      • 2017-08-31
      • 1970-01-01
      • 1970-01-01
      • 2013-08-03
      • 2020-01-13
      • 1970-01-01
      • 2020-12-23
      相关资源
      最近更新 更多