dnmh
dnmh

Reputation: 2135

Django CSRF cross site AJAX issue

I have a backend server at localhost:8000 and a frontend server at localhost:3000. Backend is Django and I have the corsheaders package installed and I make GET requests without issues. When I open my site, the first GET request successfully sets a CSRF token (I can see the cookie in dev tools).

I have this in settings.py:

CORS_ORIGIN_WHITELIST = (
    'localhost:3000'
)

CORS_ALLOW_METHODS = (
    'DELETE',
    'GET',
    'OPTIONS',
    'PATCH',
    'POST',
    'PUT'
)

CORS_ALLOW_HEADERS = (
    'accept',
    'accept-encoding',
    'authorization',
    'content-type',
    'dnt',
    'origin',
    'user-agent',
    'x-csrftoken',
    'x-requested-with',
)

CSRF_TRUSTED_ORIGINS = (
    'localhost:3000',
)

CORS_ALLOW_CREDENTIALS = True

Now I'm trying to make a POST request and I'm constantly turned down by the server:

403 - Forbidden (CSRF cookie not set.): /myapp/myview/

and this is what my JS looks like:

let csrftoken = utils.getCookie('csrftoken'); // logged this on the console, the token is really here

jQuery.ajaxSetup({
  beforeSend: function(xhr, settings) {
    xhr.setRequestHeader("X-CSRFToken", csrftoken);
  }
}); // this might be wrong - I did read it is used only if it's not cross site, but I still gave it a try

jQuery.ajax({
  url: url,
  type: 'POST',
  data: {attr: value, csrfmiddlewaretoken: csrftoken}
})...

I've tried only with csrfmiddlewaretoken in the AJAX data. I've tried only with settting the request header. I've tried both. Still no luck. I'm obviously missing something; I've never before tried doing a POST in Django across sites.

Any suggestions?

EDIT: I found out the issue is elsewhere.

Upvotes: 0

Views: 1759

Answers (2)

milorad.kukic
milorad.kukic

Reputation: 506

I was able to do it with:

$.ajax({
     url : urlToCall, // the endpoint
     type : "POST", // http method
     data : {
         csrfmiddlewaretoken: "Your token",
         data...
     },

     success : function(response) {
        console.log('success', response); 
            },
        error : function(xhr,errmsg,err) {
            console.log(xhr.status + ": " +  xhr.responseText); //  provide a bit more info about the error to the console
        }
});

Hope it helps!

Upvotes: 0

matyas
matyas

Reputation: 2796

Try to put the XSRF-Token in the Header of your Ajax request.

 $.ajax({
         url : urlToCall, // the endpoint
         type : "POST", // http method
         headers: { "X-CSRFToken": "your token here" },
         success : function(response) {
            console.log('success', response); 
                },
            error : function(xhr,errmsg,err) {
                console.log(xhr.status + ": " +  xhr.responseText); //  provide a bit more info about the error to the console
            }
    });

Upvotes: 0

Related Questions