Search code examples
ajaxpostdjango-viewscsrfdjango-csrf

Django csrf_token is null in chrome


I'm having a bit of a strange problem. I am writing a simple little app and need to post some stuff back to a django view. I'm following the guide here: https://docs.djangoproject.com/en/1.7/ref/contrib/csrf/ to set the ajax headers and have the following code in my js:

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');
console.log(csrftoken)

function csrfSafeMethod(method) {
    // these HTTP methods do not require CSRF protection
    return (/^(GET|HEAD|OPTIONS|TRACE)$/.test(method));
}
$.ajaxSetup({
    beforeSend: function(xhr, settings) {
        if (!csrfSafeMethod(settings.type) && !this.crossDomain) {
            xhr.setRequestHeader("X-CSRFToken", csrftoken);
        }
    }
});

I have a form in my html with the code:

<form onsubmit="return false;">
                {% csrf_token %}
                <input type="text" id="map-id-input"/>
                <button id="map-id-btn" class='btn btn-default custom-btn'>
                    Go 
                </button>
            </form>

I also have a snippet of js code that runs when the button above is clicked:

$(function() {
$("#map-id-btn").click(function() {
    checkMapID();
})
})

function checkMapID() {
    var mapId = $("#map-id-input").val();
    $.ajax({
        url: "check_map_id/", 
        type: "POST",
        dataType: "json", 
        data: {
            csrfmiddlewaretoken: csrftoken,
            map_id: mapId,
        },
        success: function(status_dict) {
            if (status_dict.status === 1) {
                $("#status").html("Valid map ID <br> Loading Data...")
                window.location = status_dict.url;
            }
            else {
                $("#status").html("Invalid map ID. Please try again, or contact ...")
            }
        },
        error: function(result) {
            console.log(result)
        }
    });
}

All of my Javacript is in one file, placed at the top of my template.

The view that catches the url 'check_map_id/' is:

@ensure_csrf_cookie
def check_map_id(request):
map_id = request.POST['map_id']

if map_id not in GEOJSON_LOOKUP.keys():
    status = json.dumps({
        'status': 0,
        'url': '',
    })  
    return HttpResponse(status, content_type="application/json")
else:
    status = json.dumps({
        'status': 1,
        'url': reverse('map', args=(map_id,)),
    })
    return HttpResponse(status, content_type="application/json")

Now, when I run the app in my local machine using firefox, I get a valid csrf token being printed to the console. If I fire up the app on my local machine in chrome or IE I get a null being printed. The same behaviour is echoed on the live site. I'm using linux (mint) and strangely, if I fire up the app in firefox on a windows machine, it returns null in firefox too. Something strange is going on here! Any ideas? I seem to be doing exactly what the django documentation suggests.

UPDATE: I added @ensure_csrf_cookie to my index view and now I am getting a token printed out on both broswers on my local machine. The code is not working on my live server however. If I chuck some random console.logs in my js it displays on the live server so the code is being run. I'm really at a loss.

UPDATE2: So I have established that the problem is that on my live site, the document.cookie property is not being set. I guess the csrftoken="..." cookie is set by django. It seems to be setting it on my local machine but not on my live site. The code is identical :/. What on earth is going on here?!


Solution

  • Ok. I have found the problem! It was a simple case of not actually sending the csrf token to the html page in the first place. I was focussing on the ajax call, which was actually correct.

    I changed the view that actually rendered the page the offending form was on to be:

    @ensure_csrf_cookie
    def index(request):
        context = RequestContext(request)
        return render_to_response('vis_it_app/index.html', context)
    

    The key here is 'RequestContext' which by default, send the csfr token as well. That was a mission...

    So to summarise. To make this work.

    1. Ensure the csrf token is actually sent to the page you intend to use it on by using RequestContext and @ensure_csrf_cookie

    2. Ensure {% csrf_token %} is somewhere in your form

    3. Add the AJAX specific code found here: https://docs.djangoproject.com/en/dev/ref/contrib/csrf/#ajax to your pages JavaScript

    4. Make sure you send the middleware token back with the ajax data via:

      $.ajax({ url: "...", type: "POST", dataType: "...", data: { csrfmiddlewaretoken: csrftoken, ... },

    And that should do it.