如何使用Axios将CSRF Coo​​kie从React发送到Django Rest Framework

时间:2019-01-08 18:19:11

标签: reactjs django-rest-framework axios csrf django-csrf

我想使用 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);
    })
  }

这是我的setings.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"

1 个答案:

答案 0 :(得分:2)

Django默认使用X-CSRFTOKEN作为csrf标头,请参见here。您在Django设置中使用的选项CSRF_COOKIE_NAME仅更改cookie名称,默认情况下为cookie名称,csrftoken,请参见here

要解决您的问题,请在axios调用headers: { 'X-CSRFTOKEN': csrfCookie }中使用此标头。另外,从Django设置的XSRF-TOKEN中删除CORS_ALLOW_HEADERS,然后向其中添加X-CSRFTOKEN

使用以下内容:

axios.post('http://127.0.0.1:8000/es/api-auth/login/',
    {
        next: '/',
        username: 'admin@admin.com',
        password: 'Cancun10!',
    },
    {
        headers: {
             'X-CSRFTOKEN': csrfCookie,
         },
    },
)