Enable Cross-Origin Requests (CORS) in ASP.NET Core
Cross-Origin Resource Sharing (CORS) is essential when building .NET web applications to allow them to handle requests from different origins.
By default, web applications are governed by the same-origin policy, which restricts web browsers from requesting a different origin for security reasons.
What is the Same-Origin Policy?
The same-origin policy ensures that a web application can only interact with resources from the same origin (i.e., the same domain). For instance, consider the following URLs:
Both URLs share the same origin because they have the same protocol (https), domain (www.facebook.com).
Consider these two URLs:
These URLs have different origins since they belong to different domains (facebook.com vs twitter.com). In such cases, a browser will block requests to the second origin unless CORS is enabled.
Why Do We Need CORS?
If you have a .NET Core Web API providing data and multiple applications from different origins need to consume this API, the same-origin policy would block their requests. To facilitate cross-origin communication, we enable CORS in our web application. This allows it to:
-
Handle requests from different origins.
-
Bypass the browserâs same-origin policy, ensuring that valid requests from external applications are accepted.
Without CORS, web browsers cannot make cross-origin requests, and it will give an error similar to this :
Acces to XMLHttpRequest at â{WebAPI_URL}â from origin â{ClientApp_URL}â has been blocked by CORS policy: No âAcces-Control-Allow-Originâ header is present on the requested resource.
Example Scenario
Imagine you have a .NET Core Web API that handles user data for multiple client applications. These client applications might be hosted on different domainsâletâs say:
In the provided scenario, I attempted hit the GetBooks method of a Web API from an Angular project without enabling CORS. As expected, it was blocked due to the same-origin policy.
To resolve this, I would need to enable CORS on the Web API, allowing requests from the Angular applicationâs origin. Letâs do it.
Fun Fact: A common misconception with CORS is that the request/call doesnât reach the server at all. However, the request does actually reach the server-side controller endpoint, but the browser blocks the response from being accessed by the front end due to the CORS policy.
How to Enable CORS in .NET
To properly handle CORS in a .NET web application, we need to define a list of allowed domains (origins) that can make requests to our API. A more flexible and maintainable approach is to store these allowed origins in the applicationâs settings file, such as appsettings.json, and load them dynamically at runtime.
STEP-I: Store Allowed Domains in appsettings.json: Instead of hardcoding the allowed domains in the code, we can define them in the configuration file:
{
"AllowedOrigins": [
"https://app1.example.com",
"https://app2.example.com",
"https://mobile.example.com"
]
}
STEP-II: Iâve retrieved the array of allowed origins from the app settings and used them to register CORS services :
string allowedSpecificOrigins = "AllowSpecificOrigins";
WebApplicationBuilder? builder = WebApplication.CreateBuilder(args);
string[]? allowedOrigins = builder
.Configuration
.GetSection("AllowedOrigins")
.Get<string[]>();
builder.Services.AddCors(options =>
{
options.AddPolicy(allowedSpecificOrigins,
policy =>
{
policy.WithOrigins(allowedOrigins)
.AllowAnyMethod()
.AllowAnyHeader();
});
});
builder.Services.AddControllers();
STEP-III: Enable CORS middleware :
app.UseCors(allowedSpecificOrigins);
Available Methods:
-
AllowAnyOrigin: Permits requests from all origins without restriction.
-
WithOrigins: Restricts requests to specific origins. You can pass one or more origins as arguments to this method.
-
AllowAnyHeader: Permits requests with any headers.
-
WithHeaders: Restricts requests to specific headers. You can pass one or more headers as arguments to this method.
-
AllowAnyMethod: Permits requests with any HTTP method (e.g., GET, POST, PUT, DELETE).
-
WithMethods: Restricts requests to specific HTTP methods. You can pass one or more methods as arguments to this method.
Important things to keep in mind about CORS
âď¸ CORS is not a security feature. CORS is a W3C standard that allows a server to relax the same-origin policy.
âď¸ An API isnât safer by allowing CORS.
âď¸ The order in which you register the CORS middleware is crucial. Ensure that the CORS registration is placed in the correct position within the middleware pipeline. Below is the default middleware order, including CORS :
Whenever you're ready, there are 3 ways I can help you:
- Subscribe to my youtube channel : For in-depth tutorials, coding tips, and industry insights.
- Promote yourself to 9,000+ subscribers : By sponsoring this newsletter
- Patreon community : Get access to all of my blogs and articles at one place