为什么AJAX不安全?

I'm new to JS and AJAX, and one day, I tried a cross-domain AJAX request. After some researchs, I found out that AJAX could not work over cross domains (natively) because it is unsecure.

From Wikipedia: " This policy prevents a malicious script on one page from obtaining access to sensitive data on another web page through that page's Document Object Model. "

But how could an AJAX request access to "sensitive data", while you can't with default HTTP?

An AJAX request is an HTTP request.

AJAX stands for Asyncronous Javascript And XML. It's kind of named that, after the first browser-based javascript HTTP client API, XMLHttpRequest.

HTTP requests are not inherently insecure, but certain things might make HTTP requests problematic.

A big one related to 'Ajax' requests is that, in the past at least, a HTTP request can carry session/cookie information.

This means that if Ajax requests were not restricted in browser sandboxes (cross-domain), it could mean that the owner of Site A, could make a request to Site B on behalf of a user.

Example: You're logged into a popular social network. Your browser uses a cookie to identify your logged in session. I send you a link to evil.example.org. If cross-site restrictions didn't exist, I could now make a HTTP for you + your session to the social network and act on your behalf.

However, this is not the end of this story. It is possible to do cross-site requests. This is called a CORS requests.

BUT: the way this works is that the owner of the site that you want to make a request to, has to allow in. In our previous example that means that the social network needs to explicitly allow "evil.example.org" to make these kind of requests.

The way this site gives you permission is via CORS headers.

Other ways to work around it is via:

  • Frames that are hosted on the site you're trying to access. (with specific code)
  • A proxy you control.
  • If the server you're trying to access delivers its content in a very specific way. (again, you need control of the target server).

If you control the target server, your best options is to just use CORS though. If you don't your best bet is to setup a proxy you control.