reactjs - 如何使用 Axios 将 CSRF Cookie 从 React 发送到 Django Rest Framework
问题描述
我想使用Axios从React应用程序向Django Rest Framework后端发出POST请求。我已经设法从后端获取了一个CSRF 令牌,但我无法将它与我的请求一起发送,所以我总是收到一个错误:Forbidden (CSRF cookie not set.)
这是我的React应用程序的代码:
handleClick() {
const axios = require('axios');
var csrfCookie = Cookies.get('XSRF-TOKEN');
console.log(csrfCookie)
axios.post('http://127.0.0.1:8000/es/api-auth/login/',
{
next: '/',
username: 'admin@admin.com',
password: 'Cancun10!',
},
{
headers: {
'x-xsrf-token': csrfCookie, // <------- Is this the right way to send the cookie?
},
withCredentials = true,
}
)
.then(function (response) {
console.log(response);
})
.catch(function (error) {
console.log(error);
})
}
这是我的settings.py
CSRF 配置:
CORS_ALLOW_CREDENTIALS = True
CORS_ALLOW_HEADERS = (
'xsrfheadername',
'xsrfcookiename',
'content-type',
'XSRF-TOKEN',
)
CORS_ORIGIN_WHITELIST = serverconfig.CORS_ORIGIN_WHITELIST
CSRF_TRUSTED_ORIGINS = serverconfig.CSRF_TRUSTED_ORIGINS
CSRF_COOKIE_NAME = "XSRF-TOKEN"
解决方案
DjangoX-CSRFTOKEN
默认用作 csrf 标头,请参见此处。CSRF_COOKIE_NAME
您在 Django 设置中使用的选项仅更改 cookie 名称,默认情况下为csrftoken
,请参见此处。
要解决您的问题,请在您的 axios 调用中使用此标头:headers: { 'X-CSRFTOKEN': csrfCookie }
.
使用以下内容:
axios.post('http://127.0.0.1:8000/es/api-auth/login/',
{
next: '/',
username: 'admin@admin.com',
password: 'Cancun10!',
},
{
headers: {
'X-CSRFTOKEN': csrfCookie,
},
},
)
此外,XSRF-TOKEN
从CORS_ALLOW_HEADERS
您的 Django 设置中删除,然后添加X-CSRFTOKEN
到它。如果您不想删除XSRF-TOKEN
,可以安全地添加X-CSRFTOKEN
以下CORS_ALLOW_HEADERS
文档,此处的文档
# settings.py
from corsheaders.defaults import default_headers
CORS_ALLOW_HEADERS = list(default_headers) + [
'X-CSRFTOKEN',
]
推荐阅读
- django - 模板上显示的Django外键多对一关系
- javascript - 无法在打字稿中设置接口类型的属性
- node.js - 密码执行的问题
- python - 线性回归的偏差和方差计算
- c# - Unity3D,C#如何保存对象的位置并稍后重新启动它们?
- selenium - 通过 Python 代码子进程打开 Jupyter Notebook
- python - 使用 python sdk 创建一个 auth ConfigMap
- java - 将二进制 1 和 0 的整数(或字符串)数组转换为它们在 Java 中的 alpha 等效项
- c# - 来自 webapi 的响应,字节数组为 null
- python - UnsatisfiableError: pyqt 和 py-opencv 冲突