跳到主要内容

CORS

🧠 Interview-Friendly Mental Model


What is CORS? (Core Idea)

"Browser security rule, not a server feature"

CORS (Cross-Origin Resource Sharing) controls whether a browser is allowed to call your API from another origin.

  • Origin = scheme + domain + port
  • localhost:4200localhost:5001

Interview line

"CORS is a browser security mechanism that controls cross-origin HTTP requests."


Why CORS Exists

"Protect users, not servers"

Without CORS:

  • Any website could call your API using a user's browser
  • Leads to data leaks & CSRF-like attacks

"CORS prevents malicious websites from accessing APIs using a user's browser."


When You Need CORS

Frontend ≠ Backend origin

You need CORS only if:

  • Frontend and backend are on different origins
  • Example:
    • Angular → http://localhost:4200
    • API → https://localhost:5001

❌ No CORS needed for:

  • Same origin
  • Server-to-server calls

CORS Is Enforced By…

"Browser blocks it"

  • ✅ Browser enforces CORS
  • ❌ Postman / curl ignore CORS
  • ❌ Server is NOT blocked

"CORS is enforced by browsers, not by servers."


Basic CORS Setup (Must Memorize)

Add → Policy → Use

1. Register policy

builder.Services.AddCors((options) => {
options.AddPolicy("AllowAngular", (b) =>
b.WithOrigins("http://localhost:4200").AllowAnyMethod().AllowAnyHeader(),
);
});

2. Apply middleware

app.UseCors("AllowAngular");

⚠️ Must be before MapControllers()

"CORS is configured using AddCors and applied with UseCors."


Important Middleware Order (Very Testable)

CORS before endpoints

Correct order:

UseRouting
UseCors
UseAuthorization
MapControllers

❌ Wrong placement = CORS not applied

"UseCors must be placed before MapControllers."


What a CORS Policy Controls

Origins, Methods, Headers

RuleControls
WithOriginsAllowed domains
AllowAnyMethod / WithMethodsGET, POST, etc
AllowAnyHeader / WithHeadersCustom headers
AllowCredentialsCookies / auth

Preflight Requests (High-value topic)

OPTIONS first

Browser sends OPTIONS request when:

  • Method ≠ GET/POST
  • Custom headers
  • Authorization header
  • Credentials

API must respond with:

Access-Control-Allow-Origin
Access-Control-Allow-Methods
Access-Control-Allow-Headers

"Browsers send preflight OPTIONS requests for complex CORS calls."


9️⃣ Common CORS Mistakes (Interview Gold)

❌ AllowAnyOrigin + AllowCredentials

  • Not allowed
  • Security risk

❌ Forgetting HTTPS mismatch

  • http://localhosthttps://localhost

❌ Testing with Postman

  • Postman ignores CORS

"AllowAnyOrigin cannot be combined with AllowCredentials."


Development vs Production

Strict in prod

  • Dev: allow localhost
  • Prod: allow exact domains only
  • Never:
AllowAnyOrigin();
AllowAnyHeader();
AllowAnyMethod();

in production


"CORS is a browser security mechanism that controls whether a web application from one origin can access resources from another origin. In ASP.NET Core, CORS is configured using AddCors to define policies and UseCors to apply them in the middleware pipeline. It's required when frontend and backend run on different origins, like Angular on localhost:4200 calling an API on localhost:5001. CORS is enforced by browsers, not by the server itself."


🧠 Ultra-Short Cheat Sheet

CORS = browser security
Origin = scheme + host + port
Browser blocks, server allows
Postman ignores CORS
AddCors + UseCors
UseCors before MapControllers
OPTIONS = preflight
Never AllowAnyOrigin + Credentials