如何为所有XMLHTTPRequest设置

如何为所有XMLHTTPRequest设置

本文介绍了如何为所有XMLHTTPRequest设置默认标题的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

问题描述

我们正在运行Kibana 4.3服务.我不想修改源代码.

We are running a Kibana 4.3 service. I do not want to modify the source code.

目标是添加一个加密令牌,在浏览器向Kibana发出的每个Ajax请求中将其称为A-Token.

The objective is add an encrypted token, call it A-Token to every Ajax request that the browser makes to Kibana.

背景

Kibana服务由nginx代理.

The Kibana service is proxied by nginx.

当用户向Kibana服务发出Ajax请求时,该请求将被nginx http_auth_request代理拦截,并传递给验证令牌的"auth"服务.如果丢失或无效,则"auth"将201返回到http_auth_request,并执行对Kibana服务的请求,否则返回404,并且由于没有有效令牌而进行了请求被拒绝.

When a user makes an Ajax request to the Kibana service, the request is intercepted by an nginx http_auth_request proxy and passed to an "auth" service that validates the token. If its missing or invalid, then "auth" returns 201 to http_auth_request and the request to the Kibana service is executed, else it returns a 404 and the request is denied since it was made without a valid token.

(此方案基于加密的令牌模式,该模式经常用作在无会话情况(如手头的情况)中进行跨站点脚本编写的对策.

(this scheme is based on the encrypted token pattern often used as a countermeasure for cross-site scripting in session-less situations like the one at hand).

我阅读了W3 XMLHttpRequest文档,似乎setRequestHeader需要在打开后和发送之前运行-这意味着该方案在一般情况下是不可能的,或者与JS平台有关.

I read the W3 XMLHttpRequest documentation and it seems that setRequestHeader needs to run after open and before send - which implies that this scheme is either impossible in a general case or very JS platform dependent.

使用Jquery .ajaxSetup这样的示例进行的测试确认不能单独设置标头:

A test using the Jquery .ajaxSetup like this example, confirms that headers cannot be set independently:

$.ajaxSetup({
    beforeSend: function(xhr) {
                xhr.setRequestHeader(A-Token", 1314159);
                  }
});

寻找不需要分叉Kibana的可能解决方案.

Looking for possible solutions which will not require forking Kibana.

丹尼

推荐答案

我也在寻找该问题的解决方案,但找不到任何东西,然后我想出了下一个解决方案:

I was searching for solution for this problem as well but couldn't find anything and then I came up with next solution:

        XMLHttpRequest.prototype.origOpen = XMLHttpRequest.prototype.open;
        XMLHttpRequest.prototype.open   = function () {
            this.origOpen.apply(this, arguments);
            this.setRequestHeader('X-TOKEN', 'the token');
        };

这篇关于如何为所有XMLHTTPRequest设置默认标题的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-06 16:07