public
Last active

This is what I did to insert the CSRF token in backbone requests. This works with django.

  • Download Gist
Backbone.sync_csrftoken.js
JavaScript
1 2 3 4 5 6 7
var oldSync = Backbone.sync;
Backbone.sync = function(method, model, options){
options.beforeSend = function(xhr){
xhr.setRequestHeader('X-CSRFToken', CSRF_TOKEN);
};
return oldSync(method, model, options);
};

Awesome, thank you.

More of a fan of a global, non-backbone specific approach: https://gist.github.com/3960219

Here is the sollution I used with suggestions from here: http://backbonetutorials.com/cross-domain-sessions/

$.ajaxPrefilter(function(options, originalOptions, jqXHR) {
  var token;
  options.xhrFields = {
    withCredentials: true
  };
  token = $('meta[name="csrf-token"]').attr('content');
  if (token) {
    return jqXHR.setRequestHeader('X-CSRF-Token', token);
  }
});

Please sign in to comment on this gist.

Something went wrong with that request. Please try again.