I Know this is a common problem but after tring every web solution, I still got "CSRF token missing or incorrect." error.
The ajax call use correctly the cookie crsf token DJango has created using on the the common csrf solution:
beforeSend: function (xhr, settings) {
if (!csrfSafeMethod(settings.type) && !this.crossDomain) {
xhr.setRequestHeader("X-CSRFToken", window.csrftoken);
}
}
This is the POST header:
Accept:*/*
Accept-Encoding:gzip, deflate, br
Accept-Language:it-IT,it;q=0.9,en-US;q=0.8,en;q=0.7,es;q=0.6
Connection:keep-alive
Content-Length:31
Content-Type:application/x-www-form-urlencoded; charset=UTF-8
Cookie:csrftoken=PV730Sh7PhMM4WKlnSmzMv726Y5wspf4LKHz8XR9TfHVeY167a8aAzbU8Oci6VMf
Host:127.0.0.1:8000
Origin:http://localhost:3000
Referer:http://localhost:3000/
User-Agent:Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/63.0.3239.132 Safari/537.36
X-CSRFToken:uD3NP6tHllrSSnx4qi23EVgIZy0dkVE5qhZCYN5A9ZETI8SITPb0NGtamIezFTPv
In DJANGO, im using the middleware:
'django.middleware.csrf.CsrfViewMiddleware',
Django View doens't have any @csrf option because is an authenticate POST.
As you see from headers, my Ajax Call start from another "port" (a React Application). For development, i have disabled in Chrome the cross-origin check to ensure my call goes normally.
This is a piece of Django view:
def login(request, *args, **kwargs):
username = request.POST['username']
password = request.POST['password']
c = {}
try:
user = authenticate(request,username=username, password=password)
if user is not None:
return JsonResponse(user.id, safe=False, status=200)
Im worried about the headers. As you can see, the X-CSRFToken
(created by Django after a first GET call with the option @ensure_csrf_cookie
) is different from Cookie:csrftoken=
which value I don't know where it is get.
I've tried to override it by adding a line in before send ajax configuration like this:
xhr.setRequestHeader("Cookie:csrftoken", csrftoken);
but with this (i don't know why) the request does not start.
I have no other idea.
Thanks you for any help!