我正在尝试向配置为使用 Spring Security 的服务器发送 POST 请求。提交请求时,我收到 403 错误。此问题是由于 CSRF 保护造成的。在我的 Spring Security 配置中禁用 CSRF 时,POST 请求工作正常。
我正在使用 fetch API 发送我的 POST 请求。这允许指定包含我尝试 POST 的 JSON 对象的正文附带的 HTTP header 。我现在尝试将 CSRF token 添加到我的 HTTP header 中。为此,我将以下两个元标记添加到 HTML 的 head 部分:
<meta name="_csrf" content="${_csrf.token}"/>
<meta name="_csrf_header" content="${_csrf.headerName}"/>
然后我将以下几行添加到我的 JavaScript 中:
const token = document.querySelector('meta[name="_csrf"]').content;
const header = document.querySelector('meta[name="_csrf_header"]').content;
let responsePromise = fetch(
"myEndpoint",
{ method: 'POST', headers: {'Content-Type': 'application/json', header: token}, body: JSON.stringify(myJSON) });
})
我假设 Spring Security 填写了我的 CSRF token 的内容。到目前为止,错误消息仍然存在。我认为我的 _csrf 元标记内可能没有任何内容。记录内容( token 和 header )时,我只收到:
${_csrf.headerName}
${_csrf.token}
虽然我希望看到 header 名称“X-CSRF-Token”和实际 token 。那么Spring security难道不会自动填写这个内容吗?
======更新:
我的项目是一个Maven项目。我已将 Thymeleaf 依赖项添加到我的 pom.xml 中。我对 thymeleaf 不太了解,但它似乎是使用 Spring Security 实现登录机制的最简单方法。无论如何,当在我的元标记中将 content
替换为 th:content
时,实际上找到了 header 和 token 并将其记录在我的控制台中。但我仍然无法发布我的请求,403 仍然存在。
最佳答案
在 thymeleaf 处理的属性前添加“th”
<meta name="_csrf" th:content="${_csrf.token}"/>
<meta name="_csrf_header" th:content="${_csrf.headerName}"/>
关于spring-security - 如何使用 fetch API 和 VanillaJS 将 CSRF token 添加到 HTTP header ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/70446346/