CORS Explained : Cross-Origin Resource Sharing

·

2 min read

What is CORS :

A security mechanism implemented in web browsers to allow or prevent websites from requesting other website resources.


Why we use CORS :

as mentioned before, to allow or prevent websites from requesting other website resources.

Now, why do we prevent websites from making requests?

let's take this example:

  1. This is Nour

  2. Nour is using the browser to access

    1. Her bank account.

    2. Other accounts are opened in the browser for personal reasons.

  3. The browser keeps track of her passwords, cookies and sensitive data to keep her login.

  1. Nour visited a malicious website

  2. The malicious website tries to call her credit card data through a script as if the request is made from the original website ( Nour ).

    This attack is called CROSS-SITE REQUEST FORGEY

    and the CORS mechanism is used to prevent these types of attacks.


how does CORS work :

The mechanism works by adding an origin header to API responses ( requested API) to tell the browser about the origins that are allowed to access the API.

First case :

  1. The Attacker sends a request to the API

  2. The browser does a Preflight: check if the origin ( sender ) is allowed to make the request

    1. The API responds with a response header that contains the allowed origins.

    2. The browser check if the (sender) origin is one of them.

The browser block the request because there is no Hacker.com in the origins List.

Second case :

  1. The market sends a request to the API

  2. The browser does a Preflight.

    1. The API responds with a response header that contains the allowed origins.

    2. The browser check if the (sender) origin is one of them.

  3. The browser allows the request because Market.com is allowed to request the API.

  4. The browser sends the response to the market.com


THIS IS THE END , THANK YOU FOR READING .