Reputation: 2835
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.
Upvotes: 0
Views: 1022
Reputation: 2835
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
Upvotes: 1