Software Engineer Encyclopedia
0%
Domain 05 · Security & Software Testing · Topic 5.4

CORS: Same-Origin Policy وPreflight وCredentials في ASP.NET Core

CORS — Cross-Origin Resource Sharing

شرح CORS عمليًا: origins، same-origin policy، simple/preflight requests، headers، credentials، middleware order، والفرق بين CORS وAuthentication.

  • Intermediate
  • ~13 min read
  • 12 sections
  • 10 code examples
  • 2 diagrams
  • 6 questions
  • Priority L2 · Important
  • ASP.NET Core 10 · HTTP

المتطلبات قبل ما تبدأ

Web API شغال بقاعدة بيانات (المجالات 03 و04).

مستوى التعمق المطلوب

STRONG BASICSمهم | CORS is not an authentication or authorization mechanism.

01

Same-Origin Policy و Origin

Why browsers restrict cross-origin reads
Basics

Browser Same-Origin Policy (SOP) تقيد JavaScript في صفحة من origin معين من قراءة موارد origin آخر إلا وفق قواعد محددة. الـ Origin يتكون من scheme + host + port. لذلك https://app.example.com و https://api.example.com مختلفان، وكذلك http://localhost:5173 و http://localhost:5000.

CORS (Cross-Origin Resource Sharing) آلية HTTP تسمح للسيرفر يعلن للمتصفح أي origins مسموح لها بقراءة response. هي browser-enforced policy، وليست authentication ولا authorization. أدوات مثل curl/Postman أو server-to-server calls لا تطبق browser SOP بالطريقة نفسها؛ نجاح request من Postman لا يثبت أن CORS مضبوط في المتصفح.

02

CORS Headers الأساسية

Server response controls
Basics
  • Access-Control-Allow-Origin: origin المسموح له بقراءة response.
  • Access-Control-Allow-Methods: methods المسموحة في preflight response.
  • Access-Control-Allow-Headers: request headers المسموح بها.
  • Access-Control-Allow-Credentials: هل يسمح browser بإرسال credentials cross-origin.
  • Access-Control-Expose-Headers: response headers التي يستطيع JavaScript قراءتها.
  • Access-Control-Max-Age: مدة cache لنتيجة preflight وفق browser limits.
  • Origin: request header يوضح origin الذي بدأ الطلب.

السيرفر لا يرسل «CORS token» للعميل. المتصفح يقارن origin والـ headers بالسياسة، وقد يمنع JavaScript من قراءة response حتى لو السيرفر نفذ request وأنتج side effect.

03

Simple Requests و Preflight Requests

OPTIONS before the actual request
Deep dive

بعض requests يمكن إرسالها من غير preflight وفق شروط method/headers/content type. requests الأخرى يسبقها browser بطلب OPTIONS يسأل هل method والـ headers مسموح بها. ده اسمه preflight. مثال: PUT أو custom header مثل Authorization غالبًا يسبب preflight.

HTTPPreflight request
OPTIONS /api/orders/42 HTTP/1.1
Origin: https://app.example.com
Access-Control-Request-Method: PUT
Access-Control-Request-Headers: authorization, content-type
HTTPPreflight response
HTTP/1.1 204 No Content
Access-Control-Allow-Origin: https://app.example.com
Access-Control-Allow-Methods: GET, POST, PUT
Access-Control-Allow-Headers: authorization, content-type
Access-Control-Max-Age: 600

لو preflight فشل، browser لا يرسل actual request في حالات preflighted. لكن لا تعتمد على preflight كحاجز أمني؛ request قد تأتي من non-browser client أو تتغير الظروف. authorization الحقيقي لازم يتم في API نفسها.

Preflight بالتفصيل: إمتى ولماذا؟

Browser يقرر preflight بناءً على request method/headers/content type وفق Fetch/CORS rules، وليس على أن endpoint «حساسة» أو «غير حساسة». وجود Authorization header أو custom header غالبًا يسبب OPTIONS. الـ browser قد يخزن preflight result باستخدام Access-Control-Max-Age، لكن هناك browser-specific caps؛ لا تفترض أن كل request ستسبقها OPTIONS أو أن cache ستظل طوال القيمة التي كتبتها.

Preflight request لا تحتوي عادة credentials بالطريقة نفسها التي تحملها actual request؛ لذلك CORS middleware يجب أن يسمح بـ OPTIONS ويرد بال headers المطلوبة. لو authentication middleware يرفض OPTIONS قبل CORS، سيظهر browser CORS error حتى لو actual endpoint محمية بشكل صحيح. لا تجعل OPTIONS bypass يسمح بتنفيذ business operation؛ هي negotiation request فقط.

HTTPActual credentialed request after preflight
PUT /api/profile HTTP/1.1
Origin: https://app.example.com
Cookie: __Host-Session=...
Content-Type: application/json

{"displayName":"New Name"}

بعد preflight الناجح، browser يرسل actual request. لو server نفذ update ثم response لم تحمل Allow-Origin الصحيح، JavaScript قد لا تستطيع قراءة response رغم أن side effect حصل. لذلك CORS errors لا تعني دائمًا أن server لم ينفذ request؛ افحص server logs و network trace.

Preflight Deep Dive: OPTIONS و Cache و Credentials

Preflight يحدث عندما request لا تكون simple وفق CORS criteria؛ browser يرسل OPTIONS مع Origin و Access-Control-Request-Method و Access-Control-Request-Headers. server يقرر هل يسمح بال origin/method/headers، وقد يحدد Access-Control-Max-Age لتخزين نتيجة preflight مؤقتًا. هذا cache لا يخزن response الفعلية ولا يحمي من request forgery خارج browser.

مع credentials، لا يمكن استخدام Access-Control-Allow-Origin: *; يجب origin محددة، و Access-Control-Allow-Credentials: true، مع ضبط cookie SameSite/Secure و credentials mode. CORS لا يمنع curl/Postman/server-to-server requests؛ هو browser enforcement لقراءة response cross-origin. لا تستخدمه كبديل auth أو CSRF defense.

Preflight Request من المتصفح خطوة بخطوة

Browser Check origin Preflight OPTIONS if needed Server Return allow headers Browser Send / expose response
Browser CORS flow

المتصفح يقرر هل request cross-origin، وهل هي CORS-safelisted/simple request. لو method أو headers أو content type خارج الحدود المسموحة، يرسل preflight OPTIONS يحتوي Origin و Access-Control-Request-Method و Access-Control-Request-Headers. السيرفر يرد بسياسات السماح، والمتصفح بعدها يرسل actual request إذا نجح الفحص. الـ preflight لا يحمل عادة credentials مثل actual request.

Access-Control-Max-Age يسمح للمتصفح بتخزين نتيجة preflight مدة محدودة، لكن browser قد يضع سقفًا. CORS errors تظهر في console كأنها network failure، لكنها ليست بالضرورة فشل اتصال السيرفر؛ قد يكون response وصل لكن المتصفح منع JavaScript من قراءته.

C#Practical engineering example
builder.Services.AddCors(options => options.AddPolicy("Spa", policy =>
    policy.WithOrigins("https://app.example.com")
          .WithMethods("GET", "POST", "PUT", "DELETE")
          .WithHeaders("Content-Type", "Authorization")
          .AllowCredentials()
          .SetPreflightMaxAge(TimeSpan.FromMinutes(10))));

app.UseRouting();
app.UseCors("Spa");
app.UseAuthentication();
app.UseAuthorization();

مع credentials لا تستخدم wildcard origin *؛ يجب تحديد origins صراحة. لا تعكس أي Origin يرسله العميل بشكل آلي. اختبر من browser حقيقي، لأن Postman و curl لا يطبقان browser same-origin policy ولا يمنعان قراءة response بنفس الطريقة.

04

Credentials و Cookies و Wildcard

Credentialed cross-origin requests
Deep dive

لو browser يرسل cookies أو credentials cross-origin، client request يحتاج credentials mode المناسب، والسيرفر يرسل Access-Control-Allow-Credentials: true مع origin محدد. لا يمكن استخدام wildcard * كـ Allow-Origin مع credentialed requests. استخدم allow-list دقيقة من trusted origins.

لا تعكس أي Origin عشوائيًا في response لمجرد أنه وصل في request؛ ده يحول CORS إلى reflection vulnerability. راجع subdomain trust: السماح بـ *.example.com قد يسمح subdomain takeover أو origin غير موثوق. CORS لا يمنع CSRF؛ cookie auth ما زالت تحتاج CSRF defenses و SameSite policy مناسبة.

CORS مع Cookies و SameSite و CSRF

عند cross-origin fetch، client قد يحتاج credentials: "include"، والـ server يحدد Allow-Credentials=true و Allow-Origin محدد. لكن إرسال cookie يخضع أيضًا لـ cookie attributes مثل SameSite/Secure/Domain/Path وسياسات third-party cookies في browser. CORS policy وحدها لا تضمن أن cookie ستُرسل.

لو frontend و API على subdomains مختلفة لكن same-site حسب schemeful site، سلوك SameSite قد يختلف عن cross-site domains. اختبر browser فعليًا. لا تفتح credentials لأي origin. CORS reflection مع credentials قد تسمح لموقع attacker يقرأ response authenticated باسم الضحية.

حتى مع CORS origin allow-list صحيحة، cookie-authenticated POST/PUT/DELETE تحتاج CSRF defense. SameSite=Lax/Strict يقلل بعض requests لكنه لا يغطي كل application flows، خصوصًا cross-site integrations أو unsafe GET mistakes. استخدم anti-forgery tokens أو origin checks وفق architecture.

05

إعداد CORS في ASP.NET Core وترتيب Middleware

Configure named policies
Practical
C#Program.cs — explicit origin allow-list
var allowedOrigins = builder.Configuration
    .GetSection("Cors:AllowedOrigins").Get<string[]>() ?? [];

builder.Services.AddCors(options =>
{
    options.AddPolicy("Frontend", policy => policy
        .WithOrigins(allowedOrigins)
        .WithMethods("GET", "POST", "PUT", "DELETE")
        .WithHeaders("Content-Type", "Authorization")
        .AllowCredentials());
});

var app = builder.Build();
app.UseRouting();
app.UseCors("Frontend");
app.UseAuthentication();
app.UseAuthorization();
app.MapControllers();

الترتيب مهم في pipeline. في endpoint routing المعتاد ضع UseCors بعد UseRouting وقبل UseAuthorization، وبشكل يضمن تطبيق policy على endpoints المطلوبة. راجع ترتيب static files و authentication حسب نوع التطبيق. Preflight OPTIONS لازم يمر من CORS middleware ولا يتم رفضه مبكرًا من custom auth middleware.

في production لا تترك origins كـ wildcard لمجرد تسهيل التطوير. افصل Development origins عن Production، وخزن allow-list في configuration آمنة. لا تستخدم trailing slash في origin string؛ origin يتكون scheme/host/port فقط.

Dynamic Origin Allow-List من Configuration

لو عندك عدة frontend domains (production/staging/admin)، حمّلها من configuration إلى HashSet normalized. قارن scheme/host/port exact، وارفض null origin إلا لو عندك use case محدد مثل sandboxed documents. لا تستخدم regex واسعًا مثل .*example.com؛ قد يقبل evil-example.com أو subdomain غير موثوق. لو تسمح subdomains، تحقق من suffix boundary و ownership/tenant control.

C#Exact origin validation
var allowed = new HashSet<string>(
    builder.Configuration.GetSection("Cors:AllowedOrigins").Get<string[]>() ?? [],
    StringComparer.OrdinalIgnoreCase);

builder.Services.AddCors(options => options.AddPolicy("ConfiguredOrigins", policy =>
    policy.SetIsOriginAllowed(origin =>
        Uri.TryCreate(origin, UriKind.Absolute, out var uri) &&
        allowed.Contains(uri.GetLeftPart(UriPartial.Authority)))
        .WithMethods("GET", "POST", "PUT", "DELETE")
        .WithHeaders("Content-Type", "Authorization")));

لا تكرر allow-list validation يدويًا إذا WithOrigins تكفي. المثال يوضح dynamic policy فقط. لو credentials مطلوبة أضفها مع origins محددة، وتأكد من Vary: Origin عندما response تختلف حسب origin.

06

CORS مش Authentication ولا Authorization

Browser policy is not access control
Pitfalls

CORS لا يثبت هوية المستخدم، ولا يقرر هل user يملك order، ولا يمنع curl أو backend آخر من إرسال request. هو يحدد هل browser يسمح لصفحة من origin معين بقراءة response. Authentication يحدد من caller؛ Authorization يحدد ما الذي يستطيع فعله. لازم تظل endpoints محمية حتى لو CORS policy تسمح للـ frontend origin.

مثال: السماح لـ https://app.example.com لا يعني أن أي user على الصفحة يستطيع قراءة كل orders. الـ API لازم تتحقق من token/cookie، ثم تتحقق من ownership/permissions لكل order.

CORS ليس Authentication ولا CSRF Protection

CORS سياسة يطبقها المتصفح للتحكم في JavaScript origins التي تستطيع قراءة response. لا تمنع curl أو mobile app أو server-to-server client من استدعاء API. لذلك لا تعتبر origin المسموح هو مستخدم موثوق، ولا تعتمد على CORS لمنع الوصول للبيانات. كل endpoint يحتاج authentication/authorization مستقلين.

CSRF مختلف: المتصفح قد يرسل cookies تلقائيًا إلى موقع آخر حتى لو لم يستطع الموقع قراءة response. لذلك cookie-authenticated state-changing endpoints تحتاج CSRF defense مناسبًا، بينما bearer token الذي لا يرسله المتصفح تلقائيًا له threat profile مختلف (مع بقاء XSS ومخاطر تخزين token).

C#Practical engineering example
// Never use Origin as an authorization identity.
app.MapPost("/api/transfers", TransferFunds)
   .RequireAuthorization("CanTransfer");

// CORS only controls browser access to the response;
// the endpoint still authenticates and authorizes every request.

Misconfiguration شائعة: AllowAnyOrigin() مع AllowCredentials() غير مسموح في ASP.NET Core لأنه غير آمن. استخدم explicit allowlist، وراجع subdomain trust، وبيئات staging، و headers المطلوبة. لا تضف origin واسعًا مثل https://*.example.com عبر regex غير مدروس؛ subdomain takeover قد يحول origin مسموح إلى attacker-controlled.

CORS و Non-Browser Clients

Mobile apps، curl، Postman، server-to-server clients لا تعتمد على browser CORS enforcement. لذلك لا تضع CORS كـ only gate. لو API public، استخدم authentication/API keys حسب client type، rate limits، authorization، TLS، input validation. لو internal API، استخدم service identity/network policy بدل الاعتماد على Origin header؛ أي client يستطيع تزوير Origin خارج browser.

اختبر أن API ترفض missing/invalid credential حتى لو Origin مسموح. واختبر أن browser من origin غير مسموح لا يستطيع قراءة response. دي نتيجتان مختلفتان يجب التحقق منهما.

07

تشخيص CORS في المتصفح

Common misconfigurations
Practical
  • Origin mismatch بسبب port أو scheme أو hostname مختلف.
  • استخدام * مع credentials.
  • نسيان Authorization أو Content-Type في allowed headers.
  • عدم السماح بالـ method المطلوبة في preflight.
  • Middleware order يجعل OPTIONS يتوقف قبل CORS.
  • Redirect على preflight أو proxy يزيل CORS headers.
  • الاعتماد على Postman بدل اختبار browser.
  • إرجاع CORS headers في success دون error responses بسبب middleware/proxy arrangement.

افتح DevTools Network، راجع OPTIONS request والـ response headers، ثم actual request إن أُرسلت. اقرأ console message بدقة. لا تعالج المشكلة بإضافة wildcard أو تعطيل browser security. اختبر localhost ports، production domain، credentials، و custom headers.

CORS مع Reverse Proxy والاختبارات

في production، response headers قد تمر عبر API gateway/CDN/reverse proxy. proxy قد يزيل أو يكرر CORS headers، أو يرد على OPTIONS بنفسه، أو يعمل redirect من HTTP إلى HTTPS. تأكد أن policy موجودة في layer واحدة واضحة، ولا تكرر Allow-Origin من التطبيق والـ proxy بقيم مختلفة. لو عندك CDN cache، أرسل Vary: Origin عند اختلاف response حسب Origin حتى لا تتشارك cache responses بين origins بطريقة خاطئة.

اختبر من browser على origin حقيقي، مع GET و POST و PUT، Authorization header، credentials، preflight cache، allowed/denied origins، و error responses 400/401/403/500. curl مفيد لفحص headers لكنه لا يحاكي browser enforcement بالكامل. في integration tests افحص CORS headers للـ OPTIONS والـ actual response.

BashInspect CORS response headers
curl -i -X OPTIONS https://api.example.com/api/orders \
  -H "Origin: https://app.example.com" \
  -H "Access-Control-Request-Method: POST" \
  -H "Access-Control-Request-Headers: authorization,content-type"

لا تستخدم curl result كاختبار نهائي لسياسة المتصفح؛ هو يرسل request ويعرض response ولا يمنع JavaScript من قراءة البيانات. راجع DevTools Console/Network مع actual browser.

08

Trace كامل لطلب preflight: سطر بسطر

A preflight, header by header
Deep dive

Angular على https://app.shop.com بيبعت PUT بـ JSON و header Authorization لـ https://api.shop.com. ده مش «simple request» (method PUT + content-type JSON + Authorization)، فالمتصفح بيبعت preflight الأول.

Browser (app.shop.com)API (api.shop.com)OPTIONS /orders/7 Origin, Access-Control-Request-Method: PUT, -Headers: authorization, content-type204 Allow-Origin: https://app.shop.com Allow-Methods: PUT Allow-Headers: … Max-Age: 600browser checks: origin matches? method allowed? headers allowed? → yesPUT /orders/7 Origin + Authorization: Bearer …200 Access-Control-Allow-Origin: https://app.shop.com (+ Vary: Origin)
Preflight then actual request: the browser enforces, the server only declares
  • الـ preflight مالوش Authorization header: لو middleware الـ auth بيرفض OPTIONS بـ 401، الـ CORS هيفشل. عشان كده UseCors() قبل UseAuthentication().
  • Max-Age بيخلي المتصفح يحتفظ بنتيجة الـ preflight (المتصفحات بتحط حد أقصى خاص بيها) — بيقلل round-trip قبل كل طلب.
  • Vary: Origin مهم لو الـ response بتتعمل cache في CDN: من غيره، CDN ممكن يرجع Allow-Origin بتاع origin تاني.
  • الـ server بيصرّح بس، والمتصفح هو اللي بيمنع قراءة الـ response. curl و Postman ما بيطبقوش CORS — عشان كده «شغال في Postman ومش شغال في Angular».
09

CORS عبر البيئات: dev proxy و staging و prod

Configuring origins per environment
Practical
JSONproxy.conf.json (Angular dev): same-origin in development, no CORS needed
{ "/api": { "target": "https://localhost:7080", "secure": false, "changeOrigin": true } }
C#origins from configuration, validated at startup
var origins = builder.Configuration.GetSection("Cors:AllowedOrigins").Get<string[]>() ?? [];
if (origins.Any(o => o == "*" || !Uri.TryCreate(o, UriKind.Absolute, out _)))
    throw new InvalidOperationException("Cors:AllowedOrigins must be explicit absolute origins");   // fail fast

builder.Services.AddCors(o => o.AddPolicy("spa", p => p
    .WithOrigins(origins)                       // e.g. https://app.shop.com, https://staging-app.shop.com
    .WithMethods("GET", "POST", "PUT", "PATCH", "DELETE")
    .WithHeaders("authorization", "content-type", "idempotency-key")
    .WithExposedHeaders("location", "x-correlation-id", "retry-after")   // otherwise JS cannot read them
    .SetPreflightMaxAge(TimeSpan.FromMinutes(10))));

Exposed headers نقطة بتتنسى: الـ Angular مش هيقدر يقرأ Location أو Retry-After من response cross-origin إلا لو اتعملهم expose. وأفضل CORS هو مفيش CORS: لو الـ SPA والـ API على نفس الـ origin (reverse proxy أو BFF)، المشكلة كلها بتختفي، والـ cookies أبسط.

10

أخطاء شائعة في CORS

Common mistakes
Basics
  • AllowAnyOrigin() مع AllowCredentials() — ASP.NET Core بيرفض التركيبة، والحل الخاطئ هو SetIsOriginAllowed(_ => true) اللي بيعكس أي origin = ثغرة.
  • Regex/EndsWith للـ origin: EndsWith("shop.com") بيقبل evilshop.com.
  • اعتبار CORS حماية ضد الـ API abuse: أي client غير المتصفح بيتجاهله تمامًا.
  • Exception قبل ما CORS headers تتضاف ← المتصفح يعرض «CORS error» والسبب الحقيقي 500. شوف الـ response في Network tab.

الـ API بيرجع 500 لطلب cross-origin، والـ console بيقول CORS error. أول خطوة؟

11

تمرين محلول: تشخيص CORS

Worked diagnosis
Practical
الـ GET شغال من Angular، لكن الـ DELETE بيفشل بـ CORS error. الـ policy فيها WithOrigins و AllowAnyHeader بس.

الحل: الـ DELETE بيحتاج preflight. الـ policy ما فيهاش WithMethods("DELETE") أو AllowAnyMethod()، فالـ preflight بيرجع من غير Access-Control-Allow-Methods المناسب والمتصفح بيوقف الطلب. افتح الـ OPTIONS في Network tab: هتلاقي الـ header ناقص. أضف الـ methods المطلوبة صراحة.

الـ Angular مش قادر يقرأ header اسمه Location بعد POST ناجح cross-origin.

الحل: المتصفح بيكشف لـ JavaScript مجموعة headers محدودة بس (CORS-safelisted). أي header تاني لازم يتعمل expose: WithExposedHeaders("location").

12

اختبر فهمك

Knowledge check
Practical
ما الذي يكوّن Origin؟
Scheme + host + port.
هل CORS يمنع Postman أو curl من الوصول إلى API؟
لا؛ CORS سياسة يطبقها browser على cross-origin script access، وليست server-side authorization.
متى يحدث Preflight؟
عندما request لا تحقق شروط simple request، فيرسل browser OPTIONS للتحقق من method/headers/credentials policy.
هل يجوز Allow-Origin=* مع Allow-Credentials=true؟
لا؛ credentialed CORS يتطلب origin محددًا وليس wildcard.
هل CORS بديل عن CSRF protection؟
لا؛ CORS و CSRF تهديدان وآليات مختلفة، و cookie-authenticated state-changing requests تحتاج CSRF defenses مناسبة.
↗

المراجع والقراءة الإضافية

References & further reading

الدرس بيشرح الفكرة نفسها؛ الروابط دي للتحقق والتعمق والرجوع لتفاصيل الـ API. (محتاجة إنترنت.)

مصادر تعليمية ومتقدمة — Third-party & advanced reading

خريطة التغطية: 10 عنصر من الـ Roadmap ومكان شرحه في الدرس
RoadmapSame-Origin Policy§01
RoadmapOrigins§01
RoadmapCORS Headers§02
RoadmapSimple Requests§03
RoadmapPreflight Requests§03
RoadmapAllowed Origins, Methods, and Headers§02
RoadmapCredentials§03
RoadmapMiddleware Ordering§03
RoadmapCORS vs Authentication§03
RoadmapCommon Misconfigurations§03

خلصت الدرس وحليت الأسئلة؟ علّم عليه عشان يتحسب في تقدّمك.

محتويات الدرس