Cross-domain XHR/AJAX : a possible workaround?

2019-02-24 22:59发布

问题:

I just had an idea to make cross-domain AJAX calls, because so far they really are a PITA to deal with. This is a solution I haven't seen exposed anywhere on the web, so it might be (probably is) flawed/dangerous for some reason, which I can't seem to see now, so I'm turning to you to tell me if this is legit or not :

Today if you own a domain, www.foo.com, you cannont make XML Http Requests to say www.bar.com. But what if you made an XHR to foo.com, that would then ask bar.com for the page, through a cURL request (or a socket or anything ?).

You normally set up your xhr, be it a GET or a POST, but you send it to foo.com/remote-xhr.php instead and add a "url" parameter containing the originally intended URL, and "params" parameter containing, well, the parameters.

remote-xhr.php parses "params", and calls "url", and "echo" the response.

It's definitely a tradeoff, because : 1. you make 2 calls instead of one with other solutions (script tag hack/JSONP) and 2. you lose any authentication you might have had because the client isn't requesting the page but the server is (you can workaround it with unique IDs, salt, anything though) ; but you then have a perfectly normal XHR call that could work with any distand domain !

What am I missing ?

回答1:

I imagine you've already thought of some of these, but just in case not

  1. If you aren't doing any kind of authentication with your server-side XHR pass-through, you might want to limit what URLs can be called and parse the params for any extra-weird XSS opportunities this presents.

  2. The latency increase might put a strain on your webserver since it could be holding the request/response threads longer waiting for a cURL response to comeback (unless you're doing somekind of extra async architecture). Caching the cURL response might be preferrable, but depending on how many variations of your POST'ed parameters you might encounter, that might not be an option.

I'm sure there are others depending on your application, but I will go ahead and say that I'm doing something like this but only because I pay for an external API that I don't want to expose directly to my AJAX application... so I've pretty heavily abstracted the calls, and limit them to pretty much a single external URL.



回答2:

Nothing wrong with that. I use that trick in my AJAX requests.



回答3:

This is workable but keep in mind that you're allowing your server to be told, by a client, what data to download. Depending on your implementation, it could be fairly harmless but it could easily bite you in the ass if it's not secured (perhaps limit it to very specific domains?).

For instance, someone could send multiple requests to your handler that returns, say, a Linux ISO or something illegal.