
الـ CORS مش سور أمان: بيحمي إيه ومش بيحمي إيه
- كاتب موثّق
محتويات المقال
https://shop.example. وعشان يثبت ده، developer بينادي نفس الـ endpoint من صفحة على domain تاني، والـ console في المتصفح بيطبع "blocked by CORS policy". النتيجتين حقيقيتين. بس ولا واحدة فيهم معناها اللي الفريق فاكره.
الفكرة الغلط الشائعة
Program.cs جنب الـ authentication، ورا method اسمها WithOrigins، وtutorials كتير بتوصفها إنها بتحدد مين يقدر يوصل للـ API بتاعك. وكمان أخطاء الـ CORS وجع دماغ يومي وانت بتطوّر، فبتحس إن الـ CORS بوّاب صارم. بس المنع ده بيحصل في المتصفح، بعد ما السيرفر بتاعك يكون رد خلاص.
اللي بيحصل فعلًا
السيرفر بيرد، والمتصفح بيقرر مين يقرا
https://shop.example، وناديناه بـ 4 طرق:
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 ورسالة في الـ console بتقول "No 'Access-Control-Allow-Origin' header is present on the requested resource."
الـ CORS بيخفف الـ same-origin policy، مش بيبني سور
OPTIONS ويستنى موافقة. لكن الـ request اللي شكله زي form submission بيطلع من غير ما يستأذن. وMDN بتوضّح إن السيرفر "still must opt-in using Access-Control-Allow-Origin to share the response with the script"، يعني ده بيتحكم في القراية، مش في إن الـ request يوصل ولا لأ.
الـ Origin ادعاء من المتصفح، مش هوية للـ client
Origin من الـ forbidden headers "so the user agent remains in full control" عليه، وعشان كده بيساعد ضد الـ CSRF. لكن برّه المتصفح هو header عادي: الـ curl بتاعنا ادّعى إنه https://shop.example ورجع له الـ allow header. الـ CORS مايقدرش يفرّق بين الـ front end بتاعك وأي script، وهو أصلًا مش معمول لكده. والـ Fetch Standard بيقول إن Access-Control-Allow-Origin: * على resource عام بيشاركه مع الـ browser APIs "much like it is already shared with curl and wget."
الـ CORS بيحمي إيه فعلًا: الداتا اللي بتوصلها من خلال المستخدمين
حط الـ access control جوه الـ 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 بيقرر مين مسموح له ينادي الـ endpoint، وبيشتغل مع أي client. أما الـ CORS فبيقرر بس أنهي صفحات ويب تقدر تقرا الرد جوه المتصفح، فبيكتب الـ origin الوحيد اللي محتاجه. وMicrosoft بتسمّي الفخ اللي في النسخة الغلط: "Bypassing the built-in checks by using SetIsOriginAllowed(_ => true) together with AllowCredentials is also an insecure configuration."
تطبقها إزاي في مشروعك
افترض إن أي client يقدر ينادي أي endpoint حط authentication و authorization على كل endpoint مش معمول إنه يبقى عام. والـ CORS مش بيغيّر الليستة دي. خلّي الـ policy ليستة محددة اكتب كل origin مسموح باسمه. ممنوع ترجّع الـ origin زي ما هو، وممنوع *مع credentials، والـ wildcard subdomains بس لو بتثق في كل subdomain.اسمح بالـ credentials بس لما الـ front end يحتاجها لو الـ front end بينادي الـ API بـ bearer token، يبقى مش محتاج AllowCredentials، ولما تشيلها بتشيل خطر الـ cookies.حمّل الـ origins من الـ configuration خلّي لكل environment ليستة لوحدها، عشان localhostعمره ما يوصل للـ production، ومحدش يوسّع الـ policy عشان يحل error في الـ dev.اختبر الطريقين في الـ tests نادي كل endpoint محمي بـ curl من غير credentials، ومن صفحة على origin مش مسموح. الاتنين لازم يفشلوا، كل واحد لسبب مختلف.
الخلاصة
الـ CORS بيتحكم في أنهي صفحات ويب تقدر تقرا الـ responses بتاعتك جوه المتصفح، مش في مين يقدر ينادي الـ API. السيرفر بينفّذ الـ request في الحالتين، والمتصفح بس هو اللي بيمنع الـ response عن الصفحة. الـ clients اللي مش متصفحات مش بتلتزم بالـ CORS، وتقدر تبعت أي Originheader هي عايزاه.الـ access control الحقيقي هو الـ authentication والـ authorization، على السيرفر، في كل request. الـ CORS policy المفتوحة مع credentials هي الحالة الخطيرة، فخلّي الـ origins المسموحة محددة بالظبط.
التعليقات (0)