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

前端 未结 4 1166
情话喂你
情话喂你 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条回答
  •  渐次进展
    2021-02-04 14:45

    Here's an updated version, based in Django 1.7 (using the jQuery cookie plugin)

    oldSync = Backbone.sync
    Backbone.sync = (method, model, options) ->
    
        csrfSafeMethod = (method) ->
            # these HTTP methods do not require CSRF protection
            /^(GET|HEAD|OPTIONS|TRACE)$/.test method
    
        options.beforeSend = (xhr, settings) ->
            if !csrfSafeMethod(settings.type) and !@crossDomain
                xhr.setRequestHeader 'X-CSRFToken', $.cookie('csrftoken')
            return
        oldSync method, model, options
    

提交回复
热议问题