Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

JQuery + AJAX + Django = CSRF ? [duplicate]

Possible Duplicate:
"CSRF token missing or incorrect" while post parameter via AJAX in Django

I wanted to send login data by AJAX to authenticate user, but it wasn't possible because of CSRF. Could You tell me what to add to my code to make it woking?

my JavaScript file:

$("#login").live("click", function() {
    var username = $(".login_username").val();
    var password = $(".login_password").val();

    $.ajax({
        url: "/login",
        type: "POST",
        data: {
            username: username,
            password: password
        },
        cache: false,
        success: function(tekst) {
            alert(tekst);
        }
    });
});
like image 228
Jazi Avatar asked Aug 27 '11 13:08

Jazi


2 Answers

There is a method explained here.

It consists of adding a X-CSRFToken header on each ajax request.

This is done by hooking in the jQuery.ajaxSend event, so everything is done automatically (you just have to copy and past their code, and run it once before the first ajax request you make).

like image 90
Arnaud Le Blanc Avatar answered Oct 08 '22 19:10

Arnaud Le Blanc


I've been trying to solve the same problem, And as arnaud576875 says you have to Add the csrf token header on each ajax request just like the Django docs says https://docs.djangoproject.com/en/dev/ref/contrib/csrf/#ajax And execute that code before any Ajax request you make.

But there is something additional, you have to find a way to load the csrf token to the cookies of your app before trying to do any AJAX request, after a lot of painful hours researching I couldn't find an specific answer of how to do this, what I did found is that to ensure that your view sends the csrf token within a cookie you can use the ensure_csrf_token() to each view you want to receive the token https://docs.djangoproject.com/en/dev/ref/contrib/csrf/#django.views.decorators.csrf.ensure_csrf_cookie this seems to work for a lot of people, but did not worked for me.

Another way is using the Legacy Method, adding the 'django.middleware.csrf.CsrfResponseMiddleware' to your MIDDLEWARE_CLASSES but I don't recommend this method because leaves several security risks. https://docs.djangoproject.com/en/1.2/ref/contrib/csrf/#legacy-method

All this methods that I said before did not worked for me. The way that I'm allowing Ajax to do some requests is as the following, and if someone finds this a dangerous method please let me know:

  1. Go to the first view that your user will hit, like the /home/ page.
  2. Insert this before redirecting or parsing anything request.META["CSRF_COOKIE_USED"] = True

And that's it, That is the way that works for me, but as I said before I'm not sure if this is the right method or the most secure one to accomplish the csrf protection.

like image 26
ElHacker Avatar answered Oct 08 '22 19:10

ElHacker