0

Right now I have it set up so that when a successful login occurs the login div fades and a logout button appears. I want to be able to hit the logout and go to my logout function that just redirects to the original login page, but for some reason after the (only successful) ajax form submission suddenly I am getting 403 errors : Reason given for failure: CSRF token missing or incorrect.

Wondering if the problem is that I'm not passing the CSRF token correctly. I've tried everything on the page https://docs.djangoproject.com/en/1.6/ref/contrib/csrf/#ajax

Here is my code:

urls.py

from django.conf.urls import patterns, include, url

from django.contrib import admin
admin.autodiscover()

urlpatterns = patterns('',
    # Examples:
    # url(r'^$', 'reportgenerator.views.home', name='home'),
    # url(r'^blog/', include('blog.urls')),

    url(r'^admin/', include(admin.site.urls)),
    url(r'^login/', 'reportgenerator.views.login'),
    url(r'^logout/', 'reportgenerator.views.logout'),
)

views.py

class LoginForm(forms.Form):
username = forms.CharField(max_length=200)
password = forms.CharField(max_length=200)

def login(request):
    c = {}
    c.update(csrf(request))

    if request.POST:
        form = LoginForm(request.POST)
        if form.is_valid():
            user = auth.authenticate(username = form.cleaned_data['username'],
                password = form.cleaned_data['password'])
            is_success = False
            if user is not None:
                auth.login(request, user)
                is_success = True

            if request.is_ajax():
                if (is_success):
                    return render_to_response('login.html', c, context_instance = RequestContext(request))

            return render('was_failure')
    else:
        form = LoginForm()

    c['form'] = form
        return render(request, 'login.html', c)

def logout(request):
        auth.logout(request)
        return HttpResponseRedirect('/login/')

and my javascript:

function getCookie(name) {
    var cookieValue = null;
    if (document.cookie && document.cookie != '') {
        var cookies = document.cookie.split(';');
        for (var i = 0; i < cookies.length; i++) {
            var cookie = jQuery.trim(cookies[i]);
            // Does this cookie string begin with the name we want?
            if (cookie.substring(0, name.length + 1) == (name + '=')) {
                cookieValue = decodeURIComponent(cookie.substring(name.length + 1));
                break;
            }
        }
    }
    return cookieValue;
}

var csrftoken = getCookie('csrftoken');

function csrfSafeMethod(method) {
    // these HTTP methods do not require CSRF protection
    return (/^(GET|HEAD|OPTIONS|TRACE)$/.test(method));
}

function sameOrigin(url) {
    // test that a given url is a same-origin URL
    // url could be relative or scheme relative or absolute
    var host = document.location.host; // host + port
    var protocol = document.location.protocol;
    var sr_origin = '//' + host;
    var origin = protocol + sr_origin;
    // Allow absolute or scheme relative URLs to same origin
    return (url == origin || url.slice(0, origin.length + 1) == origin + '/') ||
        (url == sr_origin || url.slice(0, sr_origin.length + 1) == sr_origin + '/') ||
        // or any other URL that isn't scheme relative or absolute i.e relative.
        !(/^(\/\/|http:|https:).*/.test(url));
}

$.ajaxSetup({
    beforeSend: function(xhr, settings) {
        if (!csrfSafeMethod(settings.type) && sameOrigin(settings.url)) {
            // Send the token to same-origin, relative URLs only.
            // Send the token only if the method warrants CSRF protection
            // Using the CSRFToken value acquired earlier
            xhr.setRequestHeader("X-CSRFToken", csrftoken);
        }
    }
});

jQuery(function() {
  var form1 = jQuery("#contactform");

  form1.submit(function(e) {
    $.ajax({
        type: "POST",
        url: form1.attr('action'),
        data: form1.serializeArray(),
        success: function() {
            popup.setAttribute("style","display: none;");
            blurback.setAttribute("style", "-webkit-filter: blur(0px)");
            $("#welcome").fadeIn("slow");
            $("#logoutfade").fadeIn("slow");
        },
        error: function() {
            document.getElementById("password").value = "";
        }
    });
      e.preventDefault(); 
  });
});
Tyler McAtee
  • 300
  • 2
  • 12

2 Answers2

1

Django provides pretty detailed information on how you can perform ajax requests requiring CSRF: https://docs.djangoproject.com/en/1.6/ref/contrib/csrf/

Using jQuery without jquery cookie addon:

// using jQuery
function getCookie(name) {
    var cookieValue = null;
    if (document.cookie && document.cookie != '') {
        var cookies = document.cookie.split(';');
        for (var i = 0; i < cookies.length; i++) {
            var cookie = jQuery.trim(cookies[i]);
            // Does this cookie string begin with the name we want?
            if (cookie.substring(0, name.length + 1) == (name + '=')) {
                cookieValue = decodeURIComponent(cookie.substring(name.length + 1));
                break;
            }
        }
    }
    return cookieValue;
}
var csrftoken = getCookie('csrftoken');

Using Jquery with jquery cookie plugin:

    var csrftoken = $.cookie('csrftoken');

And then:

function csrfSafeMethod(method) {
    // these HTTP methods do not require CSRF protection
    return (/^(GET|HEAD|OPTIONS|TRACE)$/.test(method));
}
function sameOrigin(url) {
    // test that a given url is a same-origin URL
    // url could be relative or scheme relative or absolute
    var host = document.location.host; // host + port
    var protocol = document.location.protocol;
    var sr_origin = '//' + host;
    var origin = protocol + sr_origin;
    // Allow absolute or scheme relative URLs to same origin
    return (url == origin || url.slice(0, origin.length + 1) == origin + '/') ||
        (url == sr_origin || url.slice(0, sr_origin.length + 1) == sr_origin + '/') ||
        // or any other URL that isn't scheme relative or absolute i.e relative.
        !(/^(\/\/|http:|https:).*/.test(url));
}
$.ajaxSetup({
    beforeSend: function(xhr, settings) {
        if (!csrfSafeMethod(settings.type) && sameOrigin(settings.url)) {
            // Send the token to same-origin, relative URLs only.
            // Send the token only if the method warrants CSRF protection
            // Using the CSRFToken value acquired earlier
            xhr.setRequestHeader("X-CSRFToken", csrftoken);
        }
    }
});

EDIT (to your answer) A more general approach: First make sure you have the middleware enabled:

    'django.middleware.csrf.CsrfViewMiddleware',

Then in your JS file:

$(document).on('click', '.some-class', function(){
    var $csrftoken = $.cookie('csrftoken');
    $.ajax({
        type: 'POST',
        url: /your/url/,
        crossDomain: false,
        beforeSend: function(xhr) {
            xhr.setRequestHeader("X-CSRFToken", $csrftoken);
        },
        success: function(ctx) {
            console.log(Success!)
        }
    });
});
petkostas
  • 7,250
  • 3
  • 26
  • 29
  • Hey yeah I've been staring at this documentation all day and trying to implement it but it's not really helping. How do I pass this in exactly in my code? – Tyler McAtee Jan 16 '14 at 21:59
  • nah I can't get it to work at all. I'm not having any issues submitting my first ajax form, that goes fine and then my success function runs properly. Then when I click the logout button and try to redirect to /logout/ that's when I get the problems. In fact everything works unless I get a successful return and then I'm having csrf problems. – Tyler McAtee Jan 16 '14 at 22:24
0

To follow up on this -- I figured out a couple days later. The reason I was having this problem was because the logout button was present before the ajax login. When the user was authenticated the crsf token was re-generated and the logout button the page had the old token attached to it because it was generated previously. I switched it to generating the login button after the ajax call and everything worked great.

Tyler McAtee
  • 300
  • 2
  • 12