Search code examples
django-rest-frameworkdjango-authenticationdjango-rest-framework-simplejwt

Django csrf_cookie_not_set


I am currently working on a project where the backend is handled by Django and frontend is handled by ReactJS.

The previous developers (they are no longer in the organisation) have developed all the APIs manually. I guess they were not aware of DjangoRestFramework. My job now is to REST-ify 50 odd APIs which are currently working.

I am using DRFs generic views, (List, Create, Retrieve...etc).

I am also assigned with the task of implementing DRFSimpleJWT. The previous developers coded all the functions manually for creating the tokens, what they call it as custom authentication.

I have started creating the APIs, my List and Retrieve APIs work fine but whenever the frontend developer does a POST request on a CreateAPIView, he's got back a 403 error with the description csrf cookie not set.

I also get a 403 error on my runserver log file.

I've tried disabling (commenting) the permission_classes and changing it to AllowAny.

I then proceeded to disable authentication_classes or remove thesession_authentication

In some cases the data doesn't even go through and OPTIONS appears on my server log.

I check the settings.py file and see that csrfmiddleware is disabled. Enabling it gives csrf error on all requests. I googled and played with cors settings and django settings. Nothing worked.

My view is very simple:

MyCreateView(generics.CreateAPIView):
queryset = ModelName.objects.all
serializer_class =MySerializer
permission_classes = [IsAuthenticated,]
authentication_classes = [BasicAuthentication, SessionAuthentication,]

I need help on making the POST request work. Also when I start using SimpleJWT, do I need to specify authentication_classes in my Views? Is this related with cors?

The settings.py REST_FRAMEWORK is same as DRF documentation.

Thanks. Would really appreciate the guidance.


Solution

  • From your frontend while making POST, PATCH, PUT requests modify your request header to include "X-CSRFToken". The value for this header should be read from your cookie called "csrftoken".

    refer these for further information

    https://docs.djangoproject.com/en/2.2/ref/csrf/#ajax https://www.django-rest-framework.org/topics/ajax-csrf-cors/#csrf-protection