
CORS Is Not a Security Wall: What It Protects and What It Doesn't
- كاتب موثّق
محتويات المقال
https://shop.example. To prove it, a developer calls the same endpoint from a page on another domain, and the browser console prints "blocked by CORS policy". Both results are real. Neither one means what the team thought.
The common misconception
Program.cs next to authentication, behind a method named WithOrigins, and many tutorials describe it as restricting who can access your API. CORS errors are also a daily annoyance during development, which makes CORS feel like a strict gatekeeper. But that block happens in the browser, after your server has already answered.
What actually happens
The server answers, the browser decides who reads
https://shop.example, called four ways:
Client Status CORS allow header Bodycurl, no Origin 200 none readcurl, Origin: https://evil.example 200 none readcurl, Origin: https://shop.example 200 https://shop.example readChromium 156, page on other origin 200 none blockedTypeError: Failed to fetch and the console message "No 'Access-Control-Allow-Origin' header is present on the requested resource."
CORS loosens the same-origin policy, it doesn't add a wall
OPTIONS request and waits for approval. But a request that looks like a form submission goes out without asking. MDN notes the server "still must opt-in using Access-Control-Allow-Origin to share the response with the script", which controls reading, not whether the request arrives.
Origin is a browser claim, not a client identity
Origin a forbidden header "so the user agent remains in full control" over it, which is why it helps against CSRF. Outside a browser it's an ordinary header: our curl claimed to be https://shop.example and got the allow header back. CORS can't tell your front end from a script, and it was never meant to. The Fetch Standard says that sending Access-Control-Allow-Origin: * on a public resource shares it with browser APIs "much like it is already shared with curl and wget."
What CORS does protect: data reached through your users
Put access control in the API
var builder = WebApplication.CreateBuilder(args);builder.Services.AddAuthentication().AddCookie();builder.Services.AddAuthorization();builder.Services.AddSingleton<PriceList>().AddSingleton<OrderStore>();builder.Services.AddCors(o => o.AddDefaultPolicy(p => p .SetIsOriginAllowed(_ => true) // added to silence CORS errors .AllowAnyHeader().AllowAnyMethod().AllowCredentials()));var app = builder.Build();app.UseCors();app.UseAuthentication();app.UseAuthorization();// "Only our front end can call this: CORS is configured"app.MapGet("/api/prices/internal", (PriceList prices) => prices.Internal());// Any site can now read this with the visitor's cookieapp.MapGet("/api/me/orders", (ClaimsPrincipal user, OrderStore orders) => orders.ForUser(user.Identity!.Name!)).RequireAuthorization();app.Run();var builder = WebApplication.CreateBuilder(args);builder.Services.AddAuthentication().AddCookie();builder.Services.AddAuthorizationBuilder() .AddPolicy("pricing", p => p.RequireRole("PricingStaff"));builder.Services.AddSingleton<PriceList>().AddSingleton<OrderStore>();builder.Services.AddCors(o => o.AddDefaultPolicy(p => p .WithOrigins("https://shop.example") // exact list, never reflected .WithMethods("GET", "POST").WithHeaders("Content-Type") .AllowCredentials()));var app = builder.Build();app.UseCors();app.UseAuthentication();app.UseAuthorization();// The real gate: it applies to curl and browsers alikeapp.MapGet("/api/prices/internal", (PriceList prices) => prices.Internal()) .RequireAuthorization("pricing");app.MapGet("/api/me/orders", (ClaimsPrincipal user, OrderStore orders) => orders.ForUser(user.Identity!.Name!)).RequireAuthorization();app.Run();RequireAuthorization decides who may call an endpoint, and it runs for every client. CORS only decides which web pages may read the answer in a browser, so it lists the one origin that needs it. Microsoft names the trap in the wrong version: "Bypassing the built-in checks by using SetIsOriginAllowed(_ => true) together with AllowCredentials is also an insecure configuration."
How to apply it in your project
Assume every client can call every endpoint Put authentication and authorization on each endpoint that isn't meant to be public. CORS doesn't change that list. Make the policy an exact list Name each allowed origin. No reflection, no *with credentials, and wildcard subdomains only if you trust every subdomain.Allow credentials only when the front end needs them If your front end calls the API with a bearer token, it doesn't need AllowCredentials, and leaving it off removes the cookie risk.Load origins from configuration Keep a separate list per environment, so localhostnever ships to production and nobody widens the policy to fix a dev error.Check both paths in tests Call each protected endpoint with curl and no credentials, and from a page on a non-allowed origin. Both should fail, for different reasons.
Key takeaways
CORS controls which web pages may read your responses in a browser, not who may call your API. The server runs the request either way; the browser only withholds the response from the page. Non-browser clients ignore CORS and can send any Originheader they like.Real access control is authentication and authorization, enforced on the server for every request. An open CORS policy with credentials is the dangerous case; keep the allowed origins exact.
التعليقات (0)