Interview Handbook by Sayed Elmahdy English

المحور 19 · الجودة والتشغيل

Security

AuthN و AuthZ، و OAuth2 و OIDC، و JWT، و Passkeys، و OWASP Top 10، و Secrets.

18 سؤالJunior · 5Mid · 8Senior · 510 اختيارات

المفاهيم

هنفهم إيه؟ لما مستخدم يطلب invoice، لازم نعرف مين هو ثم نتحقق إنه مسموح له يشوفها. هتتعلم تربط التهديد بضابط مناسب—من تسجيل الدخول والصلاحيات إلى منع حقن وتسريب الأسرار—وتفهم ما الذي يحميه كل ضابط وما الذي لا يحميه.

قبل ما تبدأ: request يحمل بيانات من عميل لا نثق به تلقائياً. Authentication تثبت الهوية؛ authorization تقرر السماح بالفعل. يحمي النقل، لكنه لا يثبت أن كل طلب مصرح به. معرفة بسيطة بـ وواجهات تكفي لمتابعة الأمثلة.

المصطلحات اللي تحتها خط منقّط تقدر تضغط عليها لمعرفة معناها، وترجع تكمل من نفس مكانك.

#Authentication و Authorization و cookies و tokensAuthentication, authorization, cookies and tokens

مثال خطوة بخطوة
  1. أحمد دخل الموقع بنجاح؛ ده يثبت هويته وفق آلية تسجيل الدخول، وليس إنه يملك كل الطلبات.
  2. أحمد طلب فتح الطلب 42 الذي يخص منى. authorization لازم تتحقق من ملكية الطلب أو صلاحية واضحة، حتى لو authentication نجحت.
  3. Cookie أو وسيلة لحمل أو إثبات سياق الهوية بحسب التصميم؛ وجودها لا يغني عن فحص الصلاحية لكل مورد. اختبر مستخدمًا مسجلًا يحاول الوصول لبيانات مستخدم آخر.

معرفة إن caller سجّل دخول مش معناها يقدر يفتح أي invoice. بتثبت الهوية، و بتقرر الوصول للعملية والـ resource. في ، الهوية الغايبة أو غير الصالحة غالباً 401، والهوية الصحيحة من غير صلاحية 403؛ أحياناً 404 مناسب عشان مانكشفش وجود resource.

بطاقة الدخول تثبت إنت مين؛ صلاحية الباب بتحدد تقدر تدخل الأوضة دي ولا لأ.
الاختيارالسلوك والمخاطر
Cookieالمتصفح بيبعتها تلقائياً؛ مناسبة لجلسة web مع HttpOnly و Secure و SameSite وسياسة .
Bearer token في Authorization headerالعميل بيضيفه صراحة؛ مناسب للـ APIs. سرقته تسمح بالاستخدام لحد expiry أو revocation مطبقة.
BFFtokens تفضل في backend، والمتصفح ياخد session cookie؛ يقلل تعرضها لـ JavaScript لكن CSRF و لسه محتاجين حماية.

Cookie آلية نقل وتخزين، و صيغة token؛ مش متضادين. HttpOnly يمنع JavaScript يقرا cookie، لكنه مش بيمنع XSS يبعت requests باسم المستخدم.

#OAuth2 و OIDC والـ flows الحاليةOAuth 2.0, OIDC and current flows

تفويض عميل للوصول لـ بـ access ؛ مش login protocol لوحده. بيضيف هوية المستخدم و ID token للـ client. الـ API يستقبل access token المخصص له، مش ID token مخصص لواجهة تسجيل الدخول.

  1. العميل يولّد code verifier عشوائي و S256 challenge، و state لربط الطلب بالرد.
  2. المستخدم يسجل دخول عند identity provider عبر redirect مسجلة بدقة؛ OIDC يستخدم nonce لربط ID token بالطلب.
  3. يرجع authorization code قصيرة العمر، والعميل يبدّلها مع verifier عبر token endpoint.
  4. العميل يحقق OIDC response و ID token، ويستخدم access token لاستدعاء API. Refresh token مش مضمونة؛ تعتمد على scope وسياسة provider.

يحمي code interception، مش بديل عن state أو redirect validation. Confidential clients لسه محتاجة client authentication. Client credentials لـ service identity من غير مستخدم؛ فضّل managed identity أو certificates لما المنصة تدعم.

قديمالاختيار الحالي
Implicit: token في authorization responseAuthorization code مع PKCE لتقليل exposure و replay
Password grant: التطبيق يستلم password المستخدمRedirect لـ provider؛ password grant محظورة في security BCP

#JWT validation و refresh rotationJWT validation and refresh-token rotation

مثال خطوة بخطوة
  1. يحتوي claim باسم role وقيمتها admin. قراءة النص وفك ترميزه تكشف ما هو مكتوب فقط؛ لا تثبت إن مصدرًا موثوقًا أصدره.
  2. قبل الاعتماد عليه تحقق من التوقيع ومصدر الإصدار والجمهور المقصود والصلاحية وفق إعدادات موثوقة. تعديل role داخل token موقّع يجب أن يؤدي لرفضه.
  3. التوقيع لا يخفي البيانات؛ لا تضع أسرارًا في لمجرد أنه موقّع. وبعد قبول token، ما زلت تحتاج قرار authorization للعملية والمورد المحددين.

الـ signed JWT الشائعة فيها header و payload و signature. Base64Url مش encryption؛ ماتحطش أسرار في claims. التوقيع بيتحقق بمفاتيح issuer موثوق وخوارزميات مقبولة، مش بمجرد فك النص أو تصديق alg اللي المهاجم كاتبها.

// Package: Microsoft.AspNetCore.Authentication.JwtBearer 10.x
using Microsoft.AspNetCore.Authentication.JwtBearer;
using Microsoft.IdentityModel.Tokens;

builder.Services.AddAuthentication(JwtBearerDefaults.AuthenticationScheme)
    .AddJwtBearer(options =>
    {
        options.Authority = "https://identity.example.com"; // (1)
        options.Audience = "orders-api";
        options.MapInboundClaims = false;
        options.TokenValidationParameters = new()
        {
            ValidateIssuer = true,
            ValidateAudience = true,
            ValidateLifetime = true,
            ValidateIssuerSigningKey = true,
            RequireSignedTokens = true,
            ValidAlgorithms = [SecurityAlgorithms.RsaSha256], // (2)
            ClockSkew = TimeSpan.FromSeconds(30)
        };
    });
builder.Services.AddAuthorization();
// After builder.Build():
app.UseAuthentication();
app.UseAuthorization();
app.MapGet("/orders", () => Results.Ok()).RequireAuthorization(); // (3)
🧾 شرح الكود
  1. (1) Authority ثابتة من configuration موثوقة؛ metadata و signing keys تيجي من provider عبر ، مع key rotation.
  2. (2) المثال يفترض provider بيستخدم RS256؛ اتفق على الخوارزميات الفعلية وماتقبلش unsigned token.
  3. (3) ترتيب الـ يكوّن User قبل permission evaluation. RequireAuthorization هنا login بس؛ ملكية كل order محتاجة policy إضافية.

Access tokens قصيرة العمر تقلل نافذة السرقة، لكن مش فيه مدة سحرية واحدة. في offline validation الإلغاء مش فوري؛ denylist أو introspection يضيفوا state وتكلفة. Refresh rotation تستهلك token وتصدر بديل في عملية atomic، وتراقب reuse وتلغي family حسب سياسة provider. نسّق refresh المتوازي عشان ماتعتبرش retry شرعي سرقة بلا تحليل.

#ASP.NET Core Identity و passkeys في .NET 10ASP.NET Core Identity and .NET 10 passkeys

Identity بيدير users و password hashing و roles و lockout و email confirmation و recovery . مش OAuth authorization server كامل، و bearer tokens بتاعة Identity endpoints مش لازم تكون ولا بديل عام لـ provider.

في 10، Identity فيها دعم passkeys عبر WebAuthn. وقت registration يتسجل public key، ووقت login authenticator يوقع challenge مربوط بالـ relying party و origin. البصمة أو PIN بتفتح استخدام المفتاح محلياً؛ السيرفر مش بيستلم البصمة أو private key.

  1. سجّل challenge جديدة قصيرة العمر واربطها بالعملية والمستخدم عند اللزوم.
  2. الـ browser و authenticator ينفذوا WebAuthn ceremony.
  3. السيرفر يتحقق من challenge و origin و RP ID و signature و user verification حسب السياسة.
  4. وفّر إدارة credentials وفقد الجهاز و recovery بمستوى أمان مناسب.
قبلفي ASP.NET Core 10
تكامل WebAuthn مخصص أو مكتبة خارجيةIdentity passkey APIs و integration حسب نوع التطبيق

Passkeys بتقاوم phishing بسبب ارتباطها بالموقع، لكن recovery ضعيفة ممكن تهد الحماية. بعض credentials بتتزامن عن طريق مدير passkeys؛ ماتدعيش إن كل private key محبوسة في جهاز مادي واحد.

#Roles و claims و policies و resource authorizationRoles, claims, policies and resource authorization

Role زي Finance تصنيف واسع. Claim زي permission معلومة جاية من issuer موثوق. Policy تجمع requirements، و handler ينفذها. Resource-based authorization مناسبة لما القرار محتاج يعرف صاحب الطلب وحالته، مش هوية caller بس.

builder.Services.AddAuthorizationBuilder()
    .AddPolicy("orders.edit", policy => policy
        .RequireAuthenticatedUser()
        .RequireClaim("permission", "orders.edit")); // (1)

// Endpoint fragment: tenant and user IDs come from validated identity context.
var order = await db.Orders.SingleOrDefaultAsync(
    o => o.Id == id && o.TenantId == tenantId, ct); // (2)
if (order is null) return Results.NotFound();
var decision = await authorization.AuthorizeAsync(
    user, order, "EditOwnPendingOrder");             // (3)
if (!decision.Succeeded) return Results.Forbid();
// Perform the update with concurrency protection.
🧾 شرح الكود
  1. (1) وجود claim مش كفاية لو مصدرها مش موثوق. Policy بتقارن value المطلوبة.
  2. (2) tenant filter قبل تسليم الداتا؛ صعب التخمين مش authorization.
  3. (3) policy مخصصة لازم تسجل requirement و handler يطابق owner و Pending ويعمل Succeed عند السماح. لو policy مش متسجلة الاستدعاء مش هيشتغل.

المثال fragment مش تعريف كامل للـ handler. اربط كمان endpoint بسياسة permission، واقفل كل مسارات القراءة والكتابة والـ jobs والـ exports بنفس tenant boundary. filters مفيدة كـ defense in depth، بس raw و IgnoreQueryFilters و admin paths محتاجين مراجعة. Cache keys و blob paths و message handlers لازم يعزلوا tenant برضه.

#OWASP Top 10:2025 وربطها بـ .NETOWASP Top 10:2025 mapped to .NET

دي قائمة توعية بالمخاطر، مش شهادة إن التطبيق آمن. الإصدار هنا 2025؛ ماعدتش category مستقلة زي 2021، لكنها لسه threat لازم تمنعها.

الفئةتطبيق عملي
A01 Broken Access Controldeny by default، و policies، و ownership و tenant checks، ومنع SSRF.
A02 Security Misconfigurationتعطيل تفاصيل exceptions في production، و محدودة، و headers وإعدادات آمنة.
A03 Software Supply Chain Failuresمصادر packages موثوقة، و dependency scanning، و build pipeline محمية.
A04 Cryptographic Failures، و password hashing، و key management و authenticated encryption.
A05 InjectionParameterized queries، و output encoding، وعدم تنفيذ input كـ commands.
A06 Insecure DesignThreat modeling، وحدود كميات ومبالغ، و abuse-case tests.
A07 Authentication FailuresIdentity أو provider موثوق، و أو passkeys، و rate limits و recovery آمنة.
A08 Software or Data Integrity Failuresتحقق webhook signatures ومصدر artifacts؛ تجنب unsafe .
A09 Security Logging and Alerting FailuresAudit للأفعال الحساسة مع alerts و retention ومن غير أسرار.
A10 Mishandling of Exceptional ConditionsFail closed، و resource limits، و timeouts، وتنضيف الموارد من غير bypass للصلاحيات.

#SQL injection: افصل الداتا عن التنفيذSQL injection: separate data from executable syntax

لو username تدخل جوه concatenation، المهاجم ممكن يغير معنى الـ query. Validation لوحدها مش بديل للـ parameters. عادة بتعمل parameterization للقيم، لكن raw SQL المبنية كسلسلة بتفضل خطر.

❌ input بقت SQL syntax
var sql = $"SELECT * FROM Users WHERE Email = '{email}'";
var users = await db.Users.FromSqlRaw(sql).ToListAsync(ct);
✅ parameterization
var users = await db.Users
    .Where(user => user.Email == email)
    .ToListAsync(ct);                                    // (1)

// If raw SQL is required, pass interpolation directly to FromSql:
var matches = await db.Users
    .FromSql($"SELECT * FROM Users WHERE Email = {email}") // (2)
    .ToListAsync(ct);
🧾 شرح الكود
  1. (1) القيمة بتتبعت كـ parameter؛ quotes في email مش بتتحول لأوامر.
  2. (2) FromSql تستقبل FormattableString مباشرة؛ ماتحولهاش string الأول وتبعتها FromSqlRaw. أسماء columns و ORDER BY directions مش parameters؛ اختارهم من allowlist ثابتة.

استخدم account بأقل صلاحيات. نفس المبدأ للـ shell: ماتركّبش commands من input؛ استخدم و argument lists مع validation حسب العملية.

#XSS و CSRF: هجمات مختلفةXSS and CSRF: different attacks

بتشغّل script في أصل موقعك، فتقدر تقرأ داتا أو تعمل أفعال المستخدم. Razor بيعمل encoding افتراضياً، لكن Html.Raw مع user content أو DOM innerHTML خطر. Rich HTML محتاجة sanitizer موثوق، و JavaScript و contexts ليها قواعد encoding مختلفة.

❌ تجاوز encoding
@Html.Raw(Model.CustomerNote)
✅ Razor output encoding
@Model.CustomerNote

بيستغل إن المتصفح بيبعت cookie تلقائي لموقعك لما المستخدم يزور صفحة مهاجم. استخدم antiforgery في state-changing cookie-authenticated requests، و SameSite كطبقة إضافية؛ ماتعملش تغيير state بـ GET. مش دفاع كامل ضد CSRF.

// MVC cookie-authenticated app; register before Build.
builder.Services.AddControllersWithViews(options =>
    options.Filters.Add(new AutoValidateAntiforgeryTokenAttribute())); // (1)

// Razor form: the form tag helper normally generates this token already.
// Explicit generation is shown to make the mechanism visible.
// @Html.AntiForgeryToken()                                      // (2)
🧾 شرح الكود
  1. (1) filter يتحقق من unsafe methods؛ محتاج namespace Microsoft.AspNetCore.Mvc. login و authorization لسه منفصلين.
  2. (2) الفورم يقدم request token مرتبط بالـ cookie token؛ AJAX يبعت token في header متفق عليه. Minimal ليها إعدادات antiforgery مختلفة حسب binding، فلا تفترض إن MVC filter بتغطيها.

Content-Security-Policy دفاع إضافي ضد XSS، مش بديل للـ encoding. Bearer header اللي JavaScript بيضيفه صراحة أقل عرضة لـ CSRF التقليدي، لكن لو حطيت token في cookie رجع نفس نمط التهديد.

#SSRF: السيرفر مش proxy لأي URLSSRF: the server must not proxy arbitrary URLs

رابط صورة من المستخدم ممكن يبقى طلب لـ cloud metadata أو خدمة داخلية. فحص string بيبدأ بـ https مش كفاية: redirects و rebinding و IPv6 و alternate formats يفتحوا مسارات تانية.

❌ حرة
var bytes = await http.GetByteArrayAsync(userSuppliedUrl, ct);
✅ حوّل الاختيار لـ ID في provider ثابت
builder.Services.AddHttpClient("product-images", client =>
    client.BaseAddress = new Uri("https://images.example.com/"))
    .ConfigurePrimaryHttpMessageHandler(() =>
        new HttpClientHandler { AllowAutoRedirect = false }); // (1)

// Endpoint fragment; imageId is a validated Guid, not a path or URL.
var client = clients.CreateClient("product-images");
using var response = await client.GetAsync(
    $"products/{imageId:N}", HttpCompletionOption.ResponseHeadersRead, ct); // (2)
response.EnsureSuccessStatusCode();
🧾 شرح الكود
  1. (1) host ثابت تحت إدارتك، و redirect مقفول عشان مايحوّلش لوجهة غير مسموحة.
  2. (2) ID typed يمنع absolute URL و path traversal؛ headers-first يتيح فحص الحجم والنوع قبل القراءة.

ضيف egress firewall أو proxy بسياسة منع private و loopback و link-local و metadata، و DNS controls، و timeouts وحد أقصى فعلي للـ streamed body حتى لو Content-Length غايب. لو business محتاج URLs حرة، محتاج validation للـ resolved destination وكل redirect واتصال، مش allowlist شكلية بس.

#Password hashing و encryption و HMACPassword hashing, encryption and HMAC

Hash عادي زي SHA-256 بصمة one-way للداتا، لكنه سريع زيادة لتخزين passwords. استخدم password hasher بطيء بملح عشوائي و work factor مناسب، زي Identity أو مكتبة Argon2id موثوقة. Salt مش سر؛ بيمنع مشاركة الحساب المسبق بين المستخدمين، لكنه مش بيمنع تخمين password ضعيفة.

الأداةالغرض
Hashبصمة؛ من غير secret مش إثبات موثوق لمصدر البيانات.
Encryptionاسترجاع plaintext بمفتاح؛ استخدم authenticated encryption من مكتبات موثوقة.
Integrity و authenticity بين أطراف بتشارك secret؛ مفيش confidentiality أو non-repudiation.
using Microsoft.AspNetCore.Identity;

var hasher = new PasswordHasher<IdentityUser>();
var storedHash = hasher.HashPassword(user, password);       // (1)
var result = hasher.VerifyHashedPassword(user, storedHash, suppliedPassword); // (2)
if (result == PasswordVerificationResult.SuccessRehashNeeded)
{
    // Persist a replacement hash through the user store after successful login.
}
🧾 شرح الكود
  1. (1) الـ framework بيولد salt ويخزن metadata للـ format والتكلفة؛ ماتعملش salt management يدوي.
  2. (2) لازم ترفض Failed. SuccessRehashNeeded نجاح مع ترقية مطلوبة؛ استخدم UserManager و SignInManager في التطبيق عشان lockout و وباقي سياسات الدخول.

ماتسجلش password أو hash في logs. تغيير work factor محتاج قياس على مواردك عشان hashing ماتتحولش لهجوم استنزاف.

#Secrets و Data Protection و dependency scanningSecrets, Data Protection and dependency scanning

Secrets في development من user-secrets، وهي مش encrypted vault. في production استخدم vault و workload identity عند الإمكان، مع صلاحيات محدودة و rotation. Environment variables اختيار نقل configuration لكنه مش مانع تسريب في dumps أو logs. سر اتعمله commit يتلغى ويتبدل فوراً؛ حذف الملف مش كفاية.

Data Protection بتحمي application state بـ encryption و integrity و purpose و key rotation. الـ instances اللي بتشارك cookies محتاجة نفس application discriminator و key ring، مع تخزين دائم وحماية keys في السكون. مش Windows DPAPI، ومش بديل تلقائي لـ KMS لتشفير أرشيف عمره سنين.

using Microsoft.AspNetCore.DataProtection;

builder.Services.AddDataProtection().SetApplicationName("Shop"); // (1)
// Production: configure persistent shared keys and encryption at rest.

public sealed class ProtectedState(IDataProtectionProvider provider)
{
    private readonly IDataProtector _protector =
        provider.CreateProtector("checkout-state.v1");           // (2)
    public string Protect(string value) => _protector.Protect(value);
    public string Unprotect(string value) => _protector.Unprotect(value);
}
# .NET 10 SDK form; include indirect dependencies too.
dotnet package list --vulnerable --include-transitive
# Older SDK form:
dotnet list package --vulnerable --include-transitive
🧾 شرح الكود
  1. (1) الاسم يوحّد عزل التطبيق، مش مكان حفظ الـ keys. حدد key storage و access control و backup قبل scale-out.
  2. (2) purpose بيفصل نوع payload؛ Unprotect يفشل لو العبث أو key غير متاحة. ماتكشفش exception details للعميل.

تشغيل vulnerability list مش معناه هتفشل تلقائياً حسب سياستك؛ افحص النتيجة أو configure NuGet audit severities وفشل warnings المطلوبة. راجع transitive dependencies ومصدر package والـ advisory وخطة التحديث، مع exceptions محدودة ومؤرخة.

#HTTPS و headers و webhook verificationHTTPS, security headers and webhook verification

يحمي النقل، و يقول للمتصفح يستخدم HTTPS في الزيارات القادمة ضمن السياسة؛ مش بديل عن ولا بيحمي أول زيارة من غير preload. وراء proxy، اضبط forwarded headers من proxies موثوقة قبل HTTPS redirection. استخدم للمصادر، و frame-ancestors ضد framing، و X-Content-Type-Options: nosniff، و Referrer-Policy مناسبة؛ اختبر السياسة بدل نسخ headers عمياني.

Webhook مش موثوقة لأنها بتقول payment succeeded. تحقق من signature على raw bytes قبل parsing، واربط timestamp بالـ signature حسب بروتوكول provider لمنع replay، وبعدها تحقق من order و amount و currency و .

using System.Security.Cryptography;

// Illustrative provider contract: hex HMAC-SHA256 over the exact raw body.
static bool Verify(byte[] rawBody, string signatureHex, byte[] secret)
{
    if (signatureHex.Length != 64) return false;             // (1)
    byte[] supplied;
    try { supplied = Convert.FromHexString(signatureHex); }
    catch (FormatException) { return false; }
    byte[] expected = HMACSHA256.HashData(secret, rawBody);   // (2)
    return CryptographicOperations.FixedTimeEquals(expected, supplied); // (3)
}
🧾 شرح الكود
  1. (1) رفض format غير صالح من غير exception تسرب تفاصيل؛ حط حد لحجم body قبل تحميلها.
  2. (2) الـ على نفس bytes؛ إعادة serialize بتغيّر التوقيع. لو provider بيوقع timestamp و body، التزم بالصيغة دي مش المثال المختصر.
  3. (3) مقارنة ثابتة الزمن للقيم الصحيحة الطول؛ TLS لسه مطلوبة لأن HMAC مش encryption.

المثال مش بيمنع replay لوحده؛ محتاج timestamp موثوق ونافذة زمنية و event ID فريدة متخزنة atomic مع الـ effect أو inbox. قارن المبلغ والعملة بالـ order من database، وماتثقش في client redirect كإثبات دفع.

أسئلة الانترفيو

راجع فهمك

ليه الاختيار ده مناسب؟ إمتى ممكن ماينفعش؟ وإيه اللي هيتغير لو الحمل زاد أو ظهر فشل؟

19.1What is the difference between authentication and authorization?Junior

الأولى إثبات الهوية، والتانية السماح بالفعل على resource معينة. Login مش إثبات ملكية invoice، و 401 غير 403.

الإجابة النموذجية (English)

I use authentication to establish who is calling and authorization to decide what that identity may do. A valid login does not imply access to every order. In an I normally challenge missing or invalid credentials with 401 and reject insufficient permission with 403, while sometimes using 404 to avoid revealing resource existence. In I establish the principal before applying endpoint policies and perform ownership and tenant checks when the decision depends on a specific resource.

19.2Are cookies and JWTs competing authentication protocols?Junior

Cookie نقل وتخزين، و format. اختار حسب client والتهديدات: automatic cookie محتاجة protection، و bearer في JavaScript معرض لـ theft.

الإجابة النموذجية (English)

I separate format from transport. is a format, while a cookie is a browser storage and delivery mechanism; a cookie can carry different session representations. Cookies are automatically attached and need defenses, while a bearer token in an Authorization header is explicitly attached but must be protected from theft. For browser applications I often consider a backend-for-frontend with HttpOnly secure session cookies, keeping provider tokens on the server while still defending against and CSRF.

19.3How do OAuth 2.0 and OpenID Connect differ?Mid

OAuth لتفويض access، و لإثبات هوية المستخدم عند client. ID مش access token للـ API.

الإجابة النموذجية (English)

I use for delegated access and OpenID Connect for user authentication on top of that framework. The access is intended for the API, while the ID token tells the client about the authenticated user. I do not send an ID token to an API as a substitute for its access token. I use a maintained provider and client , validate the intended audiences and issuers, and request only the scopes and claims the application needs.

19.4Explain authorization code with PKCE and client credentials.Mid

Code مع verifier يحمي code مسروقة؛ state و nonce ليهم أدوار تانية. Client credentials خدمة من غير مستخدم، ومينفعش secret ثابت جوه SPA.

الإجابة النموذجية (English)

For an interactive user, I use authorization code with : the client sends a challenge and later proves possession of the verifier while exchanging the returned code. That limits code interception, while state, nonce and exact redirect registration address other response-binding risks. A confidential client still authenticates itself. For machine-to-machine access without a user, I use client credentials or a platform workload identity. I never embed a confidential client secret inside a public browser or mobile application.

19.5Why avoid implicit and password grants?Mid

Implicit بتعرّض في authorization response، و password grant بتدي التطبيق password وتكسر فصل الهوية و . Security BCP بتحظر password grant.

الإجابة النموذجية (English)

I avoid implicit flow because returning access through the authorization response increases leakage and replay exposure. Authorization code with provides a better exchange model. I also reject the password grant, which requires the client to collect the user's password and does not fit modern authentication such as passkeys and provider-managed . The OAuth security best current practice prohibits that grant. I redirect users to a trusted provider instead of building a new password-collection flow into each application.

19.6Is a JWT encrypted, and what must an API validate?Junior

Signed المعتادة مش encrypted؛ validate signature و issuer و audience و lifetime والخوارزمية المسموحة. Decode بس مش validation.

الإجابة النموذجية (English)

I treat the usual signed as readable data, not encrypted storage. Its header and payload are Base64Url-encoded, and the signature protects integrity under a trusted key. The validates the signature, accepted algorithms, issuer, audience and lifetime with an intentional clock-skew allowance. I obtain keys through trusted provider metadata and support rotation rather than accepting arbitrary -supplied keys. Decoding a token is only inspection; it does not establish that the claims are trustworthy.

19.7How do refresh-token rotation and access-token revocation work?Senior

Rotation تستهلك refresh وتطلع بديل atomic، و reuse يتراجع حسب provider policy. Access token offline تفضل صالحة لحد expiry إلا لو ضفت state لفحص الإلغاء.

الإجابة النموذجية (English)

I keep access- lifetimes bounded and rotate refresh tokens through an atomic consume-and-replace operation. Reuse detection can revoke the token family under the provider's policy, with deliberate handling of concurrent refresh attempts. Revoking a refresh token prevents future renewal but does not instantly invalidate an already issued access token in an offline-validating . Immediate revocation needs an additional mechanism, such as introspection or a denylist, which adds , state and availability trade-offs.

19.8What do ASP.NET Core Identity and passkeys provide?Mid

Identity إدارة حسابات، مش OAuth server كاملة. 10 فيها WebAuthn passkeys؛ السيرفر يحتفظ public key، مش بصمة ولا private key.

الإجابة النموذجية (English)

I use Identity for account management, password hashing, roles, lockout and related login facilities, rather than treating it as a complete OAuth authorization server. 10 adds WebAuthn passkey support. The server stores a public key and verifies a fresh challenge signed by the user's authenticator, with origin and relying-party binding. Biometrics authorize local key use and are not sent to the server. I also design credential recovery carefully because weak recovery can undermine strong login.

19.9How do roles, claims, policies and resource authorization relate?Mid

Roles تصنيف، و claims assertions، و policies requirements. قرار ملكية الطلب وحالته محتاج resource authorization، مش role لوحدها.

الإجابة النموذجية (English)

I use roles for broad classifications and claims for trusted assertions such as permissions or tenant identity. Policies express requirements without scattering checks across endpoints. When permission depends on the specific object, I use resource-based authorization through a handler or an explicitly scoped query. For example, editing an order can require both an edit permission and ownership while the order is pending. I enforce the same boundary in background jobs and exports rather than relying only on controller attributes.

19.10How do you prevent cross-tenant data leakage?Senior

Tenant موثوق، و queries و writes scoped، و policies و cache و files و messages معزولة. اختبر tenant A ضد IDs بتاعة B، بما فيها admin و raw .

الإجابة النموذجية (English)

I establish tenant identity from a trusted authenticated context and authorize any tenant selection. Queries and writes remain tenant-scoped, with resource checks where needed. I extend to cache keys, storage paths, exports and message handlers. Database filters help, but raw , administrative bypasses and unfiltered relationships still require review. I add tests where one tenant supplies another tenant's identifiers, including update and bulk paths, because an unpredictable identifier alone is not an access-control boundary.

19.11How do you prevent SQL injection in .NET?Junior

Parameters مش concatenation. أو FromSql بـ interpolation مباشرة، و identifiers من allowlist. Validation و least privilege طبقات إضافية.

الإجابة النموذجية (English)

I keep values separate from syntax using parameters, usually through or a parameterized command. If I use EF FromSql, I pass the interpolated expression directly so it remains parameterized instead of building a string for FromSqlRaw. Parameters cannot represent identifiers such as column names, so dynamic sorting uses a fixed allowlist. Input validation and a least-privileged database account add protection, but neither replaces correct parameterization.

19.12What is XSS and how do you mitigate it?Mid

Script من المهاجم تشتغل على أصل الموقع. Contextual encoding و تجنب Raw و innerHTML و sanitizer للمحتوى الغني، مع كطبقة إضافية.

الإجابة النموذجية (English)

I treat as attacker-controlled script execution in the application's origin. I use context-appropriate encoding, keep Razor's default encoding and avoid unsafe sinks such as Html.Raw or innerHTML for untrusted content. Rich needs a maintained sanitizer, and a restrictive Content Security Policy adds defense in depth. HttpOnly cookies reduce direct reading but do not stop malicious script from issuing authenticated requests. I therefore protect the rendering path rather than relying on cookie flags alone.

19.13What is CSRF and does CORS prevent it?Mid

موقع مهاجم يستغل cookie بتتبعت تلقائياً. Antiforgery للـ unsafe requests، و SameSite، و GET من غير mutations. مش منع كامل لإرسال الطلب.

الإجابة النموذجية (English)

I consider when the browser automatically attaches credentials, especially session cookies. An attacker can cause a victim's browser to submit a state-changing request without reading its response. I validate antiforgery , use suitable SameSite settings and avoid state changes through GET. governs cross-origin browser access but is not a complete CSRF defense, since some requests can still be sent. Explicit bearer headers change the threat model, while storing that bearer token in a cookie restores automatic attachment.

19.14How do you defend against SSRF?Senior

قلل arbitrary URLs لصالح IDs مع destinations ثابتة، واقفل redirects، و egress controls و والتحقق من resolved IPs، وحدود حجم ووقت.

الإجابة النموذجية (English)

I avoid accepting arbitrary URLs when a typed identifier for a fixed service will meet the requirement. For outgoing fetches I constrain destinations, disable or revalidate redirects and enforce network egress rules against internal and metadata addresses. I account for rebinding, IPv6 and resolved addresses rather than checking only the text. Timeouts, response-size limits and bounded concurrency also matter. When arbitrary fetching is unavoidable, I isolate it behind a deliberately restricted proxy or service boundary.

19.15How should passwords be stored?Junior

Salted slow hashing بـ Identity hasher أو implementation موثوقة، مش reversible encryption ولا SHA-256 لوحدها. استخدم login manager لباقي السياسات.

الإجابة النموذجية (English)

I store passwords with a maintained, salted password-hashing implementation such as Identity's hasher, with an appropriate work factor. I do not store plaintext, reversible encryption or a fast general hash such as bare SHA-256. The stored format includes the information needed for verification and upgrades. I use the account framework for lockout and , never log passwords or hashes, and measure hashing cost so stronger settings remain sustainable under login traffic and abuse.

19.16How do hashing, encryption, HMAC and Data Protection differ?Mid

Hash بصمة، و encryption استرجاع بمفتاح، و integrity بسر مشترك. Data Protection stack لحماية state وإدارة keys، ومحتاج persistence وحماية key ring.

الإجابة النموذجية (English)

I use a hash for a one-way fingerprint, encryption when authorized code must recover the original data, and to authenticate data shared between secret holders. A plain hash does not authenticate the sender, and HMAC does not encrypt. Data Protection packages encryption, integrity, purposes and key rotation for application state such as cookies. In a multi-instance deployment I configure persistent shared keys and protection at rest, and I do not assume it replaces every long-term encryption requirement.

19.17How do you verify a payment webhook safely?Senior

وقّع raw bytes حسب provider contract، و constant-time comparison، و timestamp موقعة لمنع replay، و event ID unique، وبعدها amount و currency و order من المصدر.

الإجابة النموذجية (English)

I verify the provider's exact signature contract over the raw request bytes before , with bounded body size and constant-time comparison for valid signatures. I validate an authenticated timestamp where the protocol provides one and deduplicate event IDs atomically with processing. Then I compare the order, amount and currency against authoritative data and apply only valid state transitions. remains necessary, and I never treat a client redirect as payment proof. Failed deliveries need monitored retries and reconciliation.

19.18How do you manage secrets and vulnerable dependencies?Senior

Vault و workload identity و rotation، و secrets من غير Git أو logs. Scan direct و transitive، وحدد policy فعلية بدل مجرد طباعة warnings.

الإجابة النموذجية (English)

I keep secrets out of source control, use development user-secrets locally and prefer a production vault with workload identity and least privilege. Exposed credentials are revoked and rotated immediately. For dependencies I inspect direct and transitive vulnerabilities, package provenance and maintained versions, then enforce an explicit policy rather than assuming a listing command blocks releases. Exceptions have owners and expiry dates. I also protect build credentials and artifact publication, since dependency security includes the supply chain rather than package versions alone.

اختبر نفسك

إجابات الاختبار وعلامات إكمال المحاور بتتحفظ على المتصفح ده، ومش بتتنقل لأجهزة تانية.

النتيجة: 0 / 0

A valid login can read another user's invoice by changing an ID. Which failure?

الهوية صحيحة لكن فحص الملكية ناقص.

Which token should an API normally accept from an OIDC client?

Audience والغرض مختلفين؛ ID للـ client.

What does PKCE primarily protect against?

Verifier يربط تبادل code بالعميل اللي بدأ العملية.

What is true of a typical signed JWT payload?

Encoding مش encryption، و decoding مش validation.

Which password storage approach is appropriate?

الـ salt والـ work factor يقللوا فعالية التخمين offline.

Why does an HttpOnly cookie not eliminate XSS risk?

منع قراءة cookie مش منع استخدام جلسة المستخدم.

Which defense directly addresses cookie-authenticated CSRF?

المهاجم يقدر يسبب إرسال cookie، لكنه مايعرفش request الصحيح.

Why disable redirects when fetching from an allowed external service?

كل وجهة فعلية محتاجة نفس سياسة منع .

What is stored by the server during passkey registration?

Private key بتستخدمها authenticator للتوقيع؛ البصمة محلية.

A valid HMAC webhook is replayed tomorrow. What additional control matters?

يثبت سلامة الرسالة مش إنها جديدة.