I'm wondering if there is a JavaScript library, which overrides XMLHttpRequest
and allows to transparently handle all cross-domain requests and seamlessly forward them over my same-origin server-side proxy.
What I want is to have a common solution, which could be used together with any JavaScript library to make cross-domain requests (e.g. with cross-domain jQuery.ajax()
).
Are there any drawbacks to use such library (security problems, HTTPS access, etc.)?
Update:
If such library is already created by someone, than I just do not want to reinvent the wheel and handle all corner cases again.
If you just need to redirect every request to a specific proxy you could simply write it yourself, something in the lines of
XMLHttpRequest.prototype.oldOpen = XMLHttpRequest.prototype.open;
var newOpen = function(args) {
//overwrite arguments changing the original url to the proxy one,
//and add a parameter/header to send the original url to the proxy
this.oldOpen(args);
}
XMLHttpRequest.prototype.open = newOpen;
Since the proxy is in the same domain (if you want to allow x-domain proxy requests, just add the Access-Control-Allow-Origin header), it will not be sent any cookie of the remote domain (you won't have them anyway, since x-domains cookies are blocked - as long as you don't enter the field with the header Access-Control-Allow-Credentials).
Some security implications are rather obvious:
- you are proxying the request, and as such the proxy itself will have access to everything, regardless of the encryption
- HTTPS handling will be demanded to the proxy (if the remote url is secure) and the client will not be able to (or, on the other hand, will not need to, if demanded to the proxy) directly verify the server certificates
A more complex (same domain, to fully support cookies) proxy implementation could even provide basic session handling for cross domain requests rewriting the headers:
- Client requests www.remotedomain.com/querystring from www.mydomain.com without cookies
- Request is rewritten as proxy.mydomain.com/www.remotedomain.com/querystring
The proxy makes a request to www.remotedomain.com/querystring which responds with the header
Set-Cookie: name=value; path=/; expires Mon, 31-Dec-2012 23:59:59 GMT
The client receive the response back with the header
Set-Cookie: name=value; path=/www.remotedomain.com; expires Mon, 31-Dec-2012 23:59:59 GMT
On the next request the client will send the cookie, and the proxy will just forward them to the remote service
But I'm probably digressing too much. :)
I will not use JS for this kind of needs... Just make all your AJAX calls to a PHP file (or whatever) on your server that acts as a proxy.
It only needs to receive the url you want to call, POST or GET parameters and then make a cURL to the external server.
In return it will print the output of the cURL request.