将 X-CSRF-Token 标头全局添加到 XMLHttpRequest() 的所有实例;
我正在使用第三方库,它使用 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.
相关文章