0

I'm trying to access an API endpoint protected with DRF's session authentication. This requires passing the CSRF cookie in the request headers, which I have done following the Django docs, like this:

import * as Cookies from "js-cookie";
var csrftoken = Cookies.get('csrftoken');

fetch('/api/myendpoint', { headers: { 'X-CSRFToken': csrftoken }})
  .then(response => ...)

I have turned on session authentication in my settings.py like this:

REST_FRAMEWORK = {
    'DEFAULT_AUTHENTICATION_CLASSES': (
        'rest_framework.authentication.SessionAuthentication',
    ),
    'DEFAULT_PERMISSION_CLASSES': (
        'rest_framework.permissions.IsAuthenticated',
    )
}

Django login and authentication is working correctly for normal pages, but not for my API calls. I always get a 403 error with the response

Authentication credentials were not provided.

I have checked that the X-CSRFToken header value is correctly set to the current csrftoken cookie value by looking at the request in Chrome's network panel.

1 Answer 1

1

Found the answer here. The csrftoken is not supposed to be in the request headers for GET. Instead,

fetch('/api/workflows', { credentials: 'include' })...

which includes cookies, as described in the Fetch docs.

X-CSRFToken must still be set for PUT, PATCH and DELETE requests

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.