Django Rest Framework Csrf Failed: Csrf Cookie Not Set

python Django REST Framework CSRF Failed: CSRF cookie not set?

You need to include a CSRF token in the request (coming from django), however it looks like you're trying to include one.

I've had issues where Django doesn't accept the token if something is not configured correctly. There are a number of things that can cause this, such as setting the wrong SESSION_COOKIE_DOMAIN, CSRF_COOKIE_NAME or CSRF_COOKIE_DOMAIN (if you're changing any of these)

It could also be one of the CSRF_COOKIE_SECURE or SESSION_COOKIE_SECURE settings. Both of your examples indicate you're using HTTPS, so these should both be set to True. I remember when debugging on localhost, I needed to set them to False in order for things to work over HTTP

Check out the Django configuration documentation for helpful info here: https://docs.djangoproject.com/en/3.1/ref/settings/#session-cookie-secure

You might also look at your CORS settings too, if you have that enabled. Make sure CORS_ALLOW_CREDENTIALS is True. Here's a link describing CORS settings if you're using them: https://pypi.org/project/django-cors-headers/

It's also possible there is a much simpler solution. The curl request is a GET, but it looks like your Python code is doing a PUT, which is quite different when it comes to CSRF (GET doesn't really care about it, but PUT does very much). So one question might be - are you trying to perform a GET or a PUT to the endpoint?

Django REST Framework Forbidden CSRF cookie not set

You need to use ObtainAuthToken.as_view(). Any APIView automatically uses csrf_exempt() (and explicitly checks the CSRF token if you're using SessionAuthentication), but that won't work if you're not using .as_view(). You don't have to explicitly use csrf_exempt on top of what APIView does.

I'm not sure why you're not using the first url, /login/, but if you're having issues with that url, you're going the wrong way fixing them.

On a side note: csrf_exempt sets an attribute on the function. As such, using it on post() has absolutely no effect, since the middleware won't check the attributes on the post() method. You need to use it on the dispatch() method or as csrf_exempt(ObtainAuthToken.as_view()).



Related Topics



Leave a reply



Submit