ASP.NET Core  

How to configure CORS policy in ASP.NET Core for multiple origins step by step?

Introduction

In modern web development using ASP.NET Core Web API, your frontend and backend almost never run on the same origin. For example, your React or Angular application might be running on http://localhost:3000 during development, while your API is hosted on a different domain like https://api.yourapp.com.

By default, browsers block such cross-origin requests due to a security rule called the Same-Origin Policy. This is where CORS (Cross-Origin Resource Sharing) becomes essential.

CORS allows your ASP.NET Core backend to explicitly define which external domains (origins) are allowed to access your API, making your application both secure and functional.

In this detailed guide, you will learn:

  • What CORS is and how it works internally

  • How to configure CORS for multiple origins in ASP.NET Core step by step

  • Real-world scenarios and architecture usage

  • Common mistakes developers make

  • Best practices for production-ready applications

What is CORS?

CORS (Cross-Origin Resource Sharing) is a browser-enforced security mechanism that controls how resources on a web server can be requested from another domain.

Real-Life Analogy

Think of your API as a secure office building:

  • Only authorized visitors (origins) are allowed inside

  • Security checks identity before granting access

Similarly, CORS policies define which domains can access your backend.

Why CORS is Important in Real Applications

In real-world systems:

  • Frontend: http://localhost:3000 (React app)

  • Backend: https://api.myapp.com (ASP.NET Core API)

Without CORS:

  • Browser blocks the request

  • You see errors like: "No 'Access-Control-Allow-Origin' header"

With CORS:

  • Controlled and secure communication is established

Real-World Scenario

Consider an e-commerce platform:

  • Customer website (shop.com)

  • Admin panel (admin.shop.com)

  • API server (api.shop.com)

You must allow only trusted domains to access your API, not the entire internet.

Step 1: Create ASP.NET Core Web API Project

dotnet new webapi -n CorsDemo

Step 2: Configure CORS Policy for Multiple Origins

In Program.cs:

builder.Services.AddCors(options =>
{
    options.AddPolicy("AllowSpecificOrigins", policy =>
    {
        policy.WithOrigins(
            "http://localhost:3000",
            "https://myfrontend.com"
        )
        .AllowAnyHeader()
        .AllowAnyMethod();
    });
});

Deep Explanation

  • WithOrigins → Defines allowed domains (multiple origins supported)

  • AllowAnyHeader → Allows custom headers like Authorization

  • AllowAnyMethod → Allows GET, POST, PUT, DELETE

Step 3: Apply CORS Middleware

app.UseCors("AllowSpecificOrigins");

This must be placed before authorization middleware:

app.UseAuthorization();

Step 4: Apply CORS at Controller Level (Optional)

[EnableCors("AllowSpecificOrigins")]
[ApiController]
[Route("api/[controller]")]
public class ProductsController : ControllerBase
{
    [HttpGet]
    public IActionResult Get()
    {
        return Ok("CORS Enabled Response");
    }
}

Step 5: Testing CORS Behavior

  • Request from allowed origin → Success

  • Request from unknown origin → Blocked by browser

How CORS Works Internally (Important Concept)

When a browser makes a cross-origin request:

  1. It sends a preflight request (OPTIONS)

  2. Server responds with allowed origins, headers, and methods

  3. Browser validates response

  4. If allowed → actual request is sent

This is why proper configuration is critical.

Real-World Use Case

Scenario: Multi-Frontend Architecture

  • Web App: https://app.company.com

  • Admin Panel: https://admin.company.com

  • Mobile API: https://api.company.com

CORS setup:

policy.WithOrigins(
    "https://app.company.com",
    "https://admin.company.com"
);

This ensures only trusted clients can access backend services.

Before vs After CORS Configuration

Before:

  • API calls fail in browser

  • Developers see confusing errors

  • Frontend cannot connect to backend

After:

  • Secure cross-origin communication

  • Controlled API access

  • Stable frontend-backend integration

Common Mistakes Developers Make

Mistake 1: Using AllowAnyOrigin in Production

policy.AllowAnyOrigin();

This exposes your API to any domain and is a major security risk.

Mistake 2: Incorrect Middleware Order

CORS must be configured before authentication/authorization middleware.

Mistake 3: Using Credentials with AllowAnyOrigin

This combination is not allowed and causes runtime errors.

Advanced CORS Configuration

Allow Credentials (Cookies / Auth Tokens)

policy.WithOrigins("https://myfrontend.com")
      .AllowCredentials()
      .AllowAnyHeader()
      .AllowAnyMethod();

Restrict HTTP Methods

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

Advantages of CORS in ASP.NET Core

  • Enables secure communication between domains

  • Supports modern frontend architectures (React, Angular, Vue)

  • Provides fine-grained access control

Disadvantages of CORS

  • Misconfiguration can expose APIs to security risks

  • Debugging CORS issues can be time-consuming

  • Requires careful planning in production

Best Practices for CORS Configuration

  • Always whitelist specific domains in production

  • Avoid AllowAnyOrigin in secure applications

  • Separate configurations for development and production

  • Log and monitor failed CORS requests

Summary

CORS configuration in ASP.NET Core is a fundamental requirement for modern distributed web applications where frontend and backend operate on different domains. By properly defining policies for multiple origins, controlling headers and HTTP methods, and understanding how browsers enforce CORS, developers can build secure and scalable APIs. Whether you are working on enterprise systems, microservices, or cloud-based applications, implementing CORS correctly ensures seamless communication while protecting your backend from unauthorized access.