Software Engineer Encyclopedia
0%
Domain 05 · Security & Software Testing · Pillar

Authentication & Authorization: الصورة الكاملة من تسجيل الدخول إلى قرار الوصول

Authentication and Authorization — End-to-End Security Model

مرجع يربط Identity وCookies وJWT وOAuth/OIDC وClaims وRoles وPolicies وResource Authorization وSessions وCSRF وCORS.

  • Intermediate
  • ~15 min read
  • 13 sections
  • 4 code examples
  • 2 diagrams
  • 6 questions
  • Priority L2 · Essential
  • ASP.NET Core 10 · .NET 10

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

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

01

الصورة الكاملة: من أنت؟ ومسموح لك تعمل إيه؟

Identity, credential, principal and decision
Deep dive

الأمان في API يتكون من مراحل منفصلة. أولًا caller يقدم credential (cookie أو bearer token أو client certificate). Authentication handler يتحقق منها ويكوّن ClaimsPrincipal. بعد كده Authorization middleware/service يقيّم policy requirements على endpoint/resource. بعدها business logic ينفذ العملية، مع استمرار domain/database invariants. لو خلطت المراحل، غالبًا هتعمل endpoint تسمح بالوصول بناءً على وجود user فقط من غير ownership check.

CredentialCookie / BearerAuthenticationValidate / PrincipalAuthorizationPolicy / ResourceBusinessRulesDataConstraintsA valid login is not a permission to access every resource
Request security pipeline

Credential تثبت ما يدعيه caller، Principal تمثل identity وال claims، Policy تصف شروط الوصول، Resource handler يضيف سياق record، والـ domain model يمنع transitions غير صحيحة. كل طبقة لها دور؛ لا تستخدم claim أو role بدل كل شيء.

رحلة Request كاملة: من Cookie إلى Resource Policy

عند وصول request، middleware يقرأ credential وفق authentication scheme، يتحقق من token/cookie، ويبني ClaimsPrincipal. Authorization middleware يقيّم endpoint metadata والسياسات والـ requirements. ثم resource authorization قد يحتاج تحميل entity وفحص owner/tenant/state. أخيرًا database query يجب تكون scoped بما يمنع الوصول غير المقصود. كل خطوة لها threat مختلفة؛ نجاح authentication لا يعني أن المستخدم مسموح له بالـ resource.

رتب middleware بشكل صحيح: routing قبل authorization policy evaluation، و authentication قبل authorization. استخدم fallback policy إذا كان default behavior يجب يكون authenticated، واستثنِ public endpoints صراحة. لا تخلط 401 (credential مفقود/غير صالح) مع 403 (هوية معروفة بلا permission)، مع مراعاة ألا تكشف resource existence عندما ذلك حساس.

Identity و Credential و Session: افصل المفاهيم

Identity هي الكيان الذي يمثله المستخدم أو service داخل النظام، وغالبًا لها stable subject ID. Credential هي الدليل المستخدم لإثبات الهوية: password، passkey، certificate، API key، أو token. Session هي حالة الثقة/التسجيل بعد نجاح authentication، وقد تمثلها cookie أو server-side record أو access token. الخلط بينهم يسبب أخطاء مثل استخدام email كمفتاح identity دائم، أو اعتبار access token هو user account.

استخدم immutable internal user ID كـ subject، واجعل email/username attributes قابلة للتغيير مع uniqueness policy واضحة. لا تفترض أن email verified لمجرد وجوده في claim. service identities يجب تكون منفصلة عن human users ولها permissions و rotation/audit مختلفين. عند account linking، لا تربط حسابين لمجرد تطابق email غير verified.

من HTTP Request إلى Authenticated Principal ثم Authorization

الـ authentication middleware يختار scheme، ويستدعي handler الذي يستخرج credential من cookie أو Authorization header، ثم يتحقق منه ويُنشئ ClaimsPrincipal. هذا لا يعني أن المستخدم مسموح له بكل شيء؛ authorization middleware يقيّم endpoint metadata والـ policies والـ resource requirements. الترتيب المعتاد: UseAuthentication() قبل UseAuthorization() وبعد routing في pipeline المعتاد.

Challenge يعني أن العميل لم يقدم credential صالحًا أو لم تتم مصادقته؛ bearer handler غالبًا يرجع 401. Forbid يعني أن principal authenticated لكن لا يملك permission؛ غالبًا 403. لا تحوّل كل الحالات إلى 401 لأن ذلك يطمس الفرق ويصعب على clients التصرف.

C#Practical engineering example
app.UseRouting();
app.UseCors("Frontend");
app.UseAuthentication();
app.UseAuthorization();

app.MapGet("/admin/reports", () => Results.Ok())
   .RequireAuthorization(policy => policy.RequireRole("Admin"));

الـ CORS placement يتغير حسب hosting/endpoint setup، لكن يجب أن يعمل قبل endpoint execution وأن تسمح preflight requests بالمرور. لا تجعل CORS بديلًا عن auth. اختبر anonymous request (401)، authenticated without permission (403)، authenticated allowed (200)، و invalid token (401).

03

Identity Lifecycle: Registration → Login → Recovery

Credential lifecycle
Deep dive

Local account flow يبدأ بتسجيل user، password hashing، email confirmation، login، optional MFA، session issuance، logout، password reset/change، account lockout و disable. Identity تدير أجزاء كثيرة، لكن التطبيق يحدد policy والـ email delivery والـ audit والـ rate limiting. لا تعِد اختراع password hashing أو token generation.

بعد login، cookie handler أو token issuer ينشئ credential. claims داخل principal قد تشمل subject و roles و permissions و tenant context. claims snapshot قد تصبح stale بعد تغيير role أو account status؛ حدد session lifetime و security stamp/revocation strategy حسب حساسية القرار.

04

JWT Validation: لا تثق في Decode

Issuer to API trust chain
Deep dive

Issuer يصدر access token موقعة. Resource API تتحقق من signature بمفتاح موثوق، issuer، audience، expiration/nbf، وربما token type/scopes. Payload ليست سرية لمجرد أنها JWT. لا تستخدم ID token للوصول إلى API، ولا تسمح token موجهة إلى service أخرى.

Access token قصيرة العمر؛ refresh token تحفظ server-side بشكل آمن وتُدار بال rotation/revocation. Logout قد ينهي refresh session أو cookie، لكنه لا يبطل JWT موقعة تلقائيًا. اختَر بين short TTL و denylist/introspection/version lookup حسب الحاجة. Key rotation يجب أن تدعم فترة انتقالية فيها أكثر من public key صالح.

Token Lifecycle: Issuance إلى Expiry و Revocation

حدد token purpose و audience و lifetime و claims و signing key و revocation semantics قبل إصدار token. Access token يجب يحمل أقل claims لازمة، ولا يحتوي PII غير ضرورية. Claims snapshot قد تصبح stale بعد تغيير role أو تعطيل account؛ قصر lifetime يقلل window، و server-side session/version check يوفر revocation أقوى بتكلفة lookup إضافية. اختر trade-off وفق sensitivity.

لا تضع secrets أو payment data داخل JWT؛ signature تمنع التعديل لكنها لا تخفي payload في JWS العادي. لا تقبل token من issuer أو audience غير متوقعين. Key rotation تحتاج kid/trusted key resolution، overlap window، وإزالة المفتاح القديم بعد expiry. لا تسمح للـ token header أن يوجه verifier إلى arbitrary URL أو key source غير موثوق.

05

OAuth و OpenID Connect و PKCE

Delegated access and user authentication
Deep dive

OAuth authorization framework لتفويض access إلى resource؛ OIDC يضيف authentication و ID token. Authorization Code + PKCE مناسب لتطبيقات user-facing. Client Credentials لتطبيق service-to-service بلا user. لا تنشئ access token من username/password في production flow؛ استخدم identity provider و standards-based protocol.

Scope يحدد access delegated إلى API، و role/permission قد يحدد application authorization. الـ API لا تثق في token إلا بعد validation، ثم تطبق policy. BFF pattern يخفي tokens عن browser JavaScript ويحتفظ بها server-side مع session cookie، لكنه يحتاج CSRF protection وإدارة sessions.

Cookies و CSRF و OAuth 2.0 و OpenID Connect

Cookie authentication مناسبة غالبًا لتطبيق browser من نفس الموقع؛ المتصفح يرسل cookies تلقائيًا، لذلك CSRF threat مهم. استخدم HttpOnly لمنع JavaScript من قراءة cookie، و Secure مع HTTPS، و SameSite وفق cross-site flow، مع antiforgery token للعمليات الحساسة عندما يلزم. HttpOnly يقلل سرقة cookie عبر JS لكنه لا يمنع XSS من تنفيذ actions باسم المستخدم.

OAuth 2.0 إطار تفويض للوصول إلى resources، و OpenID Connect طبقة هوية فوق OAuth تضيف ID Token ومعايير authentication. لا تستخدم ID Token كـ API access token. لتطبيقات المستخدم النهائي استخدم Authorization Code Flow مع PKCE، وتجنب implicit flow القديم. افهم redirect URI validation و state و nonce.

C#Practical engineering example
// ASP.NET Core cookie settings (illustrative)
builder.Services.AddAuthentication(CookieAuthenticationDefaults.AuthenticationScheme)
    .AddCookie(options =>
    {
        options.Cookie.HttpOnly = true;
        options.Cookie.SecurePolicy = CookieSecurePolicy.Always;
        options.Cookie.SameSite = SameSiteMode.Lax;
        options.SlidingExpiration = true;
        options.ExpireTimeSpan = TimeSpan.FromMinutes(30);
    });

SameSite=None يتطلب Secure في المتصفحات الحديثة، وقد تحتاجه في cross-site identity flows؛ لا تختاره بلا فهم. في production أضف antiforgery protection، session revocation، cookie domain/path ضيقين، و HTTPS everywhere. في SPA/API افحص storage threat model بدل وضع tokens تلقائيًا في localStorage.

06

من Role إلى Policy إلى Resource Ownership

Authorization layers
Deep dive

Role مناسبة للتصنيفات الواسعة؛ claim تحمل attribute؛ policy تجمع requirements؛ resource-based handler يفحص object نفسه. مثال: orders.read permission تسمح بالوظيفة، لكن Order محدد لازم يكون تابعًا لنفس tenant أو للمستخدم، أو المستخدم لديه Support override.

اعمل authorization بعد تحميل resource أو ضمن query scoped. لا تعتمد على ID صعب التخمين. لا تضع tenant id من request body كحقيقة. لكل GET/PUT/DELETE/download/export/bulk action اختبر owner/non-owner/other tenant. Authorization middleware وحده لا يعرف business ownership تلقائيًا.

API Keys و Service-to-Service Authentication

API key عادة opaque secret يحدد client/application وليس user identity كاملة. خزّن hash للمفتاح إن أمكن، اعرض raw key مرة واحدة، وفر rotation/revocation/expiry، وحدد scopes/quotas. لا تضع API key في frontend JavaScript؛ كل زائر يستطيع استخراجها. machine-to-machine workloads يفضل لها workload identity أو OAuth client credentials أو mTLS حسب platform، بدل مشاركة password ثابتة.

في service-to-service، حدد issuer/audience لكل service، واستخدم least privilege، short-lived tokens، clock synchronization، certificate rotation، و audit identity. لا تثق في X-User-Id header القادم من الإنترنت؛ proxy موثوق فقط يمكنه تمرير identity headers بعد حذف أي header من العميل والتحقق من signed assertion.

07

ASP.NET Core Middleware Ordering

Authentication before authorization
Practical
C#Program.cs — security pipeline
var app = builder.Build();
app.UseHttpsRedirection();
app.UseRouting();
app.UseCors("Frontend");
app.UseAuthentication();
app.UseAuthorization();
app.MapControllers();
app.Run();

Authentication يجب أن يسبق Authorization حتى تتوفر HttpContext.User. CORS عادة بعد routing وقبل authorization في endpoint routing arrangement. HTTPS redirect مبكرًا. لو عندك static files أو custom middleware، راجع هل تُخدم قبل authorization أم تحتاج حماية خاصة.

Authentication Schemes و Challenge و Forbid في ASP.NET Core

Authentication scheme يحدد handler وطريقة استخراج credential والتحقق منها. قد يكون عندك cookie scheme للـ browser و JWT bearer scheme للـ API و API key scheme لخدمة داخلية. لا تجعل default scheme غامضًا إذا endpoints تحتاج أكثر من نوع. [Authorize(AuthenticationSchemes = "Bearer")] أو policy scheme يمكن أن يحدد الاختيار، لكن راجع fallback/default behavior حتى لا تقبل credential غير مقصودة.

Challenge يعني أن المستخدم لم يقدم credential صالحة للطريقة المطلوبة؛ غالبًا 401 أو redirect إلى login حسب handler. Forbid يعني أن الهوية معروفة لكن permission غير كافية؛ غالبًا 403. Cookie handler قد يحول 401 إلى redirect، وهذا غير مناسب دائمًا لـ API clients؛ اضبط behavior حسب framework version والـ API contract. لا تخلط 401/403 عند resource existence الحساسة دون threat analysis.

08

CSRF و CORS و XSS: علاقات متشابكة وليست بدائل

Browser threat model
Deep dive

CSRF يستغل browser credentials التلقائية (غالبًا cookies) لإرسال state-changing request من موقع آخر. CORS يتحكم في قراءة browser scripts للـ cross-origin response. XSS يسمح script خبيثًا بالعمل داخل origin موثوق. الدفاعات تختلف: anti-forgery tokens و SameSite/origin checks لـ CSRF؛ allow-list دقيقة لـ CORS؛ output encoding/CSP/DOM safety لـ XSS.

HttpOnly يمنع JavaScript من قراءة cookie، لكنه لا يمنع XSS من تنفيذ requests باسم المستخدم. CORS لا يمنع curl/Postman ولا يحمي API من unauthorized callers. JWT في localStorage تقلل CSRF التلقائي لكنها تزيد أثر XSS على token theft.

CSRF و CORS و XSS: تهديدات مختلفة لا تحل محل بعضها

XSS: attacker code يعمل داخل origin موثوق؛ قد يقرأ DOM ويصدر requests، حتى لو cookie HttpOnly لا يمكن قراءتها مباشرة. الدفاع: output encoding، framework sanitization، CSP، تقليل unsafe HTML و third-party scripts. CSRF: browser يرسل credential تلقائيًا إلى site الضحية؛ الدفاع يشمل SameSite و anti-forgery token و Origin/Referer validation وفق flow. CORS: browser يقرر هل script من origin آخر يستطيع قراءة response؛ ليس authentication ولا CSRF defense وحده.

لا تعتمد على CORS لمنع curl أو mobile client أو server-to-server؛ هؤلاء لا يخضعون ل browser enforcement. ولا تفترض SameSite يحل كل CSRF scenarios خصوصًا cross-site integrations أو legacy browsers. صمم cookie attributes والـ anti-forgery mechanism مع request methods و content types و redirect flows، ثم اختبرها في browser فعلي.

09

401 vs 403 و Security Testing

Verify both allowed and denied paths
Practical

401: لا توجد credentials صالحة أو authentication فشل. 403: principal authenticated لكن authorization رفض. اختبر anonymous، invalid token، expired token، wrong audience، user بلا role، owner/non-owner، cross-tenant، disabled account، revoked refresh token و CSRF failure. تأكد أن denied request لم تنفذ أي side effect.

اختبر كل flow end-to-end على test server مع test identity provider أو test signing keys. راجع cookies flags، redirect URIs، CORS preflight، refresh replay، security stamp، account recovery، audit events، و key rotation. لا تضع real secrets في tests أو fixtures.

Security Test Matrix: Negative Cases قبل Happy Path

AreaNegative testExpected outcome
AuthenticationMissing/expired/wrong issuer token401 / challenge
AuthorizationAuthenticated user without permission403 / forbid
Resource ownershipChange resource ID to another userDenied without data leakage
Tenant isolationUse tenant A credential against tenant B IDDenied at API and data boundary
RefreshReplay a consumed refresh tokenReuse detection and session response
BrowserCross-site state-changing requestCSRF defense blocks it
Rate limitBurst across multiple replicasQuota matches intended scope

اختبر أيضًا clock skew، key rotation overlap، malformed JWT header، duplicate cookies، disabled user، role removed after token issuance، account lockout، refresh race، و logout ثم replay. security test يجب يثبت أن الوصول مرفوض، لا يكتفي أن endpoint ترجع أي 4xx.

10

خريطة القرار: أي auth لأي client؟

Choosing an authentication design
Deep dive
Who is the client?Same-site web appMVC / Razor / BFFSPA cross-originAngular → APIMobile / desktopnative appService / partnerno user presentCookie sessionHttpOnly, SameSite, antiforgeryBFF (preferred) orOIDC code+PKCE, short tokensOIDC code+PKCEsystem browser, secure storageClient credentials / mTLSor managed identity; API keys for simple
Pick the auth model from the client type, not from fashion

القرار ده بيتاخد مرة واحدة في بداية المشروع وبيأثر على كل حاجة بعده (CORS، CSRF، token storage، logout). الـ Capstone اختار JWT من IdP خارجي (Entra ID أو Keycloak محليًا) مع API واحد، ومشروح ليه في الـ ADR الخاص بيه.

11

Service-to-service: client credentials خطوة بخطوة

Machine identities
Practical
C#worker calls the API with its own identity (no user)
// 1) The worker gets a token for the API's audience using its own credentials (or a managed identity in Azure)
var credential = new DefaultAzureCredential();                          // managed identity in Azure, dev login locally
var token = await credential.GetTokenAsync(new TokenRequestContext(["api://shop-api/.default"]), ct);

// 2) The API authorizes on *app roles* in the token, not on user roles
builder.Services.AddAuthorizationBuilder()
    .AddPolicy("ingest:write", p => p.RequireClaim("roles", "Ingest.Write"));   // role assigned to the worker app only
  • ما تعيدش استخدام token مستخدم في background job ("impersonation" ضمني) — الـ job يقدر يعمل اللي المستخدم يقدر بس، وبعد ما الـ token يخلص الـ job يقع.
  • لو العملية على بيانات tenant معين، الـ tenant id جزء من الـ message اللي اتعملها validation، والـ worker بيطبّق نفس الـ query filters.
  • Managed identity/workload identity أحسن من client secret: مفيش سر يتسرّب أو يتعمله rotate يدوي.
12

أخطاء شائعة في الـ authentication

Common mistakes
Basics
  • ValidateAudience = false «عشان يشتغل» ← token مخصص لـ API تاني بيتقبل عندك.
  • Refresh token طويل من غير rotation ولا revocation ← تسريب واحد = دخول لشهور.
  • 401 مقابل 403 متلخبطين: 401 = مش عارفين انت مين، 403 = عارفين ومش مسموح.
  • Logout بيمسح الـ token من المتصفح بس، والـ refresh token لسه صالح على السيرفر.
  • رسائل login بتفرق بين «المستخدم مش موجود» و«الباسورد غلط» ← account enumeration.
(Senior) API بيخدم Angular SPA و worker داخلي وشريك خارجي. إزاي تصمم الـ auth؟
IdP واحد: SPA بـ code+PKCE (أو BFF)، worker بـ client credentials/managed identity و app roles، والشريك بـ client credentials بـ scopes محدودة أو API key مع rate limit منفصل. الـ API بيتحقق من iss/aud/exp ويطبق policies مختلفة حسب نوع الـ principal، وكل طلب بيتسجل بالـ client id في الـ audit.
13

اختبر فهمك

Knowledge check
Practical
هل Authentication تعني أن المستخدم يملك صلاحية؟
لا؛ Authentication تثبت identity، و Authorization تقرر access حسب policy/resource.
هل CORS يحمي API من curl؟
لا؛ CORS browser policy، ولا يغني عن authentication/authorization.
هل ID token تصلح كـ API access token؟
لا؛ ID token موجهة إلى client لإثبات authentication، والـ API تحتاج access token موجهة إلى audience الخاصة بها.
متى تحتاج Resource-Based Authorization؟
عندما قرار الوصول يعتمد على resource data مثل owner أو tenant أو state.
ما الفرق بين 401 و403؟
401 authentication غير صالحة/مفقودة؛ 403 الهوية معروفة لكن الصلاحية غير كافية.
↗

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

References & further reading

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

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

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