What is Same Origin Policy (SOP)
- The same origin policy is imposed by browsers.
Same Origin Policy Examples
http://gurgaon.taxi.com/home/index.html can access the following documents since they are considerd from same origin
- But it can't access the following documents since they are considered from different origins
https://gurgaon.taxi.com/home/index.html (different Protocol)
http://gurgaon.taxi.com:8080/home/index.html (different Port)
http://faridabad.taxi.com/home/index.html (different host)
Why same origin policy in the first place
- In order to pervert Cross-site-scripting(XSS) security risk.
- In XSS, attackers inject client-side script into Web pages viewed by the other users.
What is the downside of SOP.
- Same Origin Policy (SOP) makes it hard to d Who "mash-up"
Because it disallows XMLHttpRequest object from accessing document from different origins.
- SOP based security model of HTML
Introduced in Netscape Navigator 2.0
Is becoming a hindrance of writing Rich client application.
- Work-Arounds( not a desirable solutions, however)
The client asks the server to access the document on behalf of it not efficient.
?Issues of SOP dealt with in HTML5
A document running in a window A (or iframe A) cannot access a document running in window B (or iframe B).
HTML5 solves through "Cross-Domain Messaging"
A document loaded from origin A cannot access service running in Origin B through traditional XHR.
A HTML5-enabled browesers support Cross-Origin Resource Sharing (CORS) and CORS-enabled XMLHttpRequest2(XHR2).
?What is & Why Cross-Domain Messaging
- Before Cross-Domain Messaging, communications between iframes, windows, tabs are disallowed by browser.
- In order to prevent XSS
- Cross-Domain Messaging enables secures cross-domain messaging across iframes, windows, tabs regardless of origins of the documents they loaded.
- These iframes, window, tabs can send/receive data to/from other iframe windows and tabs of different origins.
Posting a Message to another iframe (from Host window)
<p> The source origin of this page is http://abc.domain1.com</p>
aframe = document.getElementById('iframe');
aframe.postMessage("Hello World", //Message to post
"http://def.domain2.com" //Target Origin
<p> Target iframe </p>
<iframe id="iframe" src ="http://def.domain2.com/my_iframe.html"></iframe>
Receiving a Message from the iframe (in host window)
- Add "onmessage" event handler
- The event handler receives "event", which contains "data", "origin", and "source" properties.
- You need to check the "origin" to make sure the message if from the trusted origin or origins.
//Handle message received from the iframe
if(e.origin !== "http://def.domain2.com")
//filter origin for security reasons
//Disregard the message since it is not from a valid origin
//e.data contains message from the sender
Thanks for reading!