首页 > 解决方案 > 如何使用 Axios 将 CSRF Coo​​kie 从 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.pyCSRF 配置:

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"

标签: reactjsdjango-rest-frameworkaxioscsrfdjango-csrf

解决方案


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-TOKENCORS_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',
]

推荐阅读