What is CORS?
Tags: cors, webdev, programming, security
Published: 2023-03-07 15:10:33

Hi, I am Arun Kumar Palani, Senior software engineer in Luxoft. Let's discuss CORS in detail.

**Note**: This is a technical topic. If the reader is from a development background, he/she can easily get the key concepts of CORS. If not from development background, please read it twice it will help you to understand what is CORS? And how we can implement it in any application. 

<u>**What is CORS?**</u>

CORS is a technique that allows servers to specify who can access its resources and which HTTP request methods are allowed by the requested resource.

<u>**Origin and sample use case:**</u>

CORS started to make request resource giving easier and more effective. With CORS, it is attainable for one app to share possessions with an application owned by another domain. This leads to a netting where many apps from various rules share money with one another.

For example, 

1.	**Online food delivery app:** have you ever doubted how miscellaneous online food delivery apps’ latest fares and other connected data lands on your favorite food delivery app? That’s the power of the CORS policy. If you are going to build an online food delivery application that integrates data and possessions from all vendors and hotels, the easiest habit would be to attract data from the vendor’s or hotel’s APIs with CORS configured.
Specifically, CORS is a technical implementation that uses additional HTTP headers to state browsers to give a web request running at one inception access to selected possessions from a different inception. A web application kills a cross-origin HTTP request when it requests a property that has a different origin (rule, protocol, or traffic) from its own. A CORS request can be sparked by providing an additional plunge called “Origin” in the http request.

The cross-origin request policy of the browser (or web view) determines whether the request is allowed. Most browsers implement a same-origin policy that restricts how JavaScript can interact with resources from other domains. The same-origin policy is a critical security mechanism that helps isolate potentially malicious code from running on a user's web page. The same-origin policy has some drawbacks, however. For example, it prevents web pages from loading resources from other domains that they might need to display content or interact with users. 

CORS is a mechanism that allows web pages to request resources from other domains in a way that is safe and secure. CORS defines a standard way for browsers to request resources from other domains. When a browser makes a request for a resource from a different domain, it first sends a request to the server to see if the server will allow the cross-origin request. If the server allows the request, the browser then makes the request for the resource. The server can specify which resources are allowed to be requested from other domains, and which methods (such as GET or POST) are allowed. The server can also specify how long the response to the request can take. CORS is a safe and secure way for web pages to request resources from other domains. It is a standard that is supported by all major browsers.

**Why do we need such communications?**

1.Nowadays modern application architecture and evolving microservice design implementations require a front-end application and a backend application.

2.Assume for Frontend we might use Angular or React. Because it is simple, lightweight and we can create SPA or multiple page applications with html and CSS combination with improved state management techniques like redux, store etc.

3.For Backend we might use .NET, Java or python based on product and architectural suggestions.

4.Our Angular application is hosted on some web app and the backend application is hosted on some different web app.
Ex) Angular app: https:anuglartestapp.com
Ex) backend app: https:testapi.com

5.To establish a connection between these two web apps we might need some configurations that can be explicitly written in our only allow the origin of my front-end application.

**What will happen If we don’t specify such origin conditions?**

1.The backend application can be accessed by different people and different other endpoints.

2.It will lead to a cross site scripting attack and might create security vulnerability in the application.

3.If proper permission is not provided it will again lead to security vulnerability. Ex) (we want to expose a GET method to some third-party but if we don’t add CORS to only GET method the third party may access to POST, PUT & DELETE which is security concern)

**How to work with CORS?**

1.First, we need to check the HTTP scheme: Whether it is HTTP or HTTPS

2.Second, we need to check the port where the application is hosted.

3.Third, we need to the check domain name of the hosted application.

Once we get all those necessary information, we need to configure our front-end URLs to the back-end application so that it can communicate and produces response in the UI.

1.From the example we can see the scheme is HTTPS for both the frontend and backend, the port if we run in local host both the applications will run on different ports. We can see the domain name is different for each web app.
Ex) Angular app: https:anuglartestapp.com
Ex) backend app: https:testapi.com
Technical configurations: We must be very careful when we configure CORS for a web client, and we need to provide only necessary permissions.

**What is Preflight request?**

The CORS Operates in the following manner for Complicated Requests:
1.A pre-flight request is sent to the destination site before the actual request is sent. The OPTIONS HTTP Request method is used to send this pre-flight request.

2.The Authorized methods and Allowed origin information about the target site would be included in the response to the pre-flight request. The browser sends the actual GET/POST request after evaluating this answer to see whether the target site can deliver the desired information.

**CORS attributes:**

It works by setting specific HTTP headers, which allow a server to specify which origins are allowed to access its resources. The most common CORS headers are:

**Request headers:** These headers are set by the client browser when it makes a call to server.

**Base Origin:** This gives the details about the client application where the client application is hosted (The DNS related details of the client app)

**Access-Control-Request-Methods**: This is the header which is added in preflight mechanism of the request. It will check with the backend server whether these methods are allowed in the backend server for processing.

**Access-Control-Allow-Headers:**  Here we can pass which http headers are allowed to pass to the backend server to establish connection. This is also a preflight mechanism to check which http headers are supposed to be allowed in server.

**Response headers:**

**Access-Control-Allow-Origin:** This header specifies which origin is allowed to make requests to the resource. If the values come from the base origin did not match with the server configured value, then the user will experience CORS error on the mismatched Origin.
<u>Sample headers:</u>
1.Access-Control-Allow-Origin: * 
2.Access-Control-Allow-Origin: <origin> where origin = [www.test.com]
3.Access-Control-Allow-Origin: null which refers to null reference origin.

**Access-Control-Allow-Methods:** This header specifies which HTTP methods (e.g., GET, POST, PUT, etc.) are allowed to access the resource. If the headers did not match with the Access-Control-Request-Methods request headers, then the user or the resource who is sending the request will experience CORS error on the permissible methods.

<u>Sample headers:</u>
1.Access-Control-Allow-Methods: * which allows all header.
2.Access-Control-Allow- Methods: < methods -name> [GET, PUT, POST, DELETE] We can specify which methods are allowed.

**Access-Control-Allow-Headers**: This header specifies which HTTP headers (e.g., Content-Type, Authorization, etc.) are allowed to be sent with the request.
<u>Sample headers:</u>
1.Access-Control-Allow-Headers: * which allows all header.
2.Access-Control-Allow-Headers: <header-name>.

**Access-Control-Max-Age:** This header specifies how long (in seconds) the preflight request can be cached in the browser.
<u>Sample headers:</u>
1.Access-Control-Max-Age: 3600 specifies the preflight request is valid for next 1 hour.

**Access-Control-Allow-Credentials**: Requests are passed without credentials like cookies or the authorization header by default in CORS. But, by setting the CORS Access-Control-Allow-Credentials header to true, the cross-domain server can allow reading the response when credentials are supplied to it. The browser will allow the requesting website to access the answer if the asking website uses JavaScript to signal that it is sending cookies along with the request since the Access-Control-Allow-Credentials response header is set to true.
<u>Sample headers:</u>
1.Access-Control-Allow-Credentials: true, which allows credentials to be shared. We can toggle it based on the requirement.

**How to Implement CORS in .NET core?**

1.Install the NuGet package - Microsoft.AspNetCore.Cors
2.In configureService() method add - services.AddCors()
3.In Configure() method - options => options.AllowAnyOrigin()
4.CORS can be enabled in controller level by adding [EnableCors] attribute and we need to add few lines in ConfigureService() method.
services.AddCors(options => { options.AddPolicy(\"AllowSpecificOrigin\", builder =>
{
         builder.WithOrigins(\"http://localhost:3000\")
         .AllowAnyHeader()
         .AllowAnyMethod();
            });
      });
}
We need to change the origin as per requirements, we can also add multiple origins and can also set what method can access the controller.
5.In configure method we need to add it as a middleware
app.UseCors(\"AllowSpecificOrigin\");

**How to Implement CORS in .NET framework?**

1.	Install the Microsoft.AspNet.WebApi.Cors NuGet package
2.	We need to add the following line of code to the WebApiConfig.cs file -> config.EnableCors();
3.	We can also CORS in the controller level, method level as well. By adding EnableCors[“*”,”*”,”*”] as an attribute from the controller top. This is the default value for security purpose we need to configure the Domain, Method, Port where we want to provide access.
4.	Another way is writing this code in a separate class file and providing all the domain URL’s, methods and ports and we can add this class as a attribute over the controller top.

**CORS in Microservice:**

Prior to the standardization of CORS, the same-origin-policy (SOP) prohibits resource sharing between two web application domains with different origins. Yet today, microservice architecture is becoming more popular. This combines numerous tiny apps to create large, complicated applications. The ability to share resources is crucial for these little applications. Although they are hosted on several domains or ports and deployed on various servers, they are loosely connected. Standardized CORS are essential in this situation. Even when a http request is performed to a different domain, subdomain, protocol, or port, it still permits resource sharing.

**Significance of SOP:**

SOP is a crucial security feature that limits the interactions between resources imported from different origins in a document or script. It assists in isolating potentially harmful papers, hence lowering attack surfaces. Cross Site Scripting (XSS) and Cross Site Request Forgery (CSRF) attacks frequently target or hit web applications. Developers of online applications have utilized SOP as a solution to this problem.

The concept of "origin," which mandates that two web pages in the same domain, host, and protocol have the same origin, is a crucial part of SOP. Traditionally, origins are formatted as follows: "Origin= (domain, port, protocol)".

For example, a rule running in a browser cannot access the values on other domains running in the alike browser. This is causing the web browser carries out the same origin tactics, isolating the data being joint between two different requests on the same portal.

**Advantages of CORS:**

1.We can provide options for different domains of the application would establish communication between each other in a secure way.
2.We can provide security of the resource in three levels.
a. Origin level
b. Method level
c. Header level
3.The front-end application can easily integrate with the back end in a secure for data exchanging.
4.We can test the CORS header in the postman and verify it.

**Disadvantages of CORS:**

1.CORS increases the complexity of the applications, and it can introduce security risks if it is not properly implemented.
2.Access-Control-Allow-Origin: (*) All domains are allowed which leads to CSRF attack.
3.Improper regular expression in the validations leads to request failure even if it is a valid request.