Diagnosing CORS failures in ASP.NET Core: simple vs preflighted requests, policy configuration and middleware order, the wildcard-with-credentials rule, and why CORS relaxes rather than enforces security.
Browsers enforce the same-origin policy; CORS lets a server opt specific origins back in. For 'non-simple' requests — an Authorization header, Content-Type: application/json, PUT/DELETE — the browser first sends a preflight OPTIONS with Origin and Access-Control-Request-* headers, and only sends the real request if the response allows that exact origin, method and headers. Postman works because it isn't a browser and ignores CORS.
To diagnose, look at the preflight in the Network tab: missing Access-Control-Allow-Origin, a 401/404/500 on OPTIONS, or a mismatched origin. Typical fixes: register an explicit-origin policy, put UseCors after UseRouting and before auth. AllowAnyOrigin with credentials is forbidden by the spec. And CORS protects users' browsers, not your API: any non-browser client can still call it.
"First I'd remember that CORS is enforced by the browser, which is why Postman works. The browser's default is the same-origin policy: script on
app.example.com.aucan send some requests toapi.example.com.aubut can't read the responses. CORS is the server saying 'this origin may read my responses'. For simple requests the browser sends the request and checksAccess-Control-Allow-Originon the response. For anything with anAuthorizationheader or a JSON body, it sends a preflightOPTIONSfirst, and if that fails the real request is never sent.So I open dev tools, filter on the API host and look at the
OPTIONSrequest. Nine times out of ten it's one of four things: there's no policy for that origin, often because of a trailing slash orhttpversushttps;UseCorsis in the wrong place, after authorisation, so the preflight gets a 401; the real request failed with a 500 and the exception handler's response didn't carry CORS headers, so the browser reports a CORS error that hides the real one; or someone triedAllowAnyOriginwithAllowCredentials, which the spec forbids and ASP.NET Core rejects. For example, at [company] our SPA showed CORS errors only on one endpoint, and it turned out to be [a timeout at the gateway returning a 504 without CORS headers]; fixing the timeout fixed the 'CORS' error.The mistake I see is treating CORS as API security: locking down origins and thinking the API is protected. It isn't. curl, a server or a malicious script outside a browser ignores CORS completely. CORS protects your users' browsers from other sites reading their data; authentication and authorisation protect the API."
| Request | Preflight? | Why |
|---|---|---|
GET with no custom headers |
No | Simple request |
POST with Content-Type: application/x-www-form-urlencoded |
No | Simple content type |
POST with Content-Type: application/json |
Yes | Not a CORS-safelisted content type |
Any request with Authorization |
Yes | Non-safelisted header |
PUT, PATCH, DELETE |
Yes | Non-simple method |
| Symptom in Network tab | Likely cause | Fix |
|---|---|---|
OPTIONS returns 401/403 |
UseCors after UseAuthorization, or a gateway demanding auth on OPTIONS |
Move UseCors before auth; allow OPTIONS at the gateway |
OPTIONS 204 but no Access-Control-Allow-Origin |
Origin not in policy (scheme, port, trailing slash) | Add the exact origin |
| Preflight OK, real request 'CORS error' | Real request returned 500/502 without CORS headers | Fix the underlying error; check server logs |
Startup InvalidOperationException |
AllowAnyOrigin + AllowCredentials |
List origins explicitly |
| Works in Chrome, fails in Safari | Third-party cookie blocking with credentials: 'include' |
Same-site deployment or BFF |
A dashboard making 20 API calls per page load generated 20 extra preflights, adding about 40 ms each on mobile networks. Setting SetPreflightMaxAge(TimeSpan.FromHours(2)) (Chrome's cap) let browsers cache preflights and cut API request volume from that page by nearly half.
Checks that the candidate understands CORS as a browser mechanism, can debug it methodically from the preflight, and doesn't mistake it for API protection.
Green flags
UseCors correctly and explains whyRed flags
An origin is the triple scheme + host + port. https://app.example.com.au and https://api.example.com.au are different origins (same site, different origin). The browser lets a page send many cross-origin requests (forms, images, scripts) but stops script from reading cross-origin responses unless the server opts in. That is the line CORS draws.
Browser (app.example.com.au) API (api.example.com.au)
| OPTIONS /orders |
| Origin: https://app.example.com.au |
| Access-Control-Request-Method: POST |
| Access-Control-Request-Headers: authorization, content-type
|-------------------------------------------->|
| | CORS middleware checks policy
| 204 No Content |
| Access-Control-Allow-Origin: https://app.example.com.au
| Access-Control-Allow-Methods: POST |
| Access-Control-Allow-Headers: authorization, content-type
| Access-Control-Max-Age: 7200 |
|<--------------------------------------------|
| POST /orders (real request) |
|-------------------------------------------->|
| 200 + Access-Control-Allow-Origin |
|<--------------------------------------------|
Preflights carry no credentials, so an API that demands authentication on OPTIONS will always fail them.
With fetch(url, { credentials: 'include' }) the browser sends cookies and requires Access-Control-Allow-Credentials: true and a specific origin in Access-Control-Allow-Origin. A * is invalid with credentials, because allowing every site to read authenticated responses would defeat the same-origin policy. ASP.NET Core's CorsPolicyBuilder throws when you combine AllowAnyOrigin and AllowCredentials. The dangerous workaround is SetIsOriginAllowed(_ => true), which reflects any origin and effectively re-creates the wildcard with credentials: any website can now read your users' data.
AddCors registers named policies; UseCors() adds CorsMiddleware.UseCors must sit after UseRouting (when called explicitly) so it can read [EnableCors]/RequireCors metadata, and before UseAuthentication/UseAuthorization so preflights are answered before auth runs.Vary: Origin so caches don't serve one origin's response to another.UseCors (for example a gateway or an early exception) won't have CORS headers.POSTs are sent and executed; the browser only hides the response. That's why CSRF protection is still needed for cookie-authenticated endpoints.Origin is trivially forged outside a browser.Serving the SPA and API from the same origin (a BFF, or a reverse proxy routing /api to the API) removes CORS and third-party cookie problems in one step. This is often the best fix rather than a better policy.
Authorization header and watch it in dev tools.UseCors after UseAuthorization and observe the preflight fail with 401.AllowAnyOrigin().AllowCredentials() and read the startup exception.curl -X OPTIONS -H "Origin: https://evil.example" -H "Access-Control-Request-Method: POST" -i https://localhost:5001/orders and confirm no allow-origin header comes back.A correct CORS setup for an SPA on a sibling subdomain, with explicit origins from configuration, preflight caching and the middleware in the right place.
var builder = WebApplication.CreateBuilder(args);
string[] origins = builder.Configuration.GetSection("Cors:AllowedOrigins").Get<string[]>() ?? [];
builder.Services.AddCors(o => o.AddPolicy("spa", p => p
.WithOrigins(origins) // exact scheme+host+port, no trailing slash
.WithMethods("GET", "POST", "PUT", "DELETE")
.WithHeaders("Authorization", "Content-Type", "X-Request-Id")
.WithExposedHeaders("Location", "ETag") // headers script may read
.SetPreflightMaxAge(TimeSpan.FromHours(2)))) // Chrome caps at 2 hours
;
builder.Services.AddAuthentication().AddJwtBearer();
builder.Services.AddAuthorization();
builder.Services.AddProblemDetails();
var app = builder.Build();
app.UseExceptionHandler();
app.UseRouting();
app.UseCors("spa"); // after routing, before auth: preflights never hit auth
app.UseAuthentication();
app.UseAuthorization();
app.MapGet("/orders", () => Results.Ok(Array.Empty<object>())).RequireAuthorization();
app.Run();
{
"Cors": {
"AllowedOrigins": [ "https://app.example.com.au" ]
}
}
// Don't: reflects any origin with credentials, letting every website read your users' data
// p.SetIsOriginAllowed(_ => true).AllowCredentials();
UseCors after UseAuthorization. Why it is wrong: preflights have no credentials and get 401. Instead: call UseCors after UseRouting and before authentication.SetIsOriginAllowed(_ => true) with AllowCredentials to 'make it work'. Why it is wrong: any malicious site can read authenticated responses. Instead: list origins explicitly from configuration.https://host[:port] with no path.http://localhost:3000 in the policy and shipping it, or having only dev origins in appsettings.json. Why it is wrong: production either fails (origin missing) or allows a local origin any developer machine can serve. Instead: keep origins in per-environment configuration (appsettings.Production.json, App Configuration) and test the production list in staging.Access-Control-Allow-Origin headers make browsers reject the response. Instead: own CORS in exactly one layer.The senior insight is that the best CORS policy is often no CORS at all: a same-origin deployment (BFF or path-based routing at the edge) removes preflight latency, third-party cookie breakage in Safari and Firefox, and a whole class of misconfiguration. When cross-origin is unavoidable, the policy is configuration, should be per-environment, and should be tested like any other security setting.
| Option | When it fits | Cost | When not to |
|---|---|---|---|
| Same origin via BFF or edge routing | First-party SPA | One more hop or a BFF service | Third-party consumers |
| Explicit-origin CORS policy | Known partner SPAs, sibling subdomains | Preflight latency, config per env | Unknown origins |
Reflected origin (SetIsOriginAllowed) with an allow-list check |
Many tenant subdomains | Must validate carefully | Never with _ => true |
| No CORS (server-to-server only) | Backend APIs | None | Any browser client |
Measure: preflight count per page load, 4xx/5xx on OPTIONS in logs, and an integration test asserting a disallowed origin gets no Access-Control-Allow-Origin.
HEAD is GET without the body: same status code and headers (Content-Length, ETag, Last-Modified), so clients can check that a resource exists, how big it is or whether it changed, without downloading it. It is safe, idempotent and cacheable.
OPTIONS asks what the server supports for a URI; the answer is the Allow header. Its main real-world use is the CORS preflight: browsers send OPTIONS with Origin and Access-Control-Request-Method before non-simple cross-origin calls, and ASP.NET Core's CORS middleware answers it.
ASP.NET Core handles preflight and 405 Allow headers for you, but Minimal APIs don't map HEAD automatically. The trade-off: HEAD support is cheap to add but must not cost as much as the GET it replaces.
A refresh token lets a client get new short-lived access tokens without asking the user to sign in again. Because it is long-lived, it is the most valuable token to steal.
HttpOnly, Secure, SameSite cookie.The trade-off: a BFF adds a server hop and session state, in exchange for tokens that never reach the browser.
How to tell it (STAR)
**S:** At [company] our SPA's export screen failed with CORS errors while everything else worked, and [number] users a day were affected. **T:** I picked it up and needed to find why only one endpoint broke. **A:** I opened dev tools and saw the preflight succeed but the real request come back as a 504 from [the gateway], with no CORS headers. Application Insights showed the export ran about 45 seconds against a 30-second gateway timeout. I raised the timeout as a stopgap, made the gateway add CORS headers to errors, and then moved the export to a background job returning 202 with a status endpoint. **R:** The errors went to zero, exports finished in [time], and we added a test and an alert so a 'CORS error' would never hide a timeout again.
Last updated 23 Nov 2026.