Forbidden (CSRF cookie not set.) but it is set by Axios in React (DRF)

Firstly, I'm getting csrf cookie by calling /auth/session/ endpoint then I'm setting header for csrf cookie, actual error occurs when I'm trying to login

Request

import axios from 'axios';
import Cookies from "universal-cookie";

const cookies = new Cookies();

const Login = () => {
  axios
  .get('http://localhost:8000/auth/session/')
  .then(({ data }) => {
    console.log(data)
  })
  .catch((error) => {
    console.log(error);
  });

  axios.defaults.xsrfHeaderName = 'X-CSRFToken'
  axios.defaults.xsrfCookieName = 'csrftoken'
  axios.defaults.headers.common['X-CSRFToken'] = cookies.get('csrftoken');

  const onSubmit = object => {
    axios.post(
      'http://localhost:8000/auth/login/',
      object,
    )
      .then(res => {
        if (res.status === 201)
          alert('Successfully authorized')
        else
          Promise.reject()
      })
      .catch(err => alert(err))
  }

actual request headers image

Response

Forbidden (CSRF cookie not set.): /auth/login/
news-board-web-1  | [16/Oct/2022 15:40:58] "POST /auth/login/ HTTP/1.1" 403 2870

response image

Settings

CSRF_TRUSTED_ORIGINS = [
    'http://localhost:3000',
    'http://localhost:3001',
]

CORS_ALLOW_ALL_ORIGINS = True

CORS_ALLOW_HEADERS = list(default_headers) + [
    'X-CSRFToken'
]

CORS_EXPOSE_HEADERS = ["Content-Type", "X-CSRFToken"]
CSRF_COOKIE_HTTPONLY = False
CORS_ALLOW_CREDENTIALS = True

For login I'm using standard rest framework login that works fine with Postman, but I can't find out the reason why it doesn't work with axios

path('auth/', include('rest_framework.urls')),
Back to Top