Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Django CSRF Cookie Not Set

Tags:

python

django

People also ask

How does CSRF work in Django?

Django has a {% csrf_token %} tag that is implemented to avoid malicious attacks. It generates a token on the server-side when rendering the page and makes sure to cross-check this token for any requests coming back in. If the incoming requests do not contain the token, they are not executed.

Where is CSRF token stored in Django?

The CSRF token is like an alphanumeric code or random secret value that's peculiar to that particular site. Hence, no other site has the same code. In Django, the token is set by CsrfViewMiddleware in the settings.py file. A hidden form field with a csrfmiddlewaretoken field is present in all outgoing requests.

What is Csrf_exempt?

csrf_exempt (view) This decorator marks a view as being exempt from the protection ensured by the middleware. Example: from django.http import HttpResponse from django.views.decorators.csrf import csrf_exempt @csrf_exempt def my_view(request): return HttpResponse('Hello world')


This can also occur if CSRF_COOKIE_SECURE = True is set and you are accessing the site non-securely or if CSRF_COOKIE_HTTPONLY = True is set as stated here and here


from django.http import HttpResponse
from django.views.decorators.csrf import csrf_exempt

@csrf_exempt 
def your_view(request):
    if request.method == "POST":
        # do something
    return HttpResponse("Your response")

If you're using the HTML5 Fetch API to make POST requests as a logged in user and getting Forbidden (CSRF cookie not set.), it could be because by default fetch does not include session cookies, resulting in Django thinking you're a different user than the one who loaded the page.

You can include the session token by passing the option credentials: 'include' to fetch:

var csrftoken = getCookie('csrftoken');
var headers = new Headers();
headers.append('X-CSRFToken', csrftoken);
fetch('/api/upload', {
    method: 'POST',
    body: payload,
    headers: headers,
    credentials: 'include'
})

From This You can solve it by adding the ensure_csrf_cookie decorator to your view

from django.views.decorators.csrf import ensure_csrf_cookie
@ensure_csrf_cookie
def yourView(request):
 #...

if this method doesn't work. you will try to comment csrf in middleware. and test again.


If you're using DRF, check if your urlpatterns are correct, maybe you forgot .as_view():

So that how mine code looked like:

urlpatterns += path('resource', ResourceView) 

And that's how it should like:

urlpatterns += path('resource', ResourceView.as_view())