在 twig 中,我生成了一个 csrf token ({{ csrf_token('my_intention') }}
)。
在 Javascript 中,我使用 ajax 调用 Controller ,实际上是使用 Fetch API(Ajax xmlHttpRequest 也尝试过),POST 请求。包含请求中传递的 token 的参数名称是“token=abcdef...”。
Ajax :
var httpRequest = new XMLHttpRequest();
httpRequest.onreadystatechange = function (data) {
console.log(data);
};
httpRequest.open('POST', el.getAttribute("data-url"));
httpRequest.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
httpRequest.send(.......);
获取 API:
fetch(el.getAttribute('data-url'), {
method: 'post',
headers: {
"Content-type": "application/x-www-form-urlencoded; charset=UTF-8"
},
body: 'token=' + encodeURIComponent(el.getAttribute('data-token'))
}).then(data => data.text()).then(data => {...}
在调用的 Controller 操作中,我从 POST 请求中获取作为数据发送的 token 。我在 Controller 中这样检查 token :
$token = $request->request->get('token');
if (!$this->isCsrfTokenValid('my_intention', $token)) {
throw new InvalidCsrfTokenException("error csrf 2");
}
但是 Symfony 说 token 无效。
我不确定,但我认为在 session 变量中找不到 token 。在 isTokenValid()
$this->storage->hasToken($token->getId())
中返回 false。
在浏览器中直接调用url就可以了。
在 twig 中,我将 url 设置为调用这样的数据属性 data-url="{{ path('_check', {'id': transaction.id}) }}"
,然后我从 javascript 读取此数据属性并将其传递给 ajax/fetch 函数。
我不明白,我的代码有什么问题?
交响乐 3.1.3
编辑: 已解决:我没有在 header 请求中传递凭据,因此,Symfony 无法找到 session 并检查 token :
fetch(el.getAttribute('data-url'), {
method: 'post',
headers: {
"Content-Type": "application/x-www-form-urlencoded; charset=UTF-8",
"X-Requested-With": "XMLHttpRequest"
},
body: 'token=' + el.getAttribute('data-token'),
credentials: 'include'
}).then(data => data.text()).then(data => {
最佳答案
即使您找到了问题的答案,我还是建议您看一下这个包,它根据在服务器端定义的 Cookie 处理 token 验证,您应该传入每个异步请求。
关于ajax - Symfony 3、 "ajax request"带获取 API 和 CSRF,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39424777/