الانتقال إلى المحتوى
الأمان (Security)Secure Coding· 7 دقائق للقراءة

CORS Is Not a Security Wall: What It Protects and What It Doesn't

CORS tells browsers which other sites may read your responses. Your server still answers everyone, so access control has to live in the API itself.

ReadIn

مقال كل يوم يفرق معاك

21 نوفمبر 2026
  • كاتب موثّق
محتويات المقال

A partner review turns up a surprise: the reviewer downloads the internal price list with one curl command. The endpoint has no login, because the team considered it protected: the CORS policy only allows 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

The belief: CORS is a server-side firewall for origins. List the allowed origins, and requests from everyone else are rejected, so the API only answers your own front end.

The evidence looks convincing. Call the API from another site and the console says the request was blocked. The policy sits in 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

Microsoft's CORS docs say it directly: "It's up to the client (browser) to enforce CORS. The server executes the request and returns the response, it's the client that returns an error and blocks the response." We checked with a small ASP.NET Core 10 app whose policy allows only https://shop.example, called four ways:

text
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                  blocked

The server log shows the handler ran and returned 200 all four times. Only the browser refused to hand the body to the page, with TypeError: 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

The is the real browser rule, and MDN describes its shape: "Cross-origin writes are typically allowed. Examples are links, redirects, and form submissions." while "Cross-origin reads are typically disallowed". is the opt-in that lets you make exceptions for reads. That's why Microsoft lists it as something that "Is not a security feature, CORS relaxes security. An API is not safer by allowing CORS."

Some requests are checked first. For methods and headers a plain form can't produce, the browser sends a 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

Inside a browser, the Fetch Standard makes 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

The Fetch Standard explains why CORS had to be opt-in: "to prevent leaking data from responses behind a firewall (intranets). Additionally, for requests including credentials it needs to be opt-in to prevent leaking potentially-sensitive data." So the real risk is the opposite of the myth: a policy that's too open. Reflect any origin and allow credentials, and any site a signed-in user visits can read their data with their cookies. The standard calls that combination "rather unsafe", and the OWASP Top 10 2025 lists "CORS misconfiguration allows API access from unauthorized or untrusted origins" under A01 Broken Access Control.

Put access control in the API

C# Program.cs
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();

The fixed version splits the two jobs. 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."

QuestionDoes CORS answer it?What does
May a script on another site read this response?Yes, in browsersCORS headers
May curl, Postman or a server call this endpoint?NoAuthentication and authorization
Does the handler run for a disallowed origin?Yes, it still runsAuthorization inside the API
Can another site make a user's browser send a form POST?NoCSRF tokens and SameSite cookies
May this caller see this particular record?NoObject-level authorization checks

How to apply it in your project

  1. Assume every client can call every endpointPut authentication and authorization on each endpoint that isn't meant to be public. CORS doesn't change that list.
  2. Make the policy an exact listName each allowed origin. No reflection, no * with credentials, and wildcard subdomains only if you trust every subdomain.
  3. Allow credentials only when the front end needs themIf your front end calls the API with a bearer token, it doesn't need AllowCredentials, and leaving it off removes the cookie risk.
  4. Load origins from configurationKeep a separate list per environment, so localhost never ships to production and nobody widens the policy to fix a dev error.
  5. Check both paths in testsCall 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 Origin header 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.

📚 المصادر

  1. Cross-Origin Resource Sharing (CORS) — MDN Web Docs
  2. Same-origin policy — MDN Web Docs
  3. Fetch Standard, §3.3 CORS protocol — WHATWG
  4. Enable Cross-Origin Requests (CORS) in ASP.NET Core — Microsoft Learn
  5. A01:2025 Broken Access Control — OWASP Top 10:2025

التعليقات (0)