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

📚 Interview question

Explain CORS from the browser's point of view. What is the same-origin policy protecting, what makes a request "simple" versus preflighted, what happens during an OPTIONS preflight, how do credentials and exposed headers change the rules, and why is it the server's response that decides whether the browser lets your JavaScript read the result?

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.

Intermediate Theory Intermediate aspnet-core browser-security cors frontend preflight same-origin-policy

🎯 Key points

  • Origin = scheme + host + port; https://app.x.com.au and https://api.x.com.au are different origins
  • Same-origin policy stops scripts reading cross-origin responses; it does not stop the request being sent
  • Simple request: GET/HEAD/POST, safelisted headers, Content-Type application/x-www-form-urlencoded, multipart/form-data or text/plain; no preflight
  • JSON POST, PUT/DELETE, or an Authorization header trigger an OPTIONS preflight
  • Preflight asks with Origin, Access-Control-Request-Method/-Headers; server answers Allow-Origin/-Methods/-Headers/-Max-Age
  • The actual response is checked again: without matching Allow-Origin (and Allow-Credentials) JS still can't read it
  • Credentials (cookies) need credentials:'include' plus Allow-Credentials: true and an explicit origin, never *; Expose-Headers for non-safelisted response headers
  • CORS relaxes browser protection; it is not API authorisation (curl ignores it), and CSRF is a separate defence

⏱ 30-second answer

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.

🗣 Full answer (senior)

How I would answer this in an interview

"The origin is the triple of scheme, host and port. The browser's same-origin policy says a script from https://app.example.com.au can send requests anywhere, because the web has always allowed forms and images to do that, but it can't read a response from https://api.example.com.au unless 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-Type of application/x-www-form-urlencoded, multipart/form-data or text/plain: things an HTML form could already send. The browser sends it with an Origin header and, when the response comes back, checks Access-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 with Access-Control-Request-Method and Access-Control-Request-Headers. Only if the response allows that origin, method and those headers does the browser send the real request. Access-Control-Max-Age lets 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 return Access-Control-Allow-Credentials: true, and the allowed origin must be echoed exactly; * is rejected. In ASP.NET Core that's why AllowAnyOrigin() with AllowCredentials() 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."


Simple vs preflighted

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

The headers

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

Production example

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.

🔍 What the interviewer is checking

Checks that the candidate understands what the browser enforces and why, rather than copying CORS settings until the error goes away.

Green flags

  • Defines origin precisely and states SOP blocks reading, not sending
  • Knows what triggers a preflight (JSON, Authorization, PUT/DELETE)
  • Explains credentials rules and why * fails
  • Says CORS is not API security and suggests same-origin hosting

Red flags

  • Thinks CORS is enforced by the server or protects the API
  • "Fixes" it with AllowAnyOrigin or by reflecting Origin
  • Doesn't know what OPTIONS is for

📚 Learn in depth

1. What the policy protects

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.

2. The algorithm for a non-simple request

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.

3. How ASP.NET Core implements it

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.

4. Things people miss

  • Opaque responses: mode: 'no-cors' doesn't bypass CORS; it gives you an unreadable response.
  • Errors without headers: if an exception handler or proxy returns 500 without CORS headers, the browser reports a CORS error and hides the real 500.
  • Redirects: a preflight that gets a 30x fails; HTTPS redirects on the API break cross-origin calls.
  • Private Network Access: Chromium adds extra preflight checks when a public site calls a private/localhost address.

5. Avoiding CORS altogether

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.

Try it yourself

  1. Run an API on localhost:5001 and a static page on localhost:5173; call it with fetch and read the console error.
  2. Add AddCors with WithOrigins("http://localhost:5173") and watch the OPTIONS request in the Network panel.
  3. Add a custom X-Total-Count response header and try to read it from JS before and after WithExposedHeaders.
  4. Set SetPreflightMaxAge and confirm repeat calls no longer preflight (disable cache must be off).
  5. Use curl -X POST against the same endpoint to prove CORS doesn't stop non-browser clients.

💻 Code

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

⚠ Common mistakes

  • Mistake: Thinking CORS protects the API from unauthorised callers. Why it is wrong: Only browsers enforce it; curl and servers ignore it. Instead: Use authentication and authorisation; treat CORS as a browser-side relaxation.
  • Mistake: Combining 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.
  • Mistake: Reflecting any 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.
  • Mistake: Placing 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.
  • Mistake: Debugging the CORS error when the real problem is a 500. Why it is wrong: Error responses without CORS headers surface as CORS failures. Instead: Check the server log and the response status in the Network panel.
  • Mistake: Assuming a passed preflight means JS can read the response. Why it is wrong: The browser checks the actual response's CORS headers again. Instead: Make sure the real response (including errors) carries the headers.
  • Mistake: Expecting to read Location or custom headers. Why it is wrong: Only safelisted headers are exposed. Instead: WithExposedHeaders.
  • Mistake: Using 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.

🏛 Senior insight: trade-offs

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.

🔗 Follow-ups the interviewer may ask

  1. When: Candidate mentions a request working in Postman but failing in the browser Why: Checks they can diagnose a real CORS failure in ASP.NET Core
    How to 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.

  2. When: Candidate mentions the OPTIONS preflight Why: Checks they know how ASP.NET Core handles OPTIONS and HEAD
    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.

  3. When: Candidate says the request is still sent even when CORS blocks reading it Why: Checks they know CSRF is the separate problem and how antiforgery solves it
    How to answer

    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.

↩ Usually asked after

More in Web Basics

Last updated 23 Nov 2026.

🌐 Sangam's Webring

⏪ Previous 🏠 Main Next ⏩
💬 Chat with me