Skip to main content

Command Palette

Search for a command to run...

CORS Explained

Published
2 min read
CORS Explained
A

I am a software developer as well as a mentor. Teaching is my hobby and coding is my passion. Working on various technologies related to web development.

Developed interest and started writing blogs.

What are CORS?

CORS - Cross Origin Resource Sharing , a standard in browsers which provides security to our applications. It is a mechanism that allows the webapps in different origins communicate proficiently with each other and share their resources as name suggest.

Why do we need CORS?

To restrict any unknown webapp to access my data

Suppose I have a website : https://akshitagarg.com and in another tab I have a banking website https://ICICI.com, in which a user has logged in and all sessions and cookies are stored in the browser.

Now, if there is no CORS, using my website https://akshitagarg.com, I can easily make any request to banking app and make any web request, which raised the security concerns and CORS came into picture🤔

What is Origin

💡
Tuple( Scheme + Host + Port

Example :

  • Scheme : https

  • Host : akshitagarg.com

  • Port: 8000

Origin : https://akshitagarg.com/8000

Note: Origin is not path

Following are considered as same origin:

  • https://akshitagarg.com/a

  • https://akshitagarg.com/api

Following are the different origins:

  • http://akshitagarg.com/8000

  • https://akshitagarg.com/3000

  • https://api.akshitagarg.com/8000

Same-Origin-Policy

Backend controls the CORS

How CORS Works?

Scenario 1: Frontend and Backend at same orgin (CORS not required)

Scenario 2: Making Standard API calls , using GET and POST methods

While making GET/POST request we send origin in the request headers, than backend decides weather to allow the call or not

If the origin is allowed than in response header we get Access-Control-Allow-Origin key

Note: Access-Control-Allow-Origin : *

It means that all origins are allowed to make calls and it is used for public APIs.

Cookies are not sent in CORS. Need to enable:

cred: include

In this case Access-Control-Allow-Origin : * cannot be used and we need to provide exact origin like

Access-Control-Allow-Origin : http://akshitagarg.com

Scenario 3: Non-Standard HTTP Call (PUT, PATCH, DELETE)

In this case, when web app tries to make a request:

Initially broser sends preflight options request to the server. In response if the origin is allowed than the server provides additional HTTP headers ( Accept-Control-Allow-Origin , Access-Control-Allow-Methods)

Than actual HTTP call is triggered.

The End

I hope you enjoyed the article and had a good learning experience.

Follow for more articles and keep sharing👩

Keep coding

Linkedin

hashnode blogs