CodeOath
← All posts
.NET Core / Web API70 min total · 19 parts

Building REST APIs with ASP.NET Core: Routing, Middleware, and Dependency Injection

Contents — Part 13 of 19: CORS
Part 13 of 19 · ~1 min

CORS

Cross-Origin Resource Sharing controls whether a browser running JavaScript from one origin is allowed to call your API on a different origin — a browser-enforced restriction, not a server-side security boundary by itself (a non-browser client, like curl or a mobile app, isn't affected by CORS at all).

builder.Services.AddCors(options =>
{
    options.AddPolicy("AllowFrontend", policy =>
        policy.WithOrigins("https://app.example.com")
              .AllowAnyMethod()
              .AllowAnyHeader()
              .AllowCredentials());
});

// ...

app.UseCors("AllowFrontend"); // must run before UseAuthorization, and before MapControllers

A common mistake is reaching for AllowAnyOrigin() to make a CORS error "go away" during development and shipping it to production — combined with AllowCredentials() specifically, this combination isn't even allowed by the CORS spec (browsers reject a wildcard origin paired with credentials), and more generally it defeats the entire purpose of CORS as a boundary. Register named, explicit policies with a known list of allowed origins for anything beyond local development.