全球范围内添加的X CSRF令牌头的XMLHtt prequest所有实例(); [英] Adding X-CSRF-Token header globally to all instances of XMLHttpRequest();

查看:737
本文介绍了全球范围内添加的X CSRF令牌头的XMLHtt prequest所有实例();的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我使用它生成一个原始的第三方库 XMLHtt prequest 新XMLHtt prequest

I am using a third party library which spawns a raw XMLHttpRequest with new XMLHttpRequest.

这将绕过我的CSRF保护和被击落我的导轨的服务器。

This bypasses my CSRF protection and gets shot down by my rails server.

有没有办法在全球范围内增加predefined $('元[名称= CSRF令牌])。ATTR(内容) >)的 XMLHtt prequest 在实例化时的所有实例?

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

这不会增加在实例化时的标题,但请求被发送权利之前。您的可以的拦截来电新XMLHtt prequest()为好,但你需要等待与添加,不会有帮助直到头打开被调用。

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令牌头的XMLHtt prequest所有实例();的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆