javascript 使用 Backbone.js 发布数据时如何防范 CSRF?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/18124870/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to protect against CSRF when using Backbone.js to post data?
提问by NeoWang
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 situation?
Backbone.js 在后台处理将数据发布到服务器,因此没有简单的方法在有效负载中插入 CSRF 令牌。在这种情况下,如何保护我的网站免受 CSRF 的影响?
In this SO answer: https://stackoverflow.com/a/10386412/954376, the suggestion is to verify the x-Requested-By header to be XMLHTTPRequest. Is this enough to block all CSRF attempts?
在这个 SO 答案中:https: //stackoverflow.com/a/10386412/954376,建议将 x-Requested-By 标头验证为 XMLHTTPRequest。这足以阻止所有 CSRF 尝试吗?
In Django docs, the suggestion is to add CSRF token in another custom header in every AJAX request: https://docs.djangoproject.com/en/1.5/ref/contrib/csrf/#ajax. Is this necessary?
在 Django 文档中,建议在每个 AJAX 请求的另一个自定义标头中添加 CSRF 令牌:https: //docs.djangoproject.com/en/1.5/ref/contrib/csrf/#ajax。这是必要的吗?
I understand if the attack uses hidden form, I am safe by just assuring the request is from XMLHTTPRequest. But is there any CSRF attack tricks that can forge the header?
我知道如果攻击使用隐藏形式,只要确保请求来自 XMLHTTPRequest,我就安全了。但是有没有可以伪造头部的CSRF攻击技巧?
采纳答案by Esailija
回答by Pasi Jokinen
Setting a global CSRF-token for all jQuery.ajax calls:
为所有 jQuery.ajax 调用设置一个全局 CSRF 令牌:
$(function(){
$.ajaxSetup({
headers: {'X-CSRFToken': CSRF_TOKEN}
});
})
Setting the token just for Backbone by overriding Backbone.sync:
通过覆盖 Backbone.sync 为 Backbone 设置令牌:
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
编辑:修正了 Kadam 在评论中指出的一个错字
回答by Akhorus
Here's an updated version, based in Django 1.7(using the jQuery cookie plugin)
这是基于Django 1.7的更新版本(使用 jQuery cookie 插件)
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
回答by June
I know it's a bit old question, but I'll leave a link to the github repo of AMD module just for this:
我知道这是一个有点老的问题,但我会为此留下一个指向 AMD 模块的 github 存储库的链接:
https://github.com/kuc2477/backbone.csrf.git(disclaimer: I'm the author of the module)
https://github.com/kuc2477/backbone.csrf.git(免责声明:我是模块的作者)