How to protect against CSRF when using Backbone.js to post data?

前端 未结 4 1115
情话喂你
情话喂你 2021-02-04 14:43

Backbone.js handles posting data to server under the hood, so there is no easy way to insert a CSRF token in the payload. How can I protect my site against CSRF in this situatio

4条回答
  •  闹比i
    闹比i (楼主)
    2021-02-04 14:57

    Setting a global CSRF-token for all jQuery.ajax calls:

    $(function(){ 
      $.ajaxSetup({
        headers: {'X-CSRFToken': CSRF_TOKEN}
      });
    })
    

    Setting the token just for Backbone by overriding Backbone.sync:

    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);
    };
    

    EDIT: Fixed a typo Kadam points at in comments

提交回复
热议问题