How do I set a default Header for all XMLHTTPRequests

不羁岁月 提交于 2020-06-27 18:35:33

问题


Problem description

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

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

Background

The Kibana service is proxied by nginx.

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).

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.

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

Looking for possible solutions which will not require forking Kibana.

Danny


回答1:


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


来源:https://stackoverflow.com/questions/37963758/how-do-i-set-a-default-header-for-all-xmlhttprequests

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!