[英]Django CSRF failure, using React forms
I'm having a problem with CSRF with Django and React.我在使用 Django 和 React 时遇到 CSRF 问题。
I have read through the already high number of questions around this, as well as the django docs naturally.我已经阅读了大量关于此的问题,以及自然而然的 django 文档。 I have tried every possible combination of different things that should address the issue but am still struggling with it.我已经尝试了各种可能的组合来解决这个问题,但仍然在努力解决这个问题。
Firstly I tried to create a register page, but when I POST to register/ I get CSRF cookie not set, 403.首先,我尝试创建一个注册页面,但是当我 POST 注册/我未设置 CSRF cookie 时,403。
I have gone so far as disabling the CSRF middleware [bad I know, just trying to get somewhere] and I am getting 405s, method not allowed [attempting to post].我已经禁用了 CSRF 中间件 [我知道很糟糕,只是想到达某个地方] 并且我收到了 405,方法不允许 [尝试发布]。 I just thought maybe this is something someone has run into before or sounds familiar and could give some guidance?我只是想也许这是某人以前遇到过或听起来很熟悉的东西,可以提供一些指导吗?
I have tried: - adding the decorator @csrf_exempt, - adding the CSRF to the header of a request, - attaching the whole cookie, - attaching a hidden form field with the token.我尝试过: - 添加装饰器 @csrf_exempt, - 将 CSRF 添加到请求的标头, - 附加整个 cookie, - 附加带有令牌的隐藏表单字段。
I am using this seed project: https://github.com/Seedstars/django-react-redux-base if anyone wants to have a look, I've done a bit in React, but not a lot on the Django side, so it isn't far off what's there我正在使用这个种子项目: https : //github.com/Seedstars/django-react-redux-base如果有人想看看,我在 React 中做了一些,但在 Django 方面做得不多,所以离那里不远
You should not disable the csrf check in django.你不应该在 django 中禁用 csrf 检查。 Instead in your form/template simply do {% csrf_token %}
not {{ csrf_token }}
It will print a hidden form element with value assigned to your csrf token already.相反,在您的表单/模板中,只需执行{% csrf_token %}
而不是{{ csrf_token }}
它将打印一个隐藏的表单元素,其值已经分配给您的 csrf 令牌。
If you are using ajax, you can simply set your ajax headers globally as:如果您使用的是 ajax,您可以简单地将 ajax 标头全局设置为:
$.ajaxSetup({
beforeSend: function (xhr, settings) {
// this time double brackets
xhr.setRequestHeader("X-CSRFToken", "{{csrf_token}}");
}
});
if you are using fetch then:如果您正在使用 fetch 那么:
fetch('some/url/here', {
method: 'GET',
headers: {
'X-CSRFToken': window.CSRF_TOKEN // or pass it in your own way
}
}).then(function (response) {
return response.json()
})
These are pretty much all the ones i can think of.这些几乎是我能想到的所有。
Hope this helps.希望这可以帮助。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.