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

HuL*_*iCa 4 csrf django-csrf django-rest-framework reactjs axios

我想从使用AxiosReact应用程序向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);
    })
  }
Run Code Online (Sandbox Code Playgroud)

这是我的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"
Run Code Online (Sandbox Code Playgroud)

neb*_*ler 6

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

为了解决您的问题,在你的爱可信调用中使用此头: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,
         },
    },
)
Run Code Online (Sandbox Code Playgroud)

此外,XSRF-TOKENCORS_ALLOW_HEADERS您的 Django 设置中删除,然后添加X-CSRFTOKEN到它。如果你不喜欢删除XSRF-TOKEN,你可以放心地加入X-CSRFTOKENCORS_ALLOW_HEADERS与以下,文档在这里

# settings.py

from corsheaders.defaults import default_headers

CORS_ALLOW_HEADERS = list(default_headers) + [
    'X-CSRFTOKEN',
]
Run Code Online (Sandbox Code Playgroud)


小智 5

另外,如果你创建一个 axios 实例会更容易

const instance = axios.create({
  baseURL: API_URL,
  withCredentials: true,
  xsrfHeaderName: 'X-CSRFToken',
  xsrfCookieName: 'csrftoken',
})
Run Code Online (Sandbox Code Playgroud)

并确保xsrfCookieNameCSRF_COOKIE_NAME具有相同的名称。请注意,如果CSRF_COOKIE_HTTPONLY设置为 True,客户端 JavaScript 将无法访问 CSRF cookie:

const instance = axios.create({
  baseURL: API_URL,
  withCredentials: true,
  xsrfHeaderName: 'X-CSRFToken',
  xsrfCookieName: 'csrftoken',
})
Run Code Online (Sandbox Code Playgroud)