Understanding CORS (Cross-Origin Resource Sharing)

Osama HaiDer
3 min readDec 1, 2024

--

Have you ever tried to fetch data from a different domain in your web application and seen an error in the browser console saying, “Access to fetch at ‘URL’ from origin ‘YourDomain’ has been blocked by CORS policy”? This happens due to CORS.

In this blog, we’ll explain what CORS is, why it exists, and how to handle it in .NET applications.

What Is CORS?

CORS stands for Cross-Origin Resource Sharing. It is a security feature enforced by web browsers to prevent unauthorized access to resources on a server from a different domain.

For example, if your frontend app is hosted on http://frontend.com and it tries to fetch data from an API hosted on http://backend.com, the browser needs permission (via CORS) to make this cross-origin request.

Why Does CORS Exist?

CORS exists to:

  • Protect user data: Prevent malicious websites from fetching sensitive data.
  • Control resource sharing: Allow servers to decide which domains can access their resources.

How CORS Works

  1. Preflight Request:
    Before making certain requests (like POST, PUT), the browser sends a preflight OPTIONS request to the server. This request checks if the actual request is allowed.
  2. Response Headers:
    The server responds with headers indicating whether the request is permitted.
    Example of a CORS response header:
Access-Control-Allow-Origin: http://frontend.com

Common CORS Headers

Handling CORS in .NET

In .NET, you can enable and configure CORS in your API to allow cross-origin requests.

Step 1: Install CORS Package

If you’re using .NET Core or later, the CORS middleware is already included in the framework.

Step 2: Configure CORS in Program.cs

var builder = WebApplication.CreateBuilder(args);

builder.Services.AddCors(options =>
{
options.AddPolicy("AllowSpecificOrigin", policy =>
{
policy.WithOrigins("http://frontend.com") // Allow specific origin
.AllowAnyHeader() // Allow all headers
.AllowAnyMethod(); // Allow all methods
});
});

var app = builder.Build();

app.UseCors("AllowSpecificOrigin"); // Apply the CORS policy

app.MapControllers();

app.Run();

Testing CORS

Once you’ve configured CORS, test your API by making a cross-origin request from your frontend.

Example using JavaScript:

fetch('http://backend.com/api/data', {
method: 'GET'
})
.then(response => response.json())
.then(data => console.log(data))
.catch(error => console.error('Error:', error));

If CORS is correctly set up, your API will respond without any errors.

Advanced CORS Configuration

  1. Allow All Origins:
    Not recommended for production but useful for testing.
policy.AllowAnyOrigin().AllowAnyMethod().AllowAnyHeader();

2. Restrict Methods:
Specify allowed HTTP methods.

policy.WithMethods("GET", "POST");

3. Allow Credentials:
Allow cookies or authentication tokens.

policy.AllowCredentials();

4. Custom Headers:
If your API expects specific headers, list them explicitly.

policy.WithHeaders("Authorization", "Content-Type");

Summary

CORS is essential for securing web applications and controlling how resources are accessed across domains. By properly configuring CORS in your .NET API, you can ensure a secure and functional integration between your backend and frontend.

Key Points:

  • CORS prevents unauthorized access to APIs from different domains.
  • Use .WithOrigins() to allow specific domains in your .NET app.
  • Test your configuration to confirm it works as expected.

Implement CORS in your project today and enable secure cross-origin communication!

--

--

Osama HaiDer
Osama HaiDer

Written by Osama HaiDer

SSE at TEO International | .Net | Azure | AWS | Web APIs | C#

No responses yet