AJAX - The Complete Reference

(avery) #1

PART II


Chapter 7: Security Concerns 299


using HTTP either loaded in another window or requested via an XHR. Different directories
don’t matter, so it would be perfectly fine to look at http://www.example.com/dir2/page2
.html, but access to other servers like http://www.othersite.com is certainly disallowed.
Even within the same domain, same-origin checks will fail by default; for example,
http://www2.example.com/page.html would be rejected. In JavaScript, it is possible to
loosen this restriction by setting the document.domain to a value of example.com. However,
it should be noted that this is not supported consistently in XHR-based communication in
browsers. Also, you can only change the domain to subdomains of the current domain,
so it would be possible to go from http://www.example.com to example.com, but not back to
http://www.example.com and certainly not to www2.example.com. However, later you will see
the use of document.domain in regard to some remote script access ideas.
Table 7-4 shows the result of attempting to access particular target URLs either via
an open window or an XHR call, assuming that the accessing script was loaded from
http://www.example.com/dir/page.html.
To further explain the same-origin policy, we present an example at http://ajaxref.com/
ch7/sameorigin.html, which is shown in Figure 7-3.

NNOT EOTE We use a try/catch block to catch the same-origin policy errors; however, without this you
may note that some browsers will be a bit quiet about the security violation.

While the same-origin policy is clear in its application with XHR requests, it is also used
when there are multiple windows or frames onscreen. In general, when there is one Window
object, whether hosted in a frame or iframe, it should be subject to the same-origin
restrictions just described and not allowed to access script from a window object of another
domain. However, while the same-origin policy is very important in protecting us, there are
exceptions to this policy that can be abused or simply misunderstood.

Target URLs

Result of Same-Origin Check
with http://www.example.com Reason

http://www.example.com/index.html Passes Same domain
and protocol
http://www.example.com/other1/other2/index.html Passes Same domain
and protocol
http://www.example.com:8080/dir/page.html Does not pass Different port
http://www2.example.com/dir/page.html Does not pass Different
server
http://otherdomain.com/ Does not pass Different
domain
ftp://www.example.com/ Does not pass Different
protocol

TABLE 7-4 Same-Origin Check Examples
Free download pdf