📁 Sangam Dhakal - Portfolio v2.0 - Netscape Navigator 4.0
_
□
×

📚 Interview question

Your React SPA on app.example.com.au calls your ASP.NET Core API on api.example.com.au and the browser console shows 'blocked by CORS policy', but the same request works in Postman. How does CORS and the preflight request actually work, how do you diagnose and fix it, why does AllowAnyOrigin with AllowCredentials fail, and why is CORS not a security control for your API?

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.

Mid-Level Debugging Intermediate aspnet-core cors debugging same-origin-policy security spa

🎯 Key points

  • Same-origin policy is the browser's default; CORS is an opt-in relaxation by the server
  • Preflight OPTIONS for non-simple requests: Authorization header, JSON content type, PUT/DELETE
  • Access-Control-Allow-Origin must echo the exact allowed origin (scheme, host, port) or *, and * is invalid with credentials
  • AllowAnyOrigin + AllowCredentials is forbidden by the spec; CorsPolicyBuilder throws
  • UseCors after UseRouting and before UseAuthentication/UseAuthorization
  • Error responses (500 from the exception handler, 504 from a gateway) without CORS headers look like CORS errors
  • Allowed origins are per-environment configuration; localhost origins never ship to production
  • Postman/curl ignore CORS entirely: CORS never protects the server, authentication does

⏱ 30-second answer

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.

🗣 Full answer (senior)

How I would answer this in an interview

"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.au can send some requests to api.example.com.au but 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 checks Access-Control-Allow-Origin on the response. For anything with an Authorization header or a JSON body, it sends a preflight OPTIONS first, and if that fails the real request is never sent.

So I open dev tools, filter on the API host and look at the OPTIONS request. Nine times out of ten it's one of four things: there's no policy for that origin, often because of a trailing slash or http versus https; UseCors is 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 tried AllowAnyOrigin with AllowCredentials, 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."


Simple vs preflighted requests

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

Diagnosis table

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

Production example

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.

🔍 What the interviewer is checking

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

  • Starts from the preflight in browser dev tools
  • Knows what makes a request non-simple (Authorization header, JSON body)
  • Places UseCors correctly and explains why
  • States clearly that CORS doesn't protect the API from non-browser clients

Red flags

  • Fixes it by allowing any origin with credentials
  • Thinks CORS blocks requests from reaching the server
  • Can't explain why Postman works

📚 Learn in depth

1. Same-origin policy first

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.

2. The preflight flow

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.

3. Credentials and the wildcard rule

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.

4. How ASP.NET Core applies CORS

  • AddCors registers named policies; UseCors() adds CorsMiddleware.
  • With endpoint routing, 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.
  • For preflights the middleware short-circuits with 204 and the CORS headers; for actual requests it adds headers to the response.
  • It adds Vary: Origin so caches don't serve one origin's response to another.
  • Responses produced by middleware before UseCors (for example a gateway or an early exception) won't have CORS headers.

5. What CORS does not do

  • It doesn't stop the request reaching the server: simple cross-origin POSTs are sent and executed; the browser only hides the response. That's why CSRF protection is still needed for cookie-authenticated endpoints.
  • It doesn't stop non-browser clients at all.
  • It doesn't authenticate anything: Origin is trivially forged outside a browser.

6. Avoiding CORS entirely

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.

Try it yourself

  1. Build a tiny SPA page on one port and an API on another; trigger a preflight by adding an Authorization header and watch it in dev tools.
  2. Move UseCors after UseAuthorization and observe the preflight fail with 401.
  3. Throw an exception in an endpoint and note the browser reports a CORS error; then add CORS headers to the error path and compare.
  4. Try AllowAnyOrigin().AllowCredentials() and read the startup exception.
  5. 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.

💻 Code

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();

⚠ Common mistakes

  • Mistake: Testing in Postman and concluding the API is fine. Why it is wrong: Postman doesn't apply CORS. Instead: reproduce in the browser and inspect the preflight in the Network tab.
  • Mistake: Putting UseCors after UseAuthorization. Why it is wrong: preflights have no credentials and get 401. Instead: call UseCors after UseRouting and before authentication.
  • Mistake: Using 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.
  • Mistake: Configuring origins with a trailing slash or the wrong scheme. Why it is wrong: origin matching is exact. Instead: use https://host[:port] with no path.
  • Mistake: Hard-coding 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.
  • Mistake: Chasing a 'CORS error' that is really a 500. Why it is wrong: the error response lacked CORS headers, so the browser hid it. Instead: check server logs and Application Insights for the real failure.
  • Mistake: Configuring CORS in both the gateway (APIM, Front Door rules, nginx) and the app. Why it is wrong: duplicate or conflicting Access-Control-Allow-Origin headers make browsers reject the response. Instead: own CORS in exactly one layer.
  • Mistake: Believing CORS restricts who can call the API. Why it is wrong: it only governs browser script reading responses. Instead: rely on authentication, authorisation and rate limiting.
  • Mistake: Adding CORS to an API whose only client is a same-origin SPA. Why it is wrong: it widens the attack surface for nothing. Instead: serve both from one origin and skip CORS.

🏛 Senior insight: trade-offs

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.

🔗 Follow-ups the interviewer may ask

  1. When: Candidate mentions the OPTIONS preflight Why: Checks wider knowledge of OPTIONS and HEAD and what ASP.NET Core maps automatically
    How to answer

    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.

  2. When: Candidate suggests a BFF or same-origin deployment to avoid CORS Why: Checks they understand token storage and the BFF pattern for SPAs
    How to answer

    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.

    • Rotation: every refresh returns a new refresh token and invalidates the old one. Reuse detection: if an old one is used again, someone has a copy, so the server revokes the whole token family.
    • Lifetimes: access tokens 5–15 minutes; refresh tokens bounded by an idle timeout and an absolute session limit.
    • Storage: in a SPA, anything JavaScript can read, XSS can steal. The BFF pattern keeps tokens on the server and gives the browser only an 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.

🛠 Real-world problems: how you handle them

CORS errors on one endpoint that were really gateway timeouts
Situation
A React SPA on [app domain] calls an ASP.NET Core API on [api domain] through [Azure API Management / Front Door]. Users report a report-export screen fails with 'blocked by CORS policy' while every other screen works. [Number] users affected daily.
Signals
Browser console CORS error on POST /reports/export only; Postman works; no 4xx in API logs for that path; Application Insights shows long-running requests on the endpoint; gateway logs show 504s.
Investigation
Reproduced in Chrome dev tools: preflight OPTIONS returned 204 with correct headers, but the real POST returned 504 from the gateway with no Access-Control-Allow-Origin. Correlated the request id in Application Insights: the export ran 45 s against a [30 s] gateway timeout. Confirmed with curl that the gateway's error response lacks CORS headers.
Resolution
Immediate: raised the gateway timeout for that route and added CORS headers to gateway error responses so real errors surface in the browser. Long term: moved the export to an async job (202 Accepted plus a status endpoint) so no request runs longer than [5 s].
Prevention
Integration test asserting CORS headers on error responses; Application Insights alert on requests over 20 s; a team note that a CORS error on a single endpoint means 'check the real status code first'.

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.

↩ Usually asked after

More in Web Security

Last updated 23 Nov 2026.

🌐 Sangam's Webring

⏪ Previous 🏠 Main Next ⏩
💬 Chat with me