问题
I understand that same origin policy is about restricting javascript from other domains from accessing contents of a page.
I read these particular points of importance of same origin policy on the Web:
XmlHttpRequests: they don't work if done cross domain. But why would a Web page make an xhr request to a less trusted site in the first place? Isn't it the Web page's fault? Why impose a restriction then?
cookies: it is not right if a malicious page can view my Facebook cookies. So if it tries to check "document.cookies" it will never see my Facebook cookies anyway. Where does same policy come into the picture here?
cross page communication: the only way a malicious page opened in a tab can view information about another page is via cookies and or local storage. So where does same origin policy help here?
回答1:
XmlHttpRequests
For example: To stop your site using my browser to get my data from my bank's website when my browser is logged into my bank.
cookies
The same origin policy doesn't apply to cookies. Cookies are simply sent to the site for which they are registered.
cross page communication: the only way a malicious page opened in a tab can view information about another page is via cookies and or local storage. So where does same origin policy help here?
You're operating under a misconception. Access to other pages is also available through window.open
and frames (including iframes).
Once you have access to the DOM of another page, you can get data from it and you have the same issues that you would if XHR exposed other websites to JavaScript. Thus the same origin policy locks access to remote documents through frames.
回答2:
It's not about protecting you from accessing untrusted things, it's about preventing your page from accessing things it shouldn't. Without the same origin policy, there's nothing stopping you (with the user's cookies) from doing, say:
$.getJson('http://api.example.com/my/secret/stuff')
or
$('<iframe src="http://gmail.com">').appendTo('body').contents().html()
As for cookies, it's not really the Same Origin Policy in play here:
Cookies use a separate definition of origins. A page can set a cookie for its own domain or any parent domain, as long as the parent domain is not a public suffix.
(from Same-origin policy at MDN)
回答3:
If I use a XSS flaw to put a remote, evil js on your page, it cannot make requests to your, or any random, server. (actually, it can, but it doesn't have all features on)
来源:https://stackoverflow.com/questions/25399859/how-does-same-origin-policy-solve-issues-with-xhr-cookies-and-cross-page-commui