CSRF Failed: CSRF token missing or incorrect
When you are using SessionAuthentication, you are using Django's authentication which usually requires CSRF to be checked. Django REST Framework enforces this, only for SessionAuthentication
, so you must pass the CSRF token in the X-CSRFToken
header.
The Django documentation provides more information on retrieving the CSRF token using jQuery and sending it in requests. The CSRF token is saved as a cookie called csrftoken
that you can retrieve from a HTTP response, which varies depending on the language that is being used.
If you cannot retrieve the CSRF cookie, this is usually a sign that you should not be using SessionAuthentication
. I recommend looking into TokenAuthentication or OAuth 2.0 depending on your needs.
This is what i did to solve it, i included csrf token to the form and using jquery/ javascrip got the csrf token like this when document loaded
var $crf_token = $('[name="csrfmiddlewaretoken"]').attr('value');
the included it on jquery headers as follow
$.ajax({
type: "POST",
url: "/api/endpoint/",
data: newEndpoint,
headers:{"X-CSRFToken": $crf_token},
success: function (newEnd) {
console.log(newEnd);
add_end(newEnd);
},
error: function () {
alert("There was an error")
}
});
I think it is a cookie issue.
Permanent Solution: If you are using Postman, First, clear the existing cookies by clicking 'X' s. Then add correct cookie.
Temporary Solution (for debugging): Try this in your settings.py
:
'DEFAULT_AUTHENTICATION_CLASSES': [
# 'rest_framework.authentication.SessionAuthentication',
'rest_framework.authentication.BasicAuthentication',
]
1- Search for the Cookie header
2- Separate the csrftoken from the sessionid
3- Add the X-CSRFToken={..the csrftoken that you extracted in step 2..} see below
4- Post again
We had this problem and it turned out to be Postman's fault. They were automatically sending csrftoken
and sessionid
default values which we weren't passing in the header. Following this tutorial helped fix the issue: https://avilpage.com/2019/02/django-tips-csrf-token-postman-curl.html