Adding CSRF token to jQuery AJAX requests

When using a jQuery-supported framework such as Backbone, underlying jQuery AJAX requests are typically abstracted at the model layer. To insert Cross-Site Request Forgery (CSRF) tokens or other session data into the request, one method is to proxy a method in the call stack and add the token via an option (example). This does have a disadvantage if you need to call $.ajax directly as you’ll need to again insert the CSRF token as a header option.

The DRY way? Use jQuery’s ajaxPrefilter API:

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

Posted

in

by

Tags:

Comments

Leave a Reply

Your email address will not be published. Required fields are marked *