問題描述
我正在使用第三方庫,它使用 new XMLHttpRequest
生成原始 XMLHttpRequest
.
I am using a third party library which spawns a raw XMLHttpRequest
with new XMLHttpRequest
.
這繞過了我的 CSRF 保護并被我的 Rails 服務器擊落.
This bypasses my CSRF protection and gets shot down by my rails server.
有沒有辦法將預定義的 CSRF 令牌 ($('meta[name=csrf-token]').attr('content')
) 全局添加到 的所有實例XMLHttpRequest
在實例化時?
Is there a way to globally add a predefined CSRF token ($('meta[name=csrf-token]').attr('content')
) to ALL instances of XMLHttpRequest
at instantiation time?
推薦答案
我建議攔截調用發送
方法:
(function() {
var send = XMLHttpRequest.prototype.send,
token = $('meta[name=csrf-token]').attr('content');
XMLHttpRequest.prototype.send = function(data) {
this.setRequestHeader('X-CSRF-Token', token);
return send.apply(this, arguments);
};
}());
這不會在實例化時添加標頭,而是在發送請求之前添加.您可以攔截對 new XMLHttpRequest()
的調用,但這無濟于事,因為您需要等待添加標頭直到 open
被調用.
This won't add the header at instantiation time, but right before the request is sent. You can intercept calls to new XMLHttpRequest()
as well, but that won't be helpful as you need to wait with adding the header until open
was called.
您可能還希望對請求的目標 URL 進行測試,以便僅在調用自己的 api 時添加標頭.不這樣做可能會在其他地方泄漏令牌,甚至可能會破壞不允許此標頭的跨域 CORS 調用.
You might also want to include a test for the target URL of the request, so that you only add the header when your own api is called. Not doing so might leak the token elsewhere, or might even break cross-domain CORS calls that don't allow this header.
這篇關于將 X-CSRF-Token 標頭全局添加到 XMLHttpRequest() 的所有實例;的文章就介紹到這了,希望我們推薦的答案對大家有所幫助,也希望大家多多支持html5模板網!