Search code examples
javascriptsecuritysame-origin-policy

How does same origin policy solve issues with XHR, cookies and cross page commuication?


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?


Solution

  • 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.