DEV Community

Cover image for Same Origin Policy & Cors
Paetelmechanic
Paetelmechanic

Posted on

Same Origin Policy & Cors

The backbone of modern internet web security is something called the Same Origin Policy. It refers to the standard in place throughout most of the interwebs that restricts access to a webpage from a secondary page unless the two pages share the same 'origin'. What's an origin you may ask? Well an origin is the combination of domain, host name, and port number, all working in tandem to provide a very specific identification address for where your page lives on the internet

This mechanism bears a particular significance for modern web applications that extensively depend on HTTP cookies[1] to maintain authenticated user sessions, as servers act based on the HTTP cookie information to reveal sensitive information or take state-changing actions. A strict separation between content provided by unrelated sites must be maintained on the client-side to prevent the loss of data confidentiality or integrity.

While waiting on that to load, let's talk about CORS a bit. CORS stands for Cross Origin Resource Sharing. It as implemented a a bit of a work around for Same Origin Policy because sometimes sites actually do want to allow access to their page from outside sources.

They accomplish this by making allowances to certain pages in their response headers. This can be verified with the use of a get request that will show if a page has permission to access or not.

For Ajax and HTTP request methods that can modify data (usually HTTP methods other than GET, or for POST usage with certain MIME types), the specification mandates that browsers "preflight" the request, soliciting supported methods from the server with an HTTP OPTIONS request method, and then, upon "approval" from the server, sending the actual request with the actual HTTP request method. Servers can also notify clients whether "credentials" (including Cookies and HTTP Authentication data) should be sent with requests

The browser sends the OPTIONS request with an Origin HTTP header to service.example.com containing the domain that served the parent page:

Origin: http://www.example.com
The server at service.example.com may respond with:

An Access-Control-Allow-Origin (ACAO) header in its response indicating which origin sites are allowed. For example:

Access-Control-Allow-Origin: http://www.example.com
Since www.example.com matches the parent page, the browser then performs the cross-origin request.

An Access-Control-Allow-Origin (ACAO) header with a wildcard that allows all domains:

Access-Control-Allow-Origin: *
An error page if the server does not allow a cross-origin request

Hopefully, if you were in the dark about what exactly same origin policy or cors was, this post helped to clarify it somewhat. Happy coding.

Top comments (0)