0

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!

RetroMime
  • 387
  • 1
  • 8
  • 23

2 Answers2

0

Don't send this from Cookie send this with params data. For i.e. I usually sent through JQuery AJAX. Don't send through headers.

       var formdata = {
"csrfmiddlewaretoken":$("input[name='csrfmiddlewaretoken']").val()
}

Also many answers you can try. "CSRF token missing or incorrect" while post parameter via AJAX in Django

Anup Yadav
  • 2,825
  • 3
  • 21
  • 30
0

There is an easy working solution:

With a JavaScriptCookie you can get it like that:

var csrftoken = Cookies.get('csrftoken');
var data = new FormData();

data.append('someOtherData', someOtherData);
data.append('csrftoken', csrftoken);
$.ajax({
         type: "POST",
         url: "someUrl",
         data: data,
      });

You should use FormData because it makes it simple for you.

If you do not want to use a third-party just have a look at this documentation. Here is also the third-party mentioned but also the way without it.

Coder949
  • 987
  • 1
  • 8
  • 29
  • I've tried to add token to Ajax Call Data as your code but it still not working. The documentation you linked is the first things I've tried as you can see in the code above. – RetroMime Feb 01 '18 at 09:39
  • did you include the JavaScriptCookie library ? – Coder949 Feb 01 '18 at 10:19