0
votes

I've been developing a backbone layer on top of Django and using Django to create the API and having backbone models calling django api to fill in the models. I'm trying to create a login for users using the default django models for users. Since I'm not rendering the pages through django but instead through router in backbone. I can't generate csrf token through django's template language {{ csrf_token }} and thus I can't post any forms.

One way I thought to work around this is to generate the token by having the backbone view fetch from the api endpoint in initialize and have the endpoint generate the token through

token = csrf._get_new_csrf_key()

and then passing it to backbone frontend through json then following the django documentation

var csrftoken = "<%=obj.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);
        }
    }
});

This didn't work since I still get Forbidden (403) CSRF verification failed. Request aborted.

Any help would be appreciated. Thanks

1

1 Answers

0
votes

The simplest workaround is to read the csrftoken cookie and pass it to django via as X-CSRFToken header. This section in the Django docs should give you the correct example: