ASP.NET Core cookbook · Beginner

Configure CORS for a browser front end

The SPA on another origin can't call the API, and someone suggests allowing every origin.

Create a free account to save this page, take notes and track your progress. Sign in

Approach

Define a named policy listing exact origins from configuration, the methods and headers you need, and credentials only if you use cookies. Apply it to the API endpoints.

Solution

var builder = WebApplication.CreateBuilder(args);
var origins = builder.Configuration.GetSection("Cors:Origins").Get<string[]>() ?? ["https://app.example.com"];
builder.Services.AddCors(options => options.AddPolicy("spa", policy => policy
    .WithOrigins(origins)
    .WithMethods("GET", "POST", "PUT", "DELETE")
    .WithHeaders("Content-Type", "Authorization")
    .AllowCredentials()
    .SetPreflightMaxAge(TimeSpan.FromHours(1))));
var app = builder.Build();
app.UseCors();
app.MapGroup("/api").RequireCors("spa").MapGet("/me", () => new { name = "Ana" });
app.Run();

Pitfalls

  • AllowAnyOrigin() with credentials (not allowed) or SetIsOriginAllowed(_ => true) with credentials (dangerous).
  • Thinking CORS protects the API; it only controls which browser pages can read responses. Keep authentication.
  • Missing UseCors() or placing it after endpoints that need it.

Variations

  • Serve the SPA and API from the same origin (reverse proxy) to avoid CORS entirely.
  • Use .WithExposedHeaders("ETag", "Location") when the front end needs to read those headers.

Further reading: Enable CORS

Reference: https://learn.microsoft.com/en-us/aspnet/core/security/cors

More ASP.NET Core recipes

Was this page helpful?