Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
613 views
in Technique[技术] by (71.8m points)

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

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?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...