CSRF验证在跨域POST请求的生产中失败 [英] CSRF Verification fails in production for Cross Domain POST request
问题描述
HTTP_X_CSRFTOKEN标头与csrftoken cookie内的内容不匹配。
The HTTP_X_CSRFTOKEN header does not match what is inside the csrftoken cookie.
如何检查cookie?跨域请求的响应标头中未显示Set-Cookie。
How can I examine the cookie? Set-Cookie is not displayed in the Response header for Cross Domain requests.
我已经按照以下说明进行操作:
I have already followed instructions found in:
使用Django的CSRF,使用Axios的React + Redux
有趣的是,我发现服务器请求标头上的 X-CSRFTOKEN转换为 HTTP_X_CSRFTOKEN。
Interestingly I found "X-CSRFTOKEN" translates to "HTTP_X_CSRFTOKEN" on the server request header.
在开发中工作正常env在localhost下(尽管我使用2个不同的端口-一个用于django,另一个用于我的前端)。
Works fine in the development env under localhost (although I am using 2 different ports - one for django and the other my frontend).
更新:
似乎没有为跨域请求正确设置csrktoken cookie(尽管浏览器在请求标头中显示了它),因此X-CSRFTOKEN未被发送。
It seems the csrktoken cookie is not correctly set for cross domain rquests (although the browser displays it in the Request Header) so the X-CSRFTOKEN does not get sent.
我最终添加了一个API调用,以使用GET请求返回当前的csrftoken,然后使用X-CSRFTOKEN标头将其发送回去。
I ended up adding an API call to return the current csrftoken using a GET request and then sending it back using the X-CSRFTOKEN header.
推荐答案
您还没有男人首先说明了如何从服务器获取 csrftoken
,因此,我假设它已经存在于您的浏览器中。
和 X-CSRFToken
标头一起,还使用 withCredentials:true
在请求中包含cookie。
我正在使用 js-cookie
库从cookie中获取 csrftoken
。
You haven't mentioned how you're getting the csrftoken
from the server in the first place, so I'm assuming it's already present in your browser.
Along with the X-CSRFToken
header, also include the cookies in the request using withCredentials: true
.
I'm using the js-cookie
library to get the csrftoken
from the cookies.
import Cookies from 'js-cookie';
axios({
url: 'http://localhost:8000/graphql',
method: 'post',
withCredentials: true,
data: {
query: `
{
// Your query here
}
`
},
headers: {
"X-CSRFToken": Cookies.get('csrftoken')
}
})
还要在您的 settings.py
中添加 CORS_ALLOW_CREDENTIALS = True
,前提是您使用的是 django-cors-headers
。否则,将不接受Cookie。
Also add CORS_ALLOW_CREDENTIALS = True
to your settings.py
, assuming you are using django-cors-headers
. Otherwise, the cookies won't be accepted.
这篇关于CSRF验证在跨域POST请求的生产中失败的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!