Adding X-CSRF-Token header globally to all instances of XMLHttpRequest();

匿名 (未验证) 提交于 2019-12-03 01:57:01

问题:

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

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

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?

回答1:

I'd recommend to intercept calls to the send method:

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

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.

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.



回答2:

you can wrap the ajax open() method to open and then set the header right away:

(function() {     var op = XMLHttpRequest.prototype.open;     XMLHttpRequest.prototype.open = function() {         var resp = op.apply(this, arguments);         this.setRequestHeader('X-CSRF-Token', $('meta[name=csrf-token]').attr('content'));         return resp;     }; }()); 


回答3:

If you need a Jquery independent solution you could use:

  (function() {       var send = XMLHttpRequest.prototype.send,           token = document.getElementsByTagName('meta')['csrf-token'].content;       XMLHttpRequest.prototype.send = function(data) {           this.setRequestHeader('X-CSRF-Token', token);           return send.apply(this, arguments);       };   }()); 


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