DEV Community

May Do
May Do

Posted on

The Basics of Same Origin Policy and CORS

Let's say you are accessing your bank account from bank.com in one browser tab, but also have a malicious website, evil.com, open in another. The bank account obviously has important information that you wouldn't want to share, so that's where security mechanisms come into play to prevent that malicious website's Javascript from accessing anything from the bank's browser tab. Such security mechanisms are same-origin policy and CORS (cross-origin resource sharing) that mandates the interactions between one source from another. This means that the codes that are being ran cannot just be any code — it has to have permission.

One way of having permission is through same-origin policy. By sharing the same origins, defined by the protocol, domain, and port of the URL, a site knows that the documents loaded should be able to interact with the resources from that origin and not another. So while evil.com could request to send information, bank.com does not permit to receive that information because they do not share origins. Bank.com could only interact with other documents within Bank.com's server.

Since the same-origin policy is a bit restrictive, another way of having permission is through cross-origin policy. This mechanism bypasses the same-origin policy and allows two sources to interact with each other without sharing origins, however only from sources that are specified. This is very helpful as many sites uses each others' sources such as images. For example, if bank.com requested access to some of loan.com's sources and its server is expecting that request, then loan.com is permitting Bank.com access to that information.

Same-origin policy and CORS are only two of the many policies, but by understanding these policies, you will understand the general core concept of how security policies work to reduce risks in malicious acts.

Top comments (0)