如何使用 Axios 将 CSRF Cookie 从 React 发送到 Django Rest Framework [英] How to send CSRF Cookie from React to Django Rest Framework with Axios
问题描述
我想从使用 Axios 的 React 应用向 Django Rest Framework 后端发出 POST 请求.我设法从后端获得了一个 CSRF 令牌,但我无法通过我的请求发送它,所以我总是收到一个 Forbidden(CSRF cookie not set.)
错误:
I want to make a POST request from a React app using Axios to a Django Rest Framework backend. I have managed to get a CSRF Token from the backend but I can't manage to send it with my request, so I always get a Forbidden (CSRF cookie not set.)
error:
这是我的 React 应用程序的代码:
This is the code of my React app:
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 配置:
And this is my settings.py
CSRF configuration:
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"
推荐答案
Django 默认使用 X-CSRFTOKEN
作为 csrf 标头,参见 这里.您在 Django 设置中使用的选项 CSRF_COOKIE_NAME
仅更改 cookie 名称,默认情况下为 csrftoken
,请参阅 此处.
Django uses X-CSRFTOKEN
as the csrf header by default, see here. The option CSRF_COOKIE_NAME
you use in your Django settings only changes the cookie name, which by default is csrftoken
, see here.
要解决您的问题,请在 axios 调用中使用此标头:headers: { 'X-CSRFTOKEN': csrfCookie }
.
To solve your issue, use this header in your axios call: 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,
},
},
)
此外,从 Django 设置中的 CORS_ALLOW_HEADERS
中删除 XSRF-TOKEN
,并将 X-CSRFTOKEN
添加到其中.如果您不想删除 XSRF-TOKEN
,您可以使用以下文档安全地将 X-CSRFTOKEN
添加到 CORS_ALLOW_HEADERS
中,文档 这里
Also, remove XSRF-TOKEN
from CORS_ALLOW_HEADERS
in your Django settings, and add X-CSRFTOKEN
to it instead. If you don't feel like removing XSRF-TOKEN
, you can safely add X-CSRFTOKEN
to CORS_ALLOW_HEADERS
with the following, documentation here
# settings.py
from corsheaders.defaults import default_headers
CORS_ALLOW_HEADERS = list(default_headers) + [
'X-CSRFTOKEN',
]
这篇关于如何使用 Axios 将 CSRF Cookie 从 React 发送到 Django Rest Framework的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!