带有csrf标头的Spring-Boot Post请求

问题描述

在开发Spring Boot应用程序时,我禁用了csrf;但现在我需要启用它。我遵循了Spring Docs here,但我不断收到“ SyntaxError:无效的标题名称”。在我的javascript文件中发出POST请求。我在这里做错了什么吗?

此功能位于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>

解决方法

暂无找到可以解决该程序问题的有效方法,小编努力寻找整理中!

如果你已经找到好的解决方法,欢迎将解决方案带上本链接一起发送给小编。

小编邮箱:dio#foxmail.com (将#修改为@)