What is CORS, and why does an ASP.NET Core API need to explicitly configure it for browser-based clients on a different origin?
Short answer
CORS is a browser-enforced security mechanism restricting web pages from making requests to a different origin (scheme, domain, or port) than the one that served the page, unless the target server explicitly permits it via response headers -- an ASP.NET Core API called from a…
Advertisement
AModel answer
CORS is a browser-enforced security mechanism restricting web pages from making requests to a different origin (scheme, domain, or port) than the one that served the page, unless the target server explicitly permits it via response headers -- an ASP.NET Core API called from a frontend hosted on a different origin (like a React app on a different port during development) must explicitly configure a CORS policy or the browser will block the response from reaching the calling JavaScript.
builder.Services.AddCors(options => {
options.AddPolicy("AllowFrontend", policy => {
policy.WithOrigins("https://app.mycompany.com").AllowAnyMethod().AllowAnyHeader();
});
});
app.UseCors("AllowFrontend");Real-world example
A single-page app hosted at app.mycompany.com calling an API at api.mycompany.com (different subdomain, hence different origin) needs the API to explicitly configure CORS to allow requests from app.mycompany.com's origin.
Likely follow-ups
- What exactly counts as a different 'origin' (scheme, host, port)?
- Why is CORS enforced by the browser rather than being a server-side security boundary?
Related topics