Django Rest Framework, CSRF and Vue.js

I am trying to use Vue.js to create some POST methods for my REST Api created using the Django Rest Framework. The problem is that I am getting CSRF Failed: CSRF token missing or incorrect. error CSRF Failed: CSRF token missing or incorrect. when sending. But I see a csrf cookie, and it is added to the headers.

Here are my settings:

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

Here is my Vue.js configuration:

 var csrftoken = Cookies.get('csrftoken'); Vue.http.headers.common['HTTP_X_CSRFTOKEN'] = csrftoken; 

And here is the relevant part of the headers that were sent:

 Cookie:djdt=hide; tabstyle=raw-tab; sessionid=1gl533mrneudxw3l9l2vg0ja1yowwmeo; csrftoken=dN85bhztB1oVRov87BsUrWTM29Ff9sjn Host:127.0.0.1:8000 HTTP_X_CSRFTOKEN:dN85bhztB1oVRov87BsUrWTM29Ff9sjn Origin:http://127.0.0.1:8000 Referer:http://127.0.0.1:8000/agencies/6/add-profiles/ 

As you can see, Cookie.csrf and the HTTP_X_CSRFTOKEN header match

I'm really at a standstill. Any suggestions?

+7
django django-rest-framework
source share
1 answer

So, I am posting this as an answer to close the question.

The problem occurred due to an invalid CSRF header name sent on request. According to the documentation:

As in other HTTP headers in request.META, the received header name from the server is normalized by converting all characters to uppercase, replacing any hyphens with underscores and adding the 'HTTP_' Prefix for the name. For example, if your client sends "X-XSRF-TOKEN", the parameter should be "HTTP_X_XSRF_TOKEN".

I also leave a link here to my question , which accumulates several problems that may lead to a CSRF Failed: CSRF token missing or incorrect. error CSRF Failed: CSRF token missing or incorrect. in Django.

+8
source share

All Articles