I\'m using Django 1.7 and django-rest-framework.
I made an API that returns me some JSON data putting this in my settings.py
REST_FRAMEW
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.
I had similar problem, I've wrapped my URLs under csrf_exempt
method as -
from django.views.decorators.csrf import csrf_exempt
url(r'^api/v1/some-resource$', csrf_exempt(SomeApiView.as_view())),
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
django1.8 python2.7
{
"detail": "CSRF Failed: CSRF token missing or incorrect."
}
I fix it by using other httpmethod; oh, I face it again, this time is because I paste it, there are some invisible characters
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
When you host django website on Apache server. Djando rest framework with TokenAuthentication and SessionAuthentication will get
CSRF Failed: CSRF token missing or incorrect
To fix this open Apache configuration file - httpd.conf Add following line:
WSGIPassAuthorization On