如何使用Axios将CSRF Coo​​kie从React发送到Django Rest Framework [英] How to send CSRF Cookie from React to Django Rest Framework with Axios

查看:153
本文介绍了如何使用Axios将CSRF Coo​​kie从React发送到Django Rest Framework的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想使用 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 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. rel ="nofollow noreferrer">此处

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 Coo​​kie从React发送到Django Rest Framework的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆