How the browser enforces the same-origin policy and CORS: what an origin is, simple vs preflighted requests, the OPTIONS preflight and its headers, credentialed requests, Access-Control-Expose-Headers, preflight caching, and how ASP.NET Core's CORS middleware answers.
The same-origin policy stops JavaScript on one origin (scheme + host + port) from reading responses from another, so a malicious page can't read your bank's API with your cookies. CORS is the server's way to opt in. For a simple request (GET, HEAD or POST with only safelisted headers and a form or text/plain body) the browser sends it and then checks Access-Control-Allow-Origin before handing the response to your code. Anything else, such as a JSON POST, a PUT or an Authorization header, first gets an OPTIONS preflight asking permission for that method and those headers. Sending cookies needs credentials: 'include' and Access-Control-Allow-Credentials: true with an explicit origin. The key trade-off: the browser enforces it but the server's headers decide, and CORS is not security for your API: non-browser clients ignore it.
"The origin is the triple of scheme, host and port. The browser's same-origin policy says a script from
https://app.example.com.aucan send requests anywhere, because the web has always allowed forms and images to do that, but it can't read a response fromhttps://api.example.com.auunless that server says it's allowed. The threat is a malicious page using your logged-in cookies to read data from a site you trust. CORS is a set of response headers the server uses to relax that rule for specific origins.Browsers split requests into two kinds. A simple request is a GET, HEAD or POST with only CORS-safelisted headers and a
Content-Typeofapplication/x-www-form-urlencoded,multipart/form-dataortext/plain: things an HTML form could already send. The browser sends it with anOriginheader and, when the response comes back, checksAccess-Control-Allow-Origin. If it doesn't match, the server still did the work, but the script gets a network error. Everything else, which in practice means every JSON API call and anything with a bearer token, gets a preflight: an OPTIONS request withAccess-Control-Request-MethodandAccess-Control-Request-Headers. Only if the response allows that origin, method and those headers does the browser send the real request.Access-Control-Max-Agelets the browser cache that approval, though browsers cap it (Chromium at two hours).Credentials add rules: the client has to opt in with
credentials: 'include', the server must returnAccess-Control-Allow-Credentials: true, and the allowed origin must be echoed exactly;*is rejected. In ASP.NET Core that's whyAllowAnyOrigin()withAllowCredentials()throws. The mistake I see is treating CORS as protection for the API. It protects users' browsers from other sites; anyone with curl can call your API, so authentication and authorisation still do the real work."
| Request | Preflight? | Why |
|---|---|---|
GET /api/products no custom headers |
No | Simple |
POST form-encoded |
No | A form could do it |
POST with Content-Type: application/json |
Yes | Not a safelisted content type |
Any request with Authorization: Bearer ... |
Yes | Non-safelisted header |
PUT, PATCH, DELETE |
Yes | Non-simple method |
| Same-origin anything | No CORS at all | Same origin |
| Direction | Header | Purpose |
|---|---|---|
| Request | Origin |
Who is asking |
| Preflight request | Access-Control-Request-Method / -Headers |
What the real request will use |
| Response | Access-Control-Allow-Origin |
Exact origin (or * without credentials) |
| Response | Access-Control-Allow-Methods / -Headers |
What's permitted |
| Response | Access-Control-Allow-Credentials |
Cookies / auth allowed |
| Response | Access-Control-Expose-Headers |
Extra response headers JS may read (e.g. Location, ETag) |
| Response | Access-Control-Max-Age |
Preflight cache seconds |
| Response | Vary: Origin |
Caches must key on origin |
A SPA on a separate origin made every API call with a bearer token, so each call doubled into preflight plus request: on a 120 ms round trip from Perth to Australia East, pages with 8 calls paid nearly a second extra. Setting SetPreflightMaxAge(TimeSpan.FromHours(1)) removed most preflights; later serving the SPA and API on one origin behind Azure Front Door removed CORS entirely.
Checks that the candidate understands what the browser enforces and why, rather than copying CORS settings until the error goes away.
Green flags
* failsRed flags
evil.example (open in tab) --fetch--> bank.example/api/balance (browser attaches bank cookies)
|
v
response arrives in the browser
|
same-origin policy: evil.example may NOT read it
Note what isn't protected: the request was sent and any side effects happened. That's why CSRF is a separate problem, solved with antiforgery tokens and SameSite cookies, not CORS.
fetch('https://api.x.com.au/orders', { method:'POST', headers:{'Content-Type':'application/json'}, credentials:'include' })
1. Browser: OPTIONS /orders
Origin: https://app.x.com.au
Access-Control-Request-Method: POST
Access-Control-Request-Headers: content-type
2. Server (UseCors): 204
Access-Control-Allow-Origin: https://app.x.com.au
Access-Control-Allow-Methods: POST
Access-Control-Allow-Headers: content-type
Access-Control-Allow-Credentials: true
Access-Control-Max-Age: 3600
3. Browser checks; if OK sends the real POST with cookies
4. Server responds; must include Allow-Origin + Allow-Credentials again
5. Browser checks again, then resolves fetch()
If any check fails, fetch rejects with a TypeError and the console shows the CORS reason; your JavaScript can't see the status code by design, so it can't probe other sites.
AddCors registers named policies. UseCors middleware runs early (after routing, before authentication and authorisation when endpoint-specific policies are used). For a preflight it short-circuits with 204 and the headers. For the actual request it adds headers to the response. Endpoint metadata (RequireCors("spa") or [EnableCors]) can choose a policy per endpoint. Because preflights carry no credentials, the CORS middleware must answer them before authorisation would reject them with 401.
mode: 'no-cors' doesn't bypass CORS; it gives you an unreadable response.Serve the SPA and API from the same origin (ASP.NET Core serving the SPA's static files, a reverse proxy or Front Door routing /api, or the Vite dev proxy locally). No CORS, no preflights, and cookies just work.
localhost:5001 and a static page on localhost:5173; call it with fetch and read the console error.AddCors with WithOrigins("http://localhost:5173") and watch the OPTIONS request in the Network panel.X-Total-Count response header and try to read it from JS before and after WithExposedHeaders.SetPreflightMaxAge and confirm repeat calls no longer preflight (disable cache must be off).curl -X POST against the same endpoint to prove CORS doesn't stop non-browser clients.An ASP.NET Core API that allows one SPA origin with cookies, and the browser call.
// Program.cs (.NET 10)
var builder = WebApplication.CreateBuilder(args);
string[] spaOrigins = builder.Configuration.GetSection("Cors:Origins").Get<string[]>() ?? [];
builder.Services.AddCors(o => o.AddPolicy("spa", p => p
.WithOrigins(spaOrigins) // exact origins: required with credentials
.AllowCredentials() // cookies / auth headers
.WithMethods("GET", "POST", "PUT", "DELETE")
.WithHeaders("Content-Type", "X-XSRF-TOKEN")
.WithExposedHeaders("Location", "ETag") // let JS read these
.SetPreflightMaxAge(TimeSpan.FromHours(1))));
builder.Services.AddAuthentication().AddCookie();
builder.Services.AddAuthorization();
var app = builder.Build();
app.UseRouting();
app.UseCors("spa"); // before auth so preflights aren't rejected with 401
app.UseAuthentication();
app.UseAuthorization();
app.MapPost("/api/orders", (CreateOrder o) => TypedResults.Created($"/api/orders/{Guid.NewGuid()}", o))
.RequireAuthorization();
app.Run();
public sealed record CreateOrder(string Sku, int Quantity);
// appsettings.Production.json
{ "Cors": { "Origins": [ "https://app.example.com.au" ] } }
// Browser code on https://app.example.com.au
const res = await fetch('https://api.example.com.au/api/orders', {
method: 'POST',
credentials: 'include', // send cookies cross-origin
headers: { 'Content-Type': 'application/json' }, // triggers a preflight
body: JSON.stringify({ sku: 'CABLE-2M', quantity: 2 }),
});
console.log(res.headers.get('Location')); // readable only because it's exposed
AllowAnyOrigin() with AllowCredentials(). Why it is wrong: AllowAnyOrigin() alone is fine for public, credential-free data, but the CORS spec forbids Access-Control-Allow-Origin: * on credentialed requests, and ASP.NET Core refuses the combination with an InvalidOperationException when the policy is built. Instead: With credentials, list exact origins from configuration.Origin header back (or SetIsOriginAllowed(_ => true)) with credentials. Why it is wrong: Every website can then read your users' data. Instead: Allow-list origins; never echo blindly.UseCors after UseAuthorization. Why it is wrong: Preflights carry no credentials and get 401, so the browser blocks the call. Instead: UseCors before auth middleware.Location or custom headers. Why it is wrong: Only safelisted headers are exposed. Instead: WithExposedHeaders.mode: 'no-cors' to "fix" it. Why it is wrong: The response becomes opaque and unreadable. Instead: Fix the server policy or use the same origin.The best CORS configuration is often none: put the SPA and API on the same origin behind a reverse proxy, Azure Front Door or by serving the SPA from ASP.NET Core, and preflights, credential rules and cookie headaches disappear. When cross-origin is unavoidable (a public API used by partner sites, or separate subdomains owned by different teams), keep origins in configuration per environment, cache preflights, and include CORS headers on error responses.
| Option | When it fits | Cost | When not to |
|---|---|---|---|
| Same origin (proxy/Front Door path routing) | Your own SPA + API | Routing config | Truly third-party callers |
| CORS with explicit origins + credentials | Separate subdomains with cookies | Preflights, careful config | Public APIs |
CORS * without credentials |
Public, read-only, token-less data | None | Anything user-specific |
Measure preflight overhead in the Network panel or with Application Insights dependency timings: count OPTIONS requests per page load and their latency from regional users.
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.
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.
CSRF makes a victim's browser send a state-changing request to your site from another site; it works because the browser attaches cookies automatically. If you authenticate with cookies, you're exposed; if callers send a bearer token in the Authorization header, a cross-site page can't add it, so classic CSRF doesn't apply.
ASP.NET Core's antiforgery uses a synchroniser token: a cookie token plus a token in the form or a header, validated together. MVC forms get it from the form tag helper with [ValidateAntiForgeryToken] or the global auto-validate filter; Razor Pages validate POSTs by default; Minimal APIs need AddAntiforgery/UseAntiforgery and validate form-bound endpoints. SameSite=Lax (the default for ASP.NET Core auth cookies) blocks most cross-site POSTs, but not attacks from a sibling subdomain or GETs that change state, so keep tokens.
Last updated 23 Nov 2026.