Skip to content

Authentication: Passwords & Hashing, MFA, Sessions vs Tokens ​

"Verifiers and CSPs SHALL NOT require subscribers to change passwords periodically. However, verifiers SHALL force a change if there is evidence that the authenticator has been compromised." — NIST، SP 800-63B-4: Digital Identity Guidelines, Authentication and Authenticator Management، بخش 3.1.1.2 (Password Verifiers)، ژوئیهٔ ۲۰۲۵

خلاصه (Summary): احراز هویت (Authentication) سیستمی است که «کسی یک ایمیل تایپ کرد» را به «این درخواست مال حساب ۴۲ است، با این عامل‌ها و در این زمان ثابت شده» تبدیل می‌کند. چهار بخش دارد که باید با هم طراحی شوند: رمزها چطور ذخیره می‌شوند (Argon2id، bcrypt، pepper)، حدس زدن چطور متوقف می‌شود (throttling، خطای یکسان، بررسی رمزهای لورفته)، عامل دوم چطور اضافه می‌شود (TOTP، passkey، کدهای بازیابی) و اثبات بعد از ورود چطور حمل می‌شود (session سمت سرور، JWT، توکن opaque، refresh token). تمرکز (Focus): تفاوت هویت، احراز هویت و مجوزدهی؛ سیاست رمز بر اساس NIST SP 800-63B-4؛ پارامترهای Argon2id/scrypt/bcrypt/PBKDF2 با هزینهٔ اندازه‌گیری‌شده؛ pepper و rehash هنگام ورود؛ credential stuffing، password spraying، enumeration و timing attack؛ محدودیت نرخ به‌ازای حساب و IP؛ lockout در برابر تأخیر تدریجی؛ CAPTCHA و احراز هویت مبتنی بر ریسک؛ MFA و سطح‌های AAL؛ TOTP/HOTP (RFC 6238/4226) با drift window و جلوگیری از replay؛ SMS/email OTP، push و MFA fatigue؛ passkeyهای WebAuthn/FIDO2 (ceremonyها، attestation، discoverable credential، synced passkey)؛ کدهای بازیابی؛ session در برابر JWT در برابر توکن opaque با introspection؛ چرخش refresh token و تشخیص استفادهٔ مجدد؛ DPoP؛ بازنشانی رمز؛ remember me؛ logout everywhere؛ step-up authentication؛ رخدادهای ممیزی؛ و محصولات: Laravel Fortify/Sanctum/Passport، Keycloak، Auth0، Okta، Cognito، Ory، go-webauthn، pquerna/otp. هدف یادگیری (Learning goal): یک سیستم ورود را از فرم رمز تا آخرین logout طراحی کنید: پارامترهای hash را از روی عدد انتخاب کنید، همهٔ شکست‌ها را یک‌شکل کنید، جلوی حدس آنلاین را بگیرید بی‌آنکه مهاجم بتواند کاربر واقعی را قفل کند، یک عامل دوم مقاوم در برابر فیشینگ با مسیر بازیابی اضافه کنید، برای هر نوع کلاینت بین session و توکن انتخاب کنید، و کاری کنید که «بازنشانی رمز» و «خروج از همه‌جا» واقعاً همهٔ sessionها را تمام کنند.

این فصل نگاه طراحی سیستم به احراز هویت است: تصمیم‌ها، عددها و جریان‌ها. عمق موضوعات همسایه در صفحهٔ خودشان می‌ماند: Password Hashing & Signed Tokens درون bcrypt و Argon2 و امضای توکن را درس می‌دهد؛ Web Sessions, Cookies, Serialization & CORS ویژگی‌های cookie، CSRF و CORS را؛ JWT Deep Dive ساختار، الگوریتم‌ها و اعتبارسنجی JWT را؛ OAuth 2.0, OpenID Connect & Single Sign-On ورود تفویضی و SSO را؛ Authorization Models تصمیم می‌گیرد کاربرِ احرازشده چه کاری مجاز است؛ Mutual TLS & Securing Service-to-Service Traffic ماشین‌ها را احراز می‌کند؛ Rate Limiting الگوریتم‌های محدودکننده را؛ Authentication in Go راهنمای عملی فقط-Go است؛ و Security Foundations چارچوب مدل‌سازی تهدید را می‌دهد.

نقشهٔ صفحه ​

اگر دنبال این هستیدبروید به
کل صفحه در سه جدولهمه‌چیز در یک دقیقه
چرا احراز هویت یک سیستم است، نه یک فرمچرا وجود دارد
از crypt در Unix تا NIST SP 800-63B-4 و passkeyاز کجا آمده
هویت در برابر احراز هویت در برابر مجوزدهیهویت، احراز هویت، مجوزدهی
طول، blocklist، بدون قواعد ترکیب، بدون تعویض دوره‌ایسیاست رمز
Argon2id، scrypt، bcrypt، PBKDF2 و پارامترهایشانhash کردن رمز
salt، pepper، rehash هنگام ورود، مهاجرت hashهای قدیمیPepper و rehash
brute force، credential stuffing، password sprayingحمله‌های آنلاین
«حسابی با این ایمیل نداریم»، تفاوت زمان پاسخEnumeration و timing
محدودیت به‌ازای حساب و IP، lockout، CAPTCHA، امتیاز ریسکThrottling و lockout
عامل‌ها، AAL1/2/3، مقاومت در برابر فیشینگMFA
TOTP/HOTP، QR، drift window، replayTOTP و HOTP
SMS، ایمیل، push، SIM swap، MFA fatigueSMS، ایمیل و push
ceremonyهای WebAuthn، attestation، passkeyWebAuthn و passkey
کدهای بازیابی و بازیابی حساببازیابی
session سمت سرور و cookieSessionها
JWT، توکن opaque، introspectionتوکن‌ها
چرخش refresh token، تشخیص استفادهٔ مجدد، DPoPRefresh token
جریان «رمز را فراموش کرده‌ام»بازنشانی رمز
remember me، logout everywhere، step-upچرخهٔ عمر session
SSO، OAuth، سرویس به سرویسSSO و ماشین‌ها
چه چیزی را ثبت کنیمممیزی
قالب hashها، زمان‌ها، تنظیم‌ها، پیام‌های خطاسازوکار
کدGo، Laravel
یازده خرابی کلاسیک و راه‌حلشانحل مسئله‌های کلاسیک
کدام hash، کدام عامل، session یا توکن، ساختن یا خریدنانتخاب
از monolith تا چند regionدر معماری
زمان‌سنجی اجراشدنی و آزمایش‌های موردانتظارآزمایشگاه
باورهای غلط، خلاصه، آزمون، واژه‌هابدفهمی‌ها، چکیده، خودآزمایی، واژه‌نامه

همه‌چیز در یک دقیقه ​

ذخیرهٔ رمزها.

انتخابپارامترهای شروعکی استفاده شودمراقب باشید
Argon2idحداقل OWASP یعنی m=19 MiB، t=2، p=1؛ گزینهٔ دوم RFC 9106 یعنی m=64 MiB، t=3، p=4سیستم‌های جدیدحافظه به‌ازای هر ورود: 64 MiB x 50 ورود هم‌زمان = 3.2 GB
scryptN=2^17، r=8، p=1 (OWASP)وقتی Argon2id در دسترس نیستهمان برنامه‌ریزی حافظه
bcryptحداقل cost 10 (OWASP)؛ 12 پیش‌فرض Laravel و PHP 8.4 به بعدسیستم قدیمی یا نبودِ Argon2فقط ۷۲ بایت اول حساب می‌شود
PBKDF2-HMAC-SHA256600,000 تکرار (OWASP)وقتی رمزنگاری تأییدشدهٔ FIPS 140 الزامی استmemory-hard نیست؛ GPUها عاشقش‌اند
Pepper۳۲ بایت تصادفی در KMS/HSM، HMAC پیش از hashدفاع در برابر نشتِ فقط پایگاه دادهچرخاندنش نیاز دارد هر کاربر یک بار وارد شود یا رمز را بازنشانی کند
SHA-256، MD5، متن سادههرگزهرگزمیلیاردها حدس در ثانیه روی هر GPU

متوقف کردن حدس زدن.

حملهچه شکلی استدفاع اصلی
Brute forceرمزهای زیاد، یک حسابthrottling به‌ازای حساب، رمز بلند، MFA
Credential stuffingجفت ایمیل/رمزِ لورفته از سایت‌های دیگر، حساب‌های زیاد، IPهای زیادبررسی رمز لورفته، MFA، تشخیص bot، سیگنال‌های per-IP و سراسری
Password sprayingیک رمز رایج («Winter2026!») روی حساب‌های زیادblocklist رمزهای رایج، محدودیت per-IP، هشدار نرخ شکست سراسری
Enumeration«حسابی با این ایمیل نداریم»، پاسخ سریع‌تر برای کاربر ناموجودپیام یکسان، status یکسان، hash ساختگی، زمان یکسان
فیشینگ / proxy بلادرنگصفحهٔ جعلی رمز و OTP را رله می‌کندpasskey/WebAuthn (وابسته به origin)، نه OTP
MFA fatigueده‌ها درخواست push ساعت دو بامدادnumber matching، محدودیت push، passkey

حمل اثبات.

سازوکاروضعیت کجاستابطالبهترین کاربرد
Session سمت سرور + cookieRedis یا جدول sessionsحذف ردیف: فوریاپ‌های مرورگری روی دامنهٔ خودتان
Access token بی‌حالت JWTداخل خود توکن (claimهای امضاشده)باید تا exp صبر کرد (یا deny list)سرویس به سرویس، کوتاه‌عمر (۵ تا ۱۵ دقیقه)
Access token opaque + introspectionAuthorization serverفوری (یا TTL کش)APIهای شخص ثالث، scopeهای پرارزش
Refresh token با چرخشAuthorization server، یک ردیف به‌ازای هر توکنابطال familyکلاینت‌های موبایل و SPA که باید وارد بمانند
Personal access token در Sanctumpersonal_access_tokens (SHA-256)حذف ردیفکلیدهای API در Laravel، اپ موبایل first-party

چرا وجود دارد ​

هر درخواستی که به سرور می‌رسد چند بایت بی‌نام است. احراز هویت مرحله‌ای است که با درجه‌ای از اطمینان یک حساب را به این بایت‌ها می‌چسباند و بعد این اتصال را برای هزار درخواست بعدی ارزان نگه می‌دارد. این کار باید هم‌زمان در برابر سه نوع دشمن جواب بدهد: کسی که آنلاین حدس می‌زند (روی فرم ورود رمز امتحان می‌کند)، کسی که پایگاه داده را دزدیده (و آفلاین با سرعت GPU حدس می‌زند)، و کسی که کاربر را فریب می‌دهد (فیشینگ، SIM swap، خسته کردن با push). انتخابی که جلوی یکی را می‌گیرد اغلب به دیگری کمک می‌کند: lockout سخت حدس زدن را متوقف می‌کند ولی به هر کسی اجازه می‌دهد مدیرعامل را بیرون نگه دارد؛ JWT بلندمدت یک lookup را صرفه‌جویی می‌کند ولی قابل ابطال نیست.

ساده‌تر، ارزان‌ترقوی‌تر، پرهزینه‌تر
hash سریع، بدون pepperArgon2id با حافظهٔ تنظیم‌شده، pepper در KMS
فقط رمزرمز + TOTP، یا یک passkey به‌تنهایی (دو عامل در یک حرکت)
JWT بی‌حالت بلندمدتJWT کوتاه + refresh token چرخشی، یا session سمت سرور
پیام خطای جزئییک پیام عمومی و جزئیات در لاگ ممیزی
قفل کردن حساب بعد از ۵ شکستتأخیر تدریجی، محدودیت per-IP، امتیاز ریسک، خبر دادن به کاربر
ایمیل لینک بازنشانی با شناسهٔ کاربرتوکن یک‌بارمصرف، hash‌شده، کوتاه‌عمر؛ ابطال sessionها بعد از آن

تمثیلی که در کل صفحه استفاده می‌شود: هتل. پذیرش یک بار گذرنامهٔ شما را بررسی می‌کند (احراز هویت) و یک کارت‌کلید می‌دهد (session یا توکن). کارت اتاق شما و باشگاه را باز می‌کند، نه دفتر مدیر را (مجوزدهی). پذیرش دفتری دارد که می‌گوید کدام کارت‌ها معتبرند، پس کارت گمشده فوراً باطل می‌شود (session سمت سرور)؛ برگهٔ چاپی‌ای که روی آن نوشته «اتاق ۳۰۵، معتبر تا جمعه» بدون دفتر هم کار می‌کند ولی باطل‌شدنی نیست (JWT بی‌حالت). نسخهٔ اصلی فهرست مهمان‌ها در گاوصندوق است (hash رمزها) و رمز گاوصندوق در ساختمان دیگری نگه‌داری می‌شود (pepper).

سه بدفهمی رایج، از همین اول ​

  1. «رمز قوی یعنی حرف بزرگ، عدد و نماد، و تعویض هر ۹۰ روز.» NIST SP 800-63B-4 دقیقاً برعکس می‌گوید: verifierها "SHALL NOT impose other composition rules" و "SHALL NOT require subscribers to change passwords periodically". کاربران به قواعد ترکیب با Password1! جواب می‌دهند؛ طول و blocklist بهتر کار می‌کنند.
  2. «MFA فیشینگ را غیرممکن می‌کند.» کد شش‌رقمی‌ای که در صفحهٔ جعلی تایپ شود بلادرنگ رله می‌شود؛ NIST می‌گوید authenticatorهای OTP و out-of-band "SHALL NOT be considered phishing-resistant". فقط authenticatorهای رمزنگاری که به origin گره خورده‌اند (WebAuthn، گواهی کلاینت) مقاوم‌اند.
  3. «JWT از session امن‌تر است.» این یک معاملهٔ دیگر است: lookup ندارد ولی logout فوری هم ندارد. برای مرورگری که با backend خودش حرف می‌زند، session سمت سرور در یک cookie با HttpOnly معمولاً پیش‌فرض امن‌تر است.

از کجا آمده ​

  • ۱۹۷۹، crypt در Unix. مقالهٔ Morris و Thompson با عنوان "Password Security: A Case History" hash کردن کند و salt‌دار را در Unix معرفی کرد (تاریخ از منبع ثانویه است؛ اصل آن در همهٔ طرح‌های امروزی زنده است).
  • ۱۹۹۹، bcrypt. bcrypt از Provos و Mazières یک «ضریب هزینه» (Cost factor) قابل‌تنظیم اضافه کرد. محدودیت ورودی ۷۲ بایتی‌اش هنوز مهم است: bcrypt.GenerateFromPassword در Go خطای ErrPasswordTooLong ("password length exceeds 72 bytes") برمی‌گرداند، در حالی که password_hash در PHP 8.5 بقیه را بی‌صدا نادیده می‌گیرد (هر دو را آزمودیم؛ سازوکار را ببینید).
  • ۲۰۰۵ و ۲۰۱۱، HOTP و TOTP. RFC 4226 رمز یک‌بارمصرف مبتنی بر HMAC را تعریف کرد؛ RFC 6238 آن را زمان‌محور کرد و "default time-step size of 30 seconds" را توصیه کرد. Google Authenticator آن را همه‌گیر کرد.
  • ۲۰۰۹ و ۲۰۱۷، scrypt و راهنمای PBKDF2. scrypt مفهوم memory-hard را آورد؛ PBKDF2 گزینهٔ تأییدشدهٔ FIPS ماند و به همین دلیل OWASP هنوز آن را "if FIPS-140 compliance is required" فهرست می‌کند.
  • ۲۰۱۵ تا ۲۰۲۱، Argon2. Argon2 برندهٔ Password Hashing Competition شد (۲۰۱۵)؛ RFC 9106 (سپتامبر ۲۰۲۱) آن را استاندارد کرد و Argon2id با "t=1 iteration, p=4 lanes, m=2^(21) (2 GiB of RAM)" را گزینهٔ اول و 64 MiB با t=3 را گزینهٔ دوم توصیه می‌کند.
  • ۲۰۱۷، NIST SP 800-63B (ویرایش ۳). قواعد ترکیب و تعویض اجباری را کنار گذاشت و blocklist رمزهای لورفته را آورد. ژوئیهٔ ۲۰۲۵، SP 800-63B-4 (نهایی، طبق CSRC منتشرشده در ۳۱ ژوئیهٔ ۲۰۲۵) حداقل رمز تک‌عاملی را به "a minimum of 15 characters" رساند، PSTN (پیامک و تماس صوتی) را authenticator «محدودشده» (Restricted) کرد، authenticatorهای syncable (passkeyها) را اضافه کرد و مقاومت در برابر فیشینگ را دقیق تعریف کرد.
  • ۲۰۱۹ تا ۲۰۲۶، WebAuthn. W3C Web Authentication سطح ۱ (۲۰۱۹)، سطح ۲ (۲۰۲۱) و سطح ۳ که W3C Recommendation به تاریخ ۲۵ اوت ۲۰۲۶ است و APIای برای "strong, attested, scoped, public key-based credentials" تعریف می‌کند. FIDO Alliance و سازندگان سیستم‌عامل‌ها credentialهای WebAuthn قابل‌کشف و همگام‌شونده را با نام passkey عرضه کردند.
  • ۲۰۱۲ تا ۲۰۲۵، توکن‌ها. OAuth 2.0 (RFC 6749، ۲۰۱۲) refresh token را آورد؛ RFC 7662 (۲۰۱۵) token introspection؛ RFC 8471 (۲۰۱۸) Token Binding؛ RFC 9449 (۲۰۲۳) DPoP؛ و RFC 9700 (ژانویهٔ ۲۰۲۵)، یعنی OAuth 2.0 Security Best Current Practice، الزام می‌کند که "Refresh tokens for public clients MUST be sender-constrained or use refresh token rotation".

فهرست مفاهیم ​

هر بلوک یک ترتیب ثابت دارد: به زبان ساده، باور غلط رایج، تعریف، خط زمانی، سناریوهای واقعی، رفتار محصولات، و راه درست.

POST /login: one pipeline, one failure message1. Throttleper account keyper client IPbefore any hashing429 + Retry-After2. Look upnormalise emailusers tablefound or not found3. Verify hashArgon2id / bcryptconstant-time compareunknown user:verify a dummy hash4. Second factorpark login.idTOTP, passkey orrecovery codeown rate limit5. Establishnew session IDor token pairrehash if staleaudit eventSame response for every failure"Invalid email or password." for every account; 429 only when throttledThe client never learns which step failed; the audit log does.

تصویر بالا مسیر یک درخواست ورود را نشان می‌دهد: اول throttling پیش از هر کار سنگین، بعد جست‌وجوی کاربر، بعد بررسی hash (برای کاربر ناموجود با یک hash ساختگی)، بعد عامل دوم، و در پایان ساختن session یا توکن، rehash و ثبت رخداد. همهٔ مسیرهای شکست به یک پیام واحد ختم می‌شوند.

هویت، احراز هویت، مجوزدهی حیاتی ​

به زبان ساده: هویت (Identity) یعنی شما در سیستم چه کسی هستید (حساب ۴۲ با ایمیل، نام و ویژگی‌ها)؛ احراز هویت (Authentication) یعنی اثبات اینکه درخواست فعلی از همان هویت آمده؛ مجوزدهی (Authorization) یعنی تصمیم دربارهٔ اینکه آن هویت الان چه کاری مجاز است.

بدفهمی رایج: «کاربر وارد شده، پس درخواست مجاز است.» احرازشده بودن هیچ چیزی دربارهٔ اینکه حساب ۴۲ اجازهٔ خواندن فاکتور ۹۰۰۱ را دارد نمی‌گوید. قاطی کردن این دو باگ IDOR (Insecure Direct Object Reference) می‌سازد: ورود کاملاً درست کار می‌کند و هر کاربری همهٔ فاکتورها را می‌خواند.

تعریف: هویت (در NIST: subscriber account) مجموعه‌ای از ویژگی‌هاست که به یک شخص یا سرویس گره خورده. Credential یا Authenticator چیزی است که مدعی در اختیار دارد (رمز، secret مربوط به TOTP، کلید خصوصی). احراز هویت بررسی می‌کند که مدعی authenticatorهای متصل به حساب را در اختیار دارد و یک رخداد احراز هویت با زمان و مجموعهٔ روش‌ها می‌سازد (RFC 8176 آن‌ها را pwd، otp، hwk، mfa، sms و ... می‌نامد). یک Session این رخداد را جلو می‌برد. بعد مجوزدهی سیاست (RBAC، ABAC، ReBAC) را روی هویت و منبع ارزیابی می‌کند.

text
     Request                                   Layer            Answer
1    POST /login email=ada@... password=...    authentication   account 42, amr=[pwd], auth_time=09:00
2    Set-Cookie: __Host-session=opaque          session          the proof is now carried by the cookie
3    GET /invoices/9001  (cookie)               session lookup   account 42, authenticated at 09:00
4    policy: invoice.owner == 42 ?              authorization    no -> 403 (not 401)
5    POST /settings/email (cookie)              step-up check    auth_time 09:00 is 40 min old -> ask again

سناریوی واقعی: یک SaaS سازمانی که در آن SSO از طریق Okta کارمند را احراز می‌کند ولی خود اپ تصمیم می‌گیرد آیا او مدیر tenant شمارهٔ ۱۷ هست یا نه؛ کارمند پشتیبانی که خود را جای کاربر می‌گذارد (به‌عنوان کارمند احراز، به‌عنوان کاربر مجاز، و به‌عنوان هر دو ممیزی می‌شود)؛ اپ بانکی موبایل که وارد شده ولی برای انتقال پول اسکن تازهٔ چهره می‌خواهد (step-up)؛ کلید APIای که سرور یک شریک را احراز می‌کند ولی فقط به orders:read محدود است.

چه چیزی آن را فراهم می‌کند:

موضوع401 یا 403نمونهٔ محصول
احراز نشده401 Unauthorized (برای API همراه WWW-Authenticate)middleware auth در Laravel redirect می‌کند یا 401 می‌دهد؛ middleware در Go
احراز شده، مجاز نیست403 ForbiddenGate/Policy در Laravel، OPA، Cedar، OpenFGA
احراز شده ولی نه به‌تازگی401 یا redirect برای احراز دوبارهpassword.confirm در Laravel، max_age/acr_values در OIDC
ارائه‌دهندهٔ هویت—Keycloak، Auth0، Okta، Amazon Cognito، Ory Kratos، Microsoft Entra ID

راه درست: سه ماژول جدا نگه دارید: انبار هویت (کاربران، credentialها)، احرازکننده (خروجی‌اش user_id، amr، auth_time است) و مجوزدهنده (policyها). نتیجهٔ احراز را به‌صورت یک struct کوچک پاس بدهید، نه «شیء کاربر»، تا کدی که به تازگی یا نوع عامل نیاز دارد بتواند آن را بررسی کند. مجوزدهی موضوع Authorization Models است.

سیاست رمز (NIST SP 800-63B-4) حیاتی ​

به زبان ساده: طول بخواهید، رمز را با فهرستی از رمزهای بد شناخته‌شده مقایسه کنید و همان‌جا بایستید. بگذارید مردم paste کنند، فاصله و emoji بگذارند و ببینند چه تایپ کرده‌اند.

بدفهمی رایج: «قواعد ترکیب (Composition rules) و تعویض ۹۰روزه رمز را قوی‌تر می‌کنند.» پیوست NIST توضیح می‌دهد که کاربران "in very predictable ways" واکنش نشان می‌دهند: password می‌شود Password1 و بعد Password1!. تعویض دوره‌ای (Rotation) هم Spring2026! و بعد Summer2026! تولید می‌کند.

تعریف: قواعد password verifier در SP 800-63B-4، با نقل از بخش 3.1.1.2:

قاعدهعبارت NIST SP 800-63B-4
حداقل طول"a minimum of 15 characters" برای استفادهٔ تک‌عاملی؛ دست‌کم هشت وقتی رمز فقط بخشی از MFA است
حداکثر طول"SHOULD permit a maximum password length of at least 64 characters"
مجموعهٔ نویسه"SHOULD accept Unicode"؛ هر code point یک نویسه حساب می‌شود؛ پیش از hash با NFC نرمال کنید
ترکیب"SHALL NOT impose other composition rules (e.g., requiring mixtures of different character types)"
تعویض دوره‌ای"SHALL NOT require subscribers to change passwords periodically" ولی با وجود شواهد نشت "SHALL force a change"
Blocklist"SHALL compare the prospective secret against a blocklist that contains known commonly used, expected, or compromised passwords" (کل رمز، نه زیررشته‌ها)
راهنما و KBA"SHALL NOT prompt subscribers to use knowledge-based authentication (KBA)" یا سؤال امنیتی
بریدن رمز"SHALL verify the entire submitted password (e.g., not truncate it)"
نمایش رمز"SHOULD offer an option to display the password" هنگام تایپ
مدیر رمزاجازهٔ paste و autofill (پیوست usability)
text
     User types                        Old policy (8 chars, 1 upper, 1 digit, 1 symbol)   NIST SP 800-63B-4 (15 chars + blocklist)
1    "Password1!"                      accepted                                           rejected: in breach corpus
2    "correct horse battery staple"    rejected: no uppercase, no digit                   accepted
3    "Summer2026!" (rotation month 3)  accepted                                           rejected: too short, common pattern
4    "🔑 my keys live in the blue bowl" rejected: emoji not allowed                      accepted, NFC-normalised, 30 code points

سناریوی واقعی: صفحهٔ ثبت‌نامی که passphrase را رد می‌کرد و کاربران را به Company2026! هل می‌داد؛ بانکی که قاعدهٔ «حداکثر ۱۲ نویسه» مدیرهای رمز را می‌شکست؛ پرتال کارمندی با تعویض ۹۰روزه که یک‌سوم تماس‌های help desk آن بازنشانی رمز بود؛ رمزی که در فهرست RockYou بود و در اولین دور spraying افتاد.

چه چیزی آن را فراهم می‌کند:

محصولطول و blocklistنکته
قاعدهٔ Password در LaravelPassword::min(15)->max(128)->uncompromised()uncompromised() از API محدوده‌ای k-Anonymity در haveibeenpwned.com استفاده می‌کند (پنج نویسهٔ اول SHA-1، Add-Padding: true)؛ mixedCase() و symbols() وجود دارند ولی NIST می‌گوید استفاده نکنید
Have I Been Pwned Pwned PasswordsGET https://api.pwnedpasswords.com/range/{first 5 SHA-1 chars}رایگان، k-anonymity، قابل mirror آفلاین
سیاست رمز Keycloakطول، "Not Recently Used"، فایل "Password Blacklist"، و قواعد ترکیب (خاموششان کنید)به‌ازای realm
Amazon Cognitoحداقل طول، کلاس‌های نویسهٔ اختیاری، محافظت در برابر credential لورفته در قابلیت‌های threat protectionبه‌ازای user pool
Auth0سطح‌های قدرت رمز، Breached Password Detectionتنظیم tenant

راه درست: حداقل ۱۵ (یا ۸ وقتی MFA برای همه اجباری است)، حداکثر دست‌کم ۶۴ نویسه (کد Go این فصل برای جلوگیری از حملهٔ منع سرویس سقف 1024 بایت می‌گذارد)، نرمال‌سازی NFC، بررسی blocklist هنگام تعیین و تغییر رمز، نمایشگر قدرت رمز به‌عنوان راهنما، autocomplete="new-password" و دکمهٔ نمایش رمز. بازنشانی اجباری فقط با شاهد: تطابق با نشت، نشت شناخته‌شده، یا موفقیت stuffing تشخیص‌داده‌شده.

hash کردن رمز: Argon2id، scrypt، bcrypt، PBKDF2 حیاتی ​

به زبان ساده: به‌جای رمز، یک اثر انگشت کند و salt‌دار از آن نگه دارید. «کند» یعنی هر حدس، وقتی مهاجم پایگاه داده را دارد، برایش CPU و حافظهٔ واقعی خرج دارد.

بدفهمی رایج: «SHA-256 یک hash امن است، پس برای رمز هم خوب است.» SHA-256 برای سریع بودن طراحی شده و این دقیقاً اینجا غلط است. hash رمز باید عمداً گران باشد، و Argon2id و scrypt memory-hard هم هستند، پس GPU با هزاران هسته نمی‌تواند هزاران حدس را ارزان و موازی اجرا کند.

تعریف: یک طرح hash رمز، رمز، یک salt تصادفی مخصوص هر کاربر و یک هزینه را می‌گیرد و یک verifier بیرون می‌دهد. NIST: "Password hashing schemes take a password, a salt, and a cost factor as inputs and generate a password hash." salt باید "SHALL be at least 32 bits" باشد؛ طرح و هزینه "SHOULD be stored for each password to allow migration". چهار طرح رایج:

طرحتنظیم‌های هزینهنقطهٔ شروع در OWASP Password Storage Cheat SheetMemory-hardنکته
Argon2idحافظه m (KiB)، زمان t (تعداد گذر)، موازی‌سازی p (lane)m=47104 (46 MiB) t=1 p=1، یا m=19456 (19 MiB) t=2 p=1، یا m=12288 t=3، m=9216 t=4، m=7168 t=5 ("equal level of defense")بلهRFC 9106؛ "increasing p does not multiply the total memory"
scryptN (CPU/حافظه)، r (اندازهٔ بلوک)، pN=2^17 (128 MiB)، r=8، p=1بلهوقتی Argon2id نیست
bcryptcost (log2 تعداد دور)"minimum of 10"خیر (4 KiB)محدودیت ورودی ۷۲ بایت؛ پیشوندهای $2y$ / $2a$ / $2b$
PBKDF2تعداد تکرار، PRFHMAC-SHA-256: 600,000؛ HMAC-SHA-512: 220,000خیرانتخاب FIPS 140؛ NIST SP 800-132
text
     Attacker with a stolen users table, one GPU, guessing "Summer2026!"-style candidates
1    unsalted SHA-256    one hash per candidate covers every user; rainbow tables work          (billions per second)
2    salted SHA-256      one hash per candidate per user; still fast                             (billions per second)
3    bcrypt cost 12      ~190 ms per guess on one CPU core (this chapter's lab)                  (a few per second per core)
4    Argon2id 19 MiB t=2 ~16-23 ms per guess, and each guess needs 19 MiB of memory              (memory bandwidth bound)
5    + pepper in a KMS   without the pepper, no guess can be checked at all

سناریوی واقعی: نشت hashهای SHA-1 بدون salt در LinkedIn در ۲۰۱۲ (به‌طور گسترده گزارش شده؛ منبع ثانویه) که در چند روز شکسته شد؛ SaaSی که ۲ میلیون hash از نوع bcrypt با cost 10 را هنگام ورود کاربران به Argon2id منتقل می‌کند؛ سیستم دولتی‌ای که باید PBKDF2 به کار ببرد چون فقط ماژول‌های تأییدشدهٔ FIPS مجازند؛ سرویس ورود روی podهای ۲ vCPU که در آن Argon2id با 64 MiB و ۵۰ ورود هم‌زمان یعنی 3.2 GB حافظه فقط برای hash.

چه چیزی آن را فراهم می‌کند:

پلتفرمپیش‌فرضچطور عوض کنیم
Laravel 13 (config/hashing.php)bcrypt، rounds 12؛ argon با memory 65536، time 4، threads 1HASH_DRIVER=argon2id، BCRYPT_ROUNDS، ARGON_MEMORY، ARGON_TIME، ARGON_THREADS، BCRYPT_LIMIT
password_hash در PHP 8.5 (اندازه‌گیری‌شده)PASSWORD_BCRYPT با cost 12؛ PASSWORD_ARGON2ID با m=65536، t=4، p=1آرایهٔ options
Go با golang.org/x/crypto/argon2پیش‌فرض ندارد: IDKey(password, salt, time, memory, threads, keyLen)؛ مستندات گزینهٔ اول RFC 9106 را نشان می‌دهدانتخاب و encode رشتهٔ PHC با خودتان است
Go با golang.org/x/crypto/bcryptDefaultCost 10، MinCost 4، MaxCost 31GenerateFromPassword(pw, cost)؛ Cost(hash) برای خواندنش
Keycloak"Argon2 (default for non-FIPS deployments)"؛ گونه‌های PBKDF2 برای FIPSسیاست رمز realm با "Hashing Algorithm" و "Hashing Iterations"
Spring Security، DjangoDelegatingPasswordEncoder با پیشوند {bcrypt}؛ Django به‌طور پیش‌فرض PBKDF2 با Argon2 اختیاریتنظیمات framework

راه درست: سیستم‌های جدید Argon2id استفاده کنند. روی نوع instance واقعی production اندازه بگیرید و بزرگ‌ترین پارامترهایی را انتخاب کنید که هم زمان ورود را زیر حدود ۱۰۰ میلی‌ثانیه نگه دارد و حاصل‌ضرب حافظه در اوج ورودهای هم‌زمان جا شود. رشتهٔ کامل PHC ($argon2id$v=19$m=...,t=...,p=...$salt$hash) را ذخیره کنید تا پارامترها بعداً قابل تغییر باشند. کد: pwhash.go.

Salt، pepper و rehash هنگام ورود مهم ​

به زبان ساده: salt باعث می‌شود hash هر کاربر متفاوت باشد؛ pepper یک کلید مخفی است که بیرون از پایگاه داده نگه داشته می‌شود، پس dump پایگاه داده به‌تنهایی بی‌فایده است؛ rehash هنگام ورود (Rehash on login) hashهای قدیمی را همان لحظه‌ای ارتقا می‌دهد که کاربر ثابت می‌کند رمز را می‌داند.

بدفهمی رایج: «pepper همان salt دوم است.» salt عمومی است و کنار hash ذخیره می‌شود؛ pepper مخفی است و جای دیگری نگه داشته می‌شود (KMS، HSM، secrets manager). OWASP: "the pepper should not be public and should not be stored along with the generated hash." و برخلاف salt، چرخاندن pepper بدون متن ساده ممکن نیست: "changing a pepper will require forcing all users whose passwords were protected by the previous pepper to reset their passwords" (مگر اینکه wrap کنید: HMAC(newPepper, oldHash) را ذخیره کنید و در ورود بعدی rehash کنید).

تعریف: NIST SP 800-63B-4 می‌گوید verifierها "SHOULD perform an additional iteration of a keyed hashing or encryption operation using a secret key known only to the verifier"، کلیدی که "separately from the hashed passwords" و ترجیحاً "within a hardware-protected area" نگه داشته شود. OWASP دو شکل را نام می‌برد: pre-hashing (اول HMAC روی رمز، بعد Argon2id) و post-hashing (اول Argon2id، بعد HMAC یا رمزگذاری نتیجه). rehash هنگام ورود: بعد از بررسی موفق، اگر hash ذخیره‌شده الگوریتم قدیمی یا پارامترهای ضعیف‌تری دارد، hash جدید را حساب و ذخیره کنید.

text
     Day       Event                                          Stored for ada@example.com
1    2019      sign-up, bcrypt cost 10                         $2y$10$...
2    2026-01   config: driver argon2id m=19456 t=2 p=1          unchanged (no plaintext available)
3    2026-02   Ada logs in; verify bcrypt OK; needsRehash=true  $argon2id$v=19$m=19456,t=2,p=1$...
4    2026-06   config: m=47104 t=1                              unchanged until her next login
5    2026-06   Ada logs in; params differ -> rehash             $argon2id$v=19$m=47104,t=1,p=1$...
6    2027      12% of users never logged in: still bcrypt       force reset for them, or wrap bcrypt in Argon2id

سناریوی واقعی: انتقال ۱.۸ میلیون hash قدیمی MD5 با wrap کردنشان (argon2id(md5)) در همان روز اول و باز کردن wrap در هر ورود؛ pepperی در AWS KMS که باعث می‌شود dump حاصل از SQL injection هیچ چیز قابل‌شکستنی نداشته باشد؛ مهاجرت bcrypt به Argon2id که بی‌صدا متوقف شد چون مسیر ورود از Auth::validate() استفاده می‌کرد که rehash نمی‌کند؛ hash ساختگی‌ای که پارامترهایش از hashهای واقعی عقب است و در نتیجه سریع‌تر جواب می‌دهد.

چه چیزی آن را فراهم می‌کند:

پلتفرمRehash هنگام ورودPepper
Laravel 13rehash_on_login (پیش‌فرض true) در Auth::attempt() و starter kitها؛ Hash::needsRehash() برای جریان‌های سفارشیداخلی نیست: HMAC پیش از Hash::make، و اگر می‌توانید کلید را بیرون از .env نگه دارید
PHPpassword_needs_rehash($hash, $algo, $options)دستی
Go (این فصل)Verify برای پارامترهای دیگر یا bcrypt مقدار needsRehash برمی‌گرداندHasher.Pepper، pre-hash با HMAC-SHA-256
Djangocheck_password خودکار ارتقا می‌دهدSECRET_KEY یک pepper نیست؛ دستی
Keycloakوقتی سیاست realm عوض شود هنگام ورود دوباره hash می‌کند—

راه درست: الگوریتم و پارامترها را کنار هر hash ذخیره کنید (رشتهٔ PHC)؛ needsRehash را در همهٔ مسیرهای ورود موفق صدا بزنید، از جمله مسیرهای سفارشی؛ hash ساختگی را با پارامترهای فعلی بسازید؛ اگر pepper اضافه می‌کنید، برایش نسخه بگذارید (یک kid کنار hash) تا چرخاندن بعدی یک ارتقای تک‌تک در زمان ورود باشد، نه بازنشانی همگانی.

حمله‌های آنلاین: brute force، credential stuffing، password spraying حیاتی ​

به زبان ساده: brute force یک حساب را با رمزهای زیاد می‌کوبد؛ credential stuffing جفت‌های ایمیل/رمزی را که از سایت‌های دیگر لو رفته‌اند دوباره امتحان می‌کند؛ password spraying یکی دو رمز خیلی رایج را آرام‌آرام روی تعداد زیادی حساب امتحان می‌کند تا زیر محدودیت هر حساب بماند.

بدفهمی رایج: «lockout به‌ازای حساب جلوی همهٔ این‌ها را می‌گیرد.» فقط جلوی brute force را می‌گیرد. stuffing هر حساب را یکی دو بار امتحان می‌کند (با رمز قدیمی واقعی همان کاربر) و از هزاران IP خانگی؛ spraying روزی یک رمز به‌ازای هر حساب امتحان می‌کند. هیچ‌کدام به آستانهٔ هر حساب نمی‌رسند.

تعریف: OWASP Credential Stuffing Prevention Cheat Sheet این دو را با هم بررسی می‌کند و MFA را اول می‌گذارد: "by far the best defense against the majority of password-related attacks". بعد کنترل‌های لایه‌لایه: بررسی رمز لورفته، CAPTCHA، اعتبار IP، device fingerprinting، connection fingerprinting، نام کاربری غیرقابل‌پیش‌بینی، ورود چندمرحله‌ای و خبر دادن به کاربر دربارهٔ ورودهای غیرعادی.

text
     Attack                Attempts per account    Attempts per IP          What sees it
1    Brute force           10,000 on ada@...       many (or rotated)        per-account counter
2    Credential stuffing   1-2 on each of 500,000  1-3 per IP (botnet)      breached-password check at login, success-rate drop, MFA
3    Password spraying     1 per day per account   50 per IP, spread out    per-IP counter, global "same password" pattern, blocklist
4    Targeted guessing     20 over a month         a few                    risk signals: new device, new country

سناریوی واقعی: سرویس پخش آنلاینی که نرخ موفقیت ورودش یک‌شبه از ۷۰٪ به ۲٪ رسید (stuffing با یک combo list خریداری‌شده)؛ دانشگاهی که spraying با Autumn2026! در یک هفته به ۴۰ حساب کارمند رسید؛ شرکت بازی‌سازی که مهاجمانش از proxyهای خانگی استفاده کردند و محدودیت per-IP هرگز فعال نشد؛ endpoint ورود API که CAPTCHA فرم وب را نداشت و botها از API رفتند.

چه چیزی آن را فراهم می‌کند:

محصولکنترل‌های مرتبط
CloudflareBot Management، Turnstile (جایگزین CAPTCHA)، leaked credentials detection (وقتی جفت credential ارسالی لورفته باشد یک header به درخواست اضافه می‌کند؛ header قدیمی "Exposed-Credential-Check" منسوخ شده)، قواعد rate limiting روی /login
AWSگروه قواعد مدیریت‌شدهٔ account takeover prevention (ATP) در AWS WAF Fraud Control؛ threat protection در Cognito (credential لورفته، احراز هویت تطبیقی)
Auth0Brute-force protection، Suspicious IP throttling، Breached Password Detection، Bot Detection
OktaThreatInsight، MFA تطبیقی، Okta FastPass (مقاوم در برابر فیشینگ)
KeycloakBrute Force Detection (به‌ازای کاربر) با حالت‌های lockout؛ محدودیت سطح IP باید از proxy یا WAF بیاید
Laravellimiter نام‌دار throttle:login، EnsureLoginIsNotThrottled در Fortify (ایمیل + IP)، Password::uncompromised() هنگام ثبت‌نام

راه درست: MFA برای هر کسی که می‌شود؛ بررسی رمز لورفته هنگام ثبت‌نام، تغییر و ورود (هشدار بدهید و در صورت تطابق بازنشانی اجباری کنید)؛ throttle هم‌زمان روی چند کلید (حساب، IP، زیرشبکهٔ IP، دستگاه، نرخ شکست سراسری)؛ تشخیص bot جلوی API ورود، نه فقط فرم HTML؛ هشدار برای افت ناگهانی نسبت ورود موفق.

Account enumeration و timing attack حیاتی ​

به زبان ساده: اگر صفحهٔ ورود، ثبت‌نام یا بازنشانی برای «این ایمیل وجود دارد» و «وجود ندارد» جواب متفاوتی بدهد، مهاجم می‌تواند فهرست مشتریان شما را بسازد و بعد فقط به آن‌ها حمله کند. تفاوت می‌تواند در پیام، status code، redirect، یک header یا فقط در زمان پاسخ باشد.

بدفهمی رایج: «پیام یکسان نشان می‌دهیم، پس امنیم.» اگر ایمیل‌های ناموجود در ۲ میلی‌ثانیه و موجودها در ۱۹۰ میلی‌ثانیه برگردند (چون فقط برای آن‌ها bcrypt اجرا می‌شود)، کرونومتر چیزی را می‌گوید که پیام پنهان می‌کند. OWASP همین را صریح می‌گوید: وقتی کاربر وجود ندارد "the application will directly throw an error"، پس "the response time will be different".

تعریف: OWASP Authentication Cheat Sheet: "an application must respond with a generic error message regardless of whether" شناسه یا رمز غلط بوده، حساب وجود ندارد، یا قفل یا غیرفعال است؛ در ورود، بازنشانی و بازیابی. نمونهٔ غلط و درست: "Login for User foo: invalid password." در برابر "Login failed; Invalid user ID or password." مقایسهٔ زمان‌ثابت (Constant-time compare) با subtle.ConstantTimeCompare یا hash_equals جلوی نشت بایت‌به‌بایتِ زمان در یک مقایسه را می‌گیرد؛ hash ساختگی برای کاربران ناموجود جلوی نشت بسیار بزرگ‌ترِ «هیچ hashی اجرا نشد» را.

text
     Request                              Naive handler                          Uniform handler
1    POST /login unknown@x.test           404 "no account", 2 ms                 422 "These credentials do not match our records.", 200 ms
2    POST /login ada@x.test wrong pw      401 "wrong password", 190 ms           422 same message, 200 ms (bcrypt 190 ms + timebox)
3    POST /forgot-password unknown@x.test "We can't find a user with that ..."  "If an account exists, we sent a link." queued, 5 ms
4    POST /register ada@x.test            "Email already taken"                  "Check your inbox to continue" + mail to Ada: "someone tried to sign up"

سناریوی واقعی: مهاجمی که پیش از اخاذی بررسی می‌کند کدام ایمیل‌ها روی یک سایت دوستیابی حساب دارند؛ اپ B2Bی که فرم ثبت‌نامش لو می‌داد کدام رقبا مشتری‌اند؛ endpoint بازنشانی‌ای که پیام ResetThrottled آن فقط برای حساب‌های واقعی ظاهر می‌شد؛ endpoint مربوط به OTP که مقایسهٔ شش‌رقمی‌اش با == روی رشته انجام می‌شد.

چه چیزی آن را فراهم می‌کند:

محصول / APIرفتار
SessionGuard::attempt() و validate() در Laravelداخل یک Timebox به مدت 200,000 µs (۲۰۰ ms) اجرا می‌شوند که فقط در موفقیت زودتر برمی‌گردد، پس شکست‌ها دست‌کم ۲۰۰ ms طول می‌کشند. اگر hash شما بیش از ۲۰۰ ms طول بکشد، شکست با رمز غلط دوباره از شکست با کاربر ناموجود کندتر می‌شود
پیام زبانی auth.failed در Laravel"These credentials do not match our records." (یکسان)
پیام زبانی passwords.user در Laravel"We can't find a user with that email address." (به‌طور پیش‌فرض enumeration: جایگزینش کنید)
Gocrypto/subtle.ConstantTimeCompare؛ framework ندارد: بررسی ساختگی را خودتان می‌نویسید
PHPhash_equals()، password_verify() (برای ورودی هم‌طول زمان‌ثابت)
WebAuthn Level 3بخش 14.6.2 با عنوان "Username Enumeration" همین نشت را برای جریان passkey بحث می‌کند

راه درست: یک پیام برای شکست ورود؛ یک پیام برای درخواست بازنشانی که از یک job صف‌شده فرستاده می‌شود تا زمان یکسان باشد؛ ثبت‌نامی که همیشه می‌گوید «صندوق ایمیل را ببینید» و به‌جای گفتن «تکراری است» به صاحب فعلی ایمیل می‌زند؛ hash ساختگی با پارامترهای فعلی؛ ConstantTimeCompare برای هر مقایسهٔ secret؛ status code و شکل پاسخ یکسان در همهٔ شاخه‌ها.

Throttling، lockout، CAPTCHA و احراز هویت مبتنی بر ریسک حیاتی ​

به زبان ساده: تعداد حدس‌هایی را که هر کس می‌تواند بزند محدود کنید، ولی طوری که مهاجم نتواند با همین محدودیت کاربران واقعی را بیرون بگذارد. به‌جای بستن در، کند کنید؛ با بیش از یک کلید بشمارید؛ و وقتی چیزی غیرعادی است اثبات بیشتری بخواهید.

بدفهمی رایج: «بعد از پنج شکست حساب را ۳۰ دقیقه قفل کن.» این یک دکمهٔ منع سرویس است: هر کس ایمیل مدیرعامل را بداند می‌تواند برای همیشه او را بیرون نگه دارد. NIST تا ۱۰۰ شکست متوالی را پیش از غیرفعال کردن authenticator مجاز می‌داند و در این میان تأخیر و چالش bot را توصیه می‌کند.

تعریف: NIST SP 800-63B-4 (بخش Rate Limiting): verifier "SHALL limit consecutive failed authentication attempts using a specific authenticator on a single subscriber account to no more than 100"، می‌تواند چالش bot اضافه کند، انتظارهایی که رشد می‌کنند "(e.g., 30 seconds up to an hour)"، و تکنیک‌های مبتنی بر ریسک با "IP address, geolocation, timing of request patterns, or browser metadata"؛ و بعد از موفقیت "SHOULD disregard any previous failed attempts". OWASP سه تنظیم lockout را اضافه می‌کند: آستانهٔ lockout، پنجرهٔ مشاهده، مدت lockout، و lockout نمایی را پیشنهاد می‌دهد. احراز هویت مبتنی بر ریسک (Risk-based authentication) یا تطبیقی به هر تلاش امتیاز می‌دهد (دستگاه جدید، سفر ناممکن، خروجی Tor، IP بدنام) و یک مرحله اضافه می‌کند (MFA، CAPTCHA) یا مسدود می‌کند.

text
     Policy in this chapter's Go code: 5 free failures, then 1s, 2s, 4s ... capped at 15 min; 100 = password disabled
     Attempt  Source IP        Result
1    1-5      198.51.100.x     invalid credentials, no delay
2    6        198.51.100.99    invalid; next attempt not before +1 s
3    7 (0.5s) 203.0.113.7      429 Retry-After: 1   (real user also waits 1 s, not 30 min)
4    7 (1.0s) 203.0.113.7      correct password -> success, counter reset
5    ip 192.0.2.66 x 50        50 different accounts, "Winter2026!" -> 51st from that IP: 429 for 10 min

سناریوی واقعی: صف پشتیبانی‌ای که بعد از هدف گرفتن همهٔ ایمیل‌های کارمندان توسط یک botnet پر از تیکت «قفل شده‌ام» شد؛ اپ مصرف‌کننده‌ای که فقط بعد از شکست سوم Turnstile نشان می‌دهد؛ بانکی که برای ورود از دستگاه جدید MFA می‌خواهد و ورود از کشوری را که مشتری هرگز استفاده نکرده مسدود می‌کند؛ تأخیر نمایی‌ای که کاربر را بعد از چند ثانیه راه می‌دهد ولی ۱۰,۰۰۰ حدس را سال‌ها طول می‌دهد.

چه چیزی آن را فراهم می‌کند:

محصولسازوکار و پیش‌فرض‌ها (از مستندات خودشان)
starter kitهای Laravel / Fortify"throttling is unique to the user's username / email address and their IP address"؛ stub در Fortify: Limit::perMinute(5) با کلید ایمیل به‌علاوهٔ IP؛ limiter two-factor پنج در دقیقه با login.id؛ passkeys ده در دقیقه
Keycloak Brute Force Detectionحالت‌های lockout موقت و دائمی؛ پیش‌فرض‌های lockout دائمی: Max Login Failures 30، Quick Login Check Milliseconds 1000، Minimum Quick Login Wait یک دقیقه
Auth0Brute-force protection (به‌ازای کاربر و IP)، Suspicious IP throttling
Amazon Cognitoاحراز هویت تطبیقی در threat protection (اقدام برای ریسک کم/متوسط/زیاد)
Cloudflare / AWS WAFقواعد rate limiting روی مسیر ورود، قواعد مدیریت‌شدهٔ bot، ATP
Goframework ندارد: شمارنده در Redis (INCR + EXPIRE یا token bucket با Lua)؛ Rate Limiting را ببینید

راه درست: throttle را پیش از hash اجرا کنید (تلاش throttleشده نباید ۲۰ میلی‌ثانیه Argon2id خرج شما کند)؛ به‌ازای حساب (ایمیل نرمال‌شده، حتی برای ایمیل ناموجود)، به‌ازای IP، به‌ازای /24 یا /64 و به‌صورت سراسری بشمارید؛ به‌جای lockout سخت از تأخیر تدریجی و یک مرحلهٔ CAPTCHA استفاده کنید؛ در سقف سخت، رمز را غیرفعال کنید (نه کل حساب) و بگذارید جریان بازنشانی دوباره فعالش کند؛ بعد از شکست‌های غیرعادی به کاربر ایمیل بزنید؛ سیگنال‌های ریسک را به «MFA بخواه» وصل کنید، نه به «رد کن».

MFA، عامل‌ها و سطح‌های اطمینان حیاتی ​

به زبان ساده: دو نوع متفاوت اثبات را ترکیب کنید (چیزی که می‌دانید، چیزی که دارید، چیزی که هستید) تا دزدیدن یکی کافی نباشد. 2FA همان MFA با دقیقاً دو عامل است.

بدفهمی رایج: «هر عامل دومی به یک اندازه خوب است.» کد پیامکی با SIM swap دزدیده و با صفحهٔ فیشینگ رله می‌شود؛ کد TOTP هم رله می‌شود؛ passkey اما origin وب‌سایت را امضا می‌کند و روی دامنهٔ جعلی بی‌فایده است. NIST این‌ها را در سطح‌های متفاوت می‌گذارد و فقط آخری را «مقاوم در برابر فیشینگ» (Phishing-resistant) می‌نامد.

تعریف: سطح‌های اطمینان احراز هویت (AAL) در NIST SP 800-63B-4: AAL1 (تک‌عاملی مجاز؛ احراز دوباره "no more than 30 days")، AAL2 (دو عامل؛ احراز دوباره در ۲۴ ساعت، بی‌فعالیتی حداکثر ۱ ساعت؛ باید گزینهٔ مقاوم در برابر فیشینگ ارائه شود)، AAL3 (authenticator رمزنگاری با "non-exportable private key" که "SHALL provide phishing resistance"؛ ۱۲ ساعت کل و ۱۵ دقیقه بی‌فعالیتی). مقاومت در برابر فیشینگ "the ability of the authentication protocol to prevent the disclosure of authentication secrets and valid authenticator outputs to an impostor verifier ... without relying on the vigilance of the claimant" است و با channel binding (TLS با احراز کلاینت) یا verifier name binding (WebAuthn) به دست می‌آید.

عاملنوعمقاوم در برابر فیشینگوضعیت در NISTمحصول نمونه
رمزدانستنیخیرمجاز؛ به‌تنهایی ۱۵+ نویسههر فرم ورود
اپ TOTPداشتنیخیر (کد رله‌شدنی است)مجاز (OTP چندعاملی وقتی اپ قفل دارد)Google Authenticator، Microsoft Authenticator، 1Password، Authy
OTP پیامکی / صوتیداشتنی (شمارهٔ تلفن)خیرauthenticator محدودشدهTwilio Verify، SMS MFA در Cognito
OTP ایمیلی / magic linkداشتنی (صندوق ایمیل)خیرauthenticator out-of-band در AAL2 نیستemail MFA در Cognito، Auth0 passwordless
تأیید push (با number matching)داشتنیخیرمجاز؛ تعداد درخواست باید محدود شودOkta Verify، Duo، Microsoft Authenticator
Passkey (همگام‌شونده)داشتنی + (دانستنی یا بودنی)بلهauthenticator syncable، AAL2iCloud Keychain، Google Password Manager، 1Password
Security key / passkey وابسته به دستگاهداشتنی + (دانستنی یا بودنی)بلهAAL3 وقتی سخت‌افزاری محافظت شودYubiKey، Titan، Windows Hello با TPM
کد بازیابیدانستنی (secret ذخیره‌شده)خیرفقط بازیابی، ۶۴+ بیت، یک‌بارمصرفهمهٔ محصولات MFA

سناریوی واقعی: یک فین‌تک که برای ناظر باید به AAL2 برسد و passkey را اول، TOTP را دوم و SMS را فقط به‌عنوان آخرین چاره انتخاب می‌کند؛ کنسول مدیریتی که کلید سخت‌افزاری می‌خواهد (AAL3)؛ اپ مصرف‌کننده‌ای که MFA را اختیاری عرضه می‌کند (و ۵٪ استفاده می‌بیند)؛ شرکتی که push MFA را اجباری کرد و از راه push bombing نفوذ خورد.

راه درست: اول passkey، بعد TOTP و در آخر SMS ارائه کنید (و هرگز SMS را تنها گزینه نکنید)؛ دست‌کم دو روش یا کدهای بازیابی ذخیره‌شده بخواهید تا گم شدن گوشی به گم شدن حساب ختم نشود؛ amr و auth_time را روی session ثبت کنید؛ برای کارهای پرخطر دوباره MFA بخواهید (step-up).

TOTP و HOTP حیاتی ​

به زبان ساده: سرور و گوشی یک secret تصادفی مشترک دارند. هر ۳۰ ثانیه هر دو HMAC(secret, current 30-second step) را حساب می‌کنند، آن را به شش رقم کوتاه می‌کنند و مقایسه می‌کنند. گوشی به شبکه نیاز ندارد.

بدفهمی رایج: «کد TOTP فقط ۳۰ ثانیه معتبر است، پس replay مشکلی نیست.» RFC 6238 صریح است: "The verifier MUST NOT accept the second attempt of the OTP after the successful validation has been issued for the first OTP." با «پنجرهٔ انحراف» (Drift window) به‌اندازهٔ ±۱ گام، یک کد تا ۹۰ ثانیه پذیرفتنی است؛ بدون بررسی «آخرین گام استفاده‌شده» کسی که از روی شانه دیده یا یک رله می‌تواند دوباره از آن استفاده کند.

تعریف: HOTP (RFC 4226): HOTP(K, C) = Truncate(HMAC-SHA-1(K, C)) mod 10^d که در آن dynamic truncation چهار بایت را از offsetی برمی‌دارد که از نیم‌بایت آخر می‌آید. TOTP (RFC 6238): C = floor((now - T0) / X) با X برابر ۳۰ ثانیهٔ توصیه‌شده و T0 = 0؛ HMAC-SHA-1، SHA-256 یا SHA-512. انحراف: "We RECOMMEND that at most one time step is allowed as the network delay"؛ همگام‌سازی دوباره می‌تواند انحراف تشخیص‌داده‌شده را برای هر کاربر ثبت کند. سرورهای HOTP یک look-ahead window به نام s و پارامتر throttling به نام T دارند. تأمین (Provisioning) با URI به شکل otpauth://totp/Issuer:account?secret=BASE32&issuer=...&algorithm=SHA1&digits=6&period=30 انجام و به‌صورت QR نمایش داده می‌شود. NIST: verifier "SHALL accept a given OTP only once while it is valid" و OTPهای کوتاه‌تر از ۶۴ بیت به محدودیت نرخ نیاز دارند.

text
     Server clock 1,800,000,000 s -> step 60,000,000; Skew = 1; last accepted step stored per user
1    09:00:05  user types 123456 (step 60,000,000)        match, store last_step = 60,000,000
2    09:00:20  attacker replays 123456                     same step <= last_step -> reject (and alert)
3    09:00:40  phone 30 s slow, sends code of 59,999,999   inside window but <= last_step -> reject
4    09:01:10  code of step 60,000,001                     match -> last_step = 60,000,001
5    09:03:00  code from 09:01:50 (two steps old)          outside ±1 window -> reject

سناریوی واقعی: SaaSی که TOTP را فعال کرد ولی بررسی replay را فراموش کرد و pentest آن را پیدا کرد؛ کاربری که ساعت گوشی‌اش ۳ دقیقه عقب بود (راه‌حل همگام‌سازی ساعت گوشی است، نه پنجرهٔ ±۱۰)؛ کدهای شش‌رقمی بدون محدودیت نرخ (۱۰۰ حدس به‌ازای هر حساب در ساعت یعنی شانس یک در ده‌هزار در ساعت؛ NIST سقف ۱۰۰ تلاشش را دقیقاً با همین حساب انتخاب کرده)؛ secretهای TOTP که به‌صورت متن ساده کنار hash رمز ذخیره شده بودند و یک SQL injection هر دو عامل را به مهاجم داد.

چه چیزی آن را فراهم می‌کند:

محصولجزئیات
Laravel FortifyTOTP شش‌رقمی از طریق pragmarx/google2fa؛ secret و کدهای بازیابی رمزگذاری‌شده ذخیره می‌شوند؛ مرحلهٔ confirm پیش از فعال شدن؛ window اختیاری؛ replay با کش کردن timestampهای استفاده‌شده مسدود می‌شود (verifyKeyNewer به‌علاوهٔ یک کلید کش به‌ازای هر کد)
Go با github.com/pquerna/otp v1.5.0totp.Generate(GenerateOpts{Issuer, AccountName})، totp.ValidateCustom(code, secret, t, ValidateOpts{Period, Skew, Digits, Algorithm})؛ دربارهٔ Skew: "Values greater than 1 are likely sketchy"؛ انبار replay ندارد و باید خودتان اضافه کنید
بستهٔ Go totp در این فصلفقط کتابخانهٔ استاندارد، بردارهای آزمون RFC، Verify(key, code, lastStep)
KeycloakOTP Policy به‌ازای realm: TOTP/HOTP، الگوریتم، تعداد رقم، look-around window، دوره
Amazon Cognito"TOTP software token MFA"
Auth0، OktaOTP در Guardian / Okta Verify به‌علاوهٔ هر اپ TOTP

راه درست: secret ۱۶۰ بیتی از CSPRNG؛ نمایش QR و متن Base32؛ پیش از فعال‌سازی یک کد معتبر بخواهید («confirm»)؛ secret را با کلیدی بیرون از پایگاه داده رمزگذاری کنید؛ skew برابر ۱؛ آخرین گام پذیرفته‌شده را در همان تراکنش ورود ذخیره کنید؛ محدودیت نرخ به‌ازای ورود در انتظار (Fortify: پنج در دقیقه)؛ هنگام ثبت عامل، کدهای بازیابی صادر کنید. کد: totp.go، Totp.php.

SMS، OTP ایمیلی و push؛ MFA fatigue مهم ​

به زبان ساده: کدهایی که با پیامک یا ایمیل فرستاده می‌شوند، یا درخواست push با «تأیید می‌کنید؟»، برای کاربر راحت‌اند ولی هر کدام یک راه شکست شناخته‌شده دارند: SIM swap و شنود SS7 برای پیامک، صندوق ایمیل نفوذشده برای ایمیل، و «تأیید کن تا تمام شود» برای push.

بدفهمی رایج: «SMS هنوز MFA است، پس برای مدیران کافی است.» NIST SP 800-63B-4 تحویل از طریق PSTN را authenticator محدودشده می‌داند: سازمان باید جایگزین نامحدود ارائه کند، کاربران را آگاه کند و برنامهٔ مهاجرت داشته باشد؛ OWASP: "Do not use SMS for high-value or PII-handling applications."

تعریف: SIM swap: مهاجم اپراتور را قانع می‌کند شمارهٔ قربانی را به سیم‌کارت جدیدی منتقل کند و بعد کدها را دریافت می‌کند. SMS pumping / toll fraud: botها برای شماره‌های پولی کد درخواست می‌کنند تا شما هزینه بدهید ("Calls and SMS messages may cost money to send"، OWASP). MFA fatigue (push bombing): "Attackers repeatedly send MFA push notifications, often combined with social engineering, hoping the user eventually approves one." NIST دیگر جریان‌های out-of-band فقط-تأیید را نمی‌پذیرد ("This method is no longer considered acceptable") و انتقال secret بین دو کانال را الزامی می‌کند؛ verifierهای push "SHOULD implement a reasonable limit on the rate or total number of push notifications".

text
     MFA fatigue with plain approve/deny push
1    01:58  attacker has the password (stuffing), triggers login      push #1 to the victim's phone
2    01:58-02:20  repeats 30 times                                     pushes #2..#30
3    02:21  attacker messages on WhatsApp "IT support, please accept"  victim taps Approve
4    02:21  session created for the attacker
     With number matching: the login page shows "42"; the phone asks which number is on screen. The victim
     cannot match a number they cannot see, and the 3rd prompt in 5 minutes is blocked and reported.

سناریوی واقعی: مشتری صرافی رمزارزی که بعد از SIM swap دارایی‌اش را از دست داد؛ صورت‌حساب پیامکی هزاران دلاری از botهایی که /send-code را با شماره‌های پولی می‌زدند؛ شرکت بزرگی که از راه push bombing یک پیمانکار نفوذ خورد؛ OTP ایمیلی‌ای که بی‌فایده بود چون صندوق ایمیل همان رمز را داشت.

چه چیزی آن را فراهم می‌کند:

محصولکنترل
Microsoft Authenticator، Okta Verify، DuoNumber matching، نمایش مکان و اپ در درخواست
OktaOkta FastPass (وابسته به دستگاه، مقاوم در برابر فیشینگ)، ThreatInsight
Amazon CognitoSMS و email message MFA (ایمیل به SES نیاز دارد)، TOTP؛ passkey به‌عنوان عامل اول
Twilio VerifyFraud Guard در برابر SMS pumping، مجوزهای جغرافیایی
نشانه‌های ریسک NIST پیش از PSTN"device swap, SIM change, number porting, other abnormal behavior"

راه درست: اگر مجبورید SMS بفرستید، به‌ازای شماره و حساب محدودیت نرخ بگذارید، بازه‌های پولی را مسدود کنید، سیگنال‌های SIM swap را بررسی کنید و هرگز اجازه ندهید SMS به‌تنهایی هم رمز و هم MFA را بازنشانی کند؛ برای push از number matching و سقف تعداد استفاده کنید؛ و برای همه‌چیز passkey را ترجیح دهید.

WebAuthn، FIDO2 و passkey حیاتی ​

به زبان ساده: دستگاه کاربر برای دامنهٔ شما یک جفت کلید می‌سازد. کلید عمومی به سرور می‌رود؛ کلید خصوصی هرگز دستگاه (یا keychain همگام‌شدهٔ کاربر) را ترک نمی‌کند. برای ورود، دستگاه یک challenge تازه از سرور را امضا می‌کند و مرورگر origin سایت را داخل چیزی که امضا می‌شود می‌گذارد، پس دامنهٔ جعلی امضایی می‌گیرد که روی دامنهٔ واقعی بی‌فایده است.

بدفهمی رایج: «passkey یعنی رمزی که در فضای ابری ذخیره شده.» هیچ چیز مخفی‌ای به سرور فرستاده یا روی آن ذخیره نمی‌شود؛ نشت پایگاه داده فقط کلیدهای عمومی را لو می‌دهد. و «passkey همیشه وابسته به دستگاه است» هم درست نیست: «passkey همگام‌شونده» (Synced passkey) را ارائه‌دهندهٔ passkey به‌صورت رمزگذاری سرتاسری بین دستگاه‌های کاربر کپی می‌کند؛ passkey وابسته به دستگاه روی security key کپی نمی‌شود.

تعریف: WebAuthn Level 3 (W3C Recommendation، ۲۵ اوت ۲۰۲۶) این‌ها را تعریف می‌کند: Relying Party (سایت شما)، RP ID آن (یک دامنه؛ "A public key credential can only be used for authentication with the same entity (as identified by RP ID) it was registered with")، authenticatorها (platform مثل Face ID، Touch ID، Windows Hello؛ roaming مثل security key) و دو ceremony. ثبت (Registration) با navigator.credentials.create() یک credential ID، کلید عمومی و شیء attestation برمی‌گرداند؛ احراز با navigator.credentials.get() یک assertion برمی‌گرداند (امضا روی authenticatorData و hash مربوط به clientDataJSON که origin و challenge را دارد). Discoverable credential (که قبلاً «resident key» نام داشت) اجازه می‌دهد کاربر بدون تایپ نام کاربری وارد شود؛ user presence (UP) و user verification (UV: PIN یا biometric) پرچم هستند؛ backup eligibility (BE) و backup state (BS) می‌گویند credential چنددستگاهی (همگام‌شونده) است یا نه؛ signature counter به تشخیص authenticator کلون‌شده کمک می‌کند ("a signal, but not proof"). FIDO2 برابر است با WebAuthn به‌علاوهٔ CTAP2 (پروتکل مرورگر به authenticator). FIDO Alliance: "Passkeys can be securely synced across a user's devices, or bound to a particular device (device-bound passkeys)."

AuthenticatorBrowser (client)Relying Party serverRegistration creates a key pair; authentication proves possession of itchallenge, rp.id, user.id, residentKeycredentials.create()UP + UV (PIN, biometric);new key pair for this RP IDpublic key, credential ID, attestation+ clientDataJSON (origin, challenge)check challenge,origin, rpIdHash,flags; store keynew challenge (+ allowCredentials or none)credentials.get()sign authenticatorData +assertion: signature, userHandlehash(clientDataJSON)+ clientDataJSONverify signaturewith stored keyREGISTRATIONAUTHENTICATION

در تصویر، سه طرف ماجرا را می‌بینید: authenticator، مرورگر و سرور relying party. در ثبت، سرور challenge و RP ID می‌فرستد، authenticator بعد از بررسی UP و UV یک جفت کلید مخصوص همان RP ID می‌سازد و سرور پس از بررسی challenge، origin و rpIdHash کلید عمومی را ذخیره می‌کند. در احراز، authenticator challenge جدید را امضا می‌کند و سرور امضا را با کلید ذخیره‌شده بررسی می‌کند.

text
     Phishing attempt against a passkey user
1    victim opens https://examp1e-login.test (look-alike)       page calls navigator.credentials.get()
2    browser: RP ID must be a suffix of examp1e-login.test         no credential for that RP ID exists -> nothing to sign
3    attacker proxies to the real site instead                     real site's challenge is signed with origin = examp1e-login.test
4    real server checks clientDataJSON.origin                      "https://examp1e-login.test" not in allowed origins -> reject
     Compare TOTP: the victim types 123456 into the fake page, the proxy forwards it within 30 s, attacker is in.

سناریوی واقعی: سایت مصرف‌کننده‌ای که «ورود با passkey» عرضه می‌کند و تیکت پشتیبانی کمتری از رمز به‌علاوهٔ SMS می‌بیند؛ سازمانی که برای دسترسی production، passkey وابسته به دستگاه روی YubiKey می‌خواهد (AAL3) و attestation را با FIDO Metadata Service بررسی می‌کند؛ کاربری که گوشی‌اش را گم می‌کند ولی passkeyهای همگام‌شده‌اش را از طریق iCloud Keychain روی گوشی جدید دارد؛ RPی که credentialها را روی app.example.com ثبت کرد و بعد خواست روی example.com هم کار کنند (RP ID را از اول انتخاب کنید: دامنهٔ قابل‌ثبت انتخاب انعطاف‌پذیر است).

چه چیزی آن را فراهم می‌کند:

محصول / کتابخانهنکته
Go با github.com/go-webauthn/webauthn (اینجا v0.15.0؛ v0.18.2 به Go 1.26 نیاز دارد)webauthn.New(&Config{RPID, RPDisplayName, RPOrigins})؛ BeginRegistration/FinishRegistration، BeginDiscoverableLogin/FinishPasskeyLogin؛ Credential.Authenticator.CloneWarning؛ Flags.BackupEligible/BackupState
Laravel FortifyFeatures::passkeys(['confirmPassword' => true])؛ بستهٔ laravel/passkeys را می‌پوشاند؛ تنظیم‌های relying_party_id، allowed_origins، user_handle_secret، timeout 60000؛ مسیرهای /passkeys/login/options و /passkeys/login؛ بستهٔ npm @laravel/passkeys
ارائه‌دهندگان passkeyiCloud Keychain، Google Password Manager، Windows Hello، 1Password، Dashlane، Bitwarden
ارائه‌دهندگان هویتKeycloak (WebAuthn Policy و passwordless)، Auth0، Okta، Amazon Cognito (passkey به‌عنوان عامل اول passwordless)، Ory Kratos
Attestation conveyancenone (پیش‌فرض، بیشتر سایت‌های مصرف‌کننده)، indirect، direct، enterprise؛ وقتی مدل دستگاه را لازم دارید با FIDO MDS بررسی کنید

راه درست: برای passkey بدون رمز residentKey: required و userVerification: required بخواهید؛ جز وقتی سیاست به مدل دستگاه نیاز دارد attestation: none بگذارید؛ credential ID، کلید عمومی، sign count، transportها، BE/BS، AAGUID، زمان ساخت و آخرین استفاده و نامی که کاربر انتخاب کرده را ذخیره کنید؛ چند passkey به‌ازای هر حساب مجاز کنید؛ هنگام ثبت excludeCredentials بفرستید؛ challenge را سمت سرور و یک‌بارمصرف نگه دارید؛ پیش از افزودن یا حذف passkey یک step-up تازه بخواهید. کد: passkey.go.

کدهای بازیابی و بازیابی حساب مهم ​

به زبان ساده: هر عامل دومی را بالاخره کسی گم می‌کند. بازیابی دری پشتی است که عمداً می‌سازید و مهاجمان اول سراغ همین می‌آیند، پس باید به اندازهٔ در اصلی محکم باشد.

بدفهمی رایج: «اگر گوشی را گم کرد، پشتیبانی بعد از چند سؤال MFA را خاموش می‌کند.» آن‌وقت MFA واقعی شما یعنی «تاریخ تولد کاربر را می‌داند و پشت تلفن قانع‌کننده است». NIST استفاده از knowledge-based authentication را برای این کار ممنوع می‌کند.

تعریف: NIST SP 800-63B-4 بخش 4.2 (بازیابی حساب): «کدهای بازیابی» (Recovery code) ذخیره‌شده "SHALL include at least 64 bits from an approved random bit generator"، "in hashed form" ذخیره می‌شوند، "SHALL be subject to the throttling requirements"، و بعد از استفاده "the CSP SHALL invalidate that recovery code and SHALL issue a new saved recovery code"؛ هر بازیابی یا کد جدید "SHALL result in an account recovery notification". روش‌های دیگر بازیابی: کد بازیابی صادرشده به نشانی تأییدشده، مخاطبان بازیابی، اثبات هویت دوباره. OWASP Forgot Password: بعد از بازیابی "invalidate existing sessions and outstanding password reset and recovery links or codes".

text
     Recovery that does not undo MFA
1    user: "lost my phone"            -> sign in with password + one recovery code (rate limited, hashed, burned)
2    server                           -> session marked amr=[pwd, recovery]; prompt "set up a new factor now"
3    server                           -> email + push to remaining devices: "a recovery code was used"
4    user enrols new TOTP / passkey   -> old TOTP secret revoked; new recovery codes issued; old ones invalid

سناریوی واقعی: تصاحب حساب در یک شبکهٔ اجتماعی از طریق کارمند پشتیبانی‌ای که به درخواست، MFA را بازنشانی کرد؛ کاربران Fortify که کدهای بازیابی را با POST /user/two-factor-recovery-codes دوباره می‌سازند؛ شرکتی با دورهٔ انتظار ۷روزه به‌علاوهٔ اعلان ایمیلی برای حذف MFA بدون کد بازیابی؛ ده کد ۱۰نویسه‌ای تصادفی که چاپ و در کشو نگه داشته شده‌اند.

راه درست: ۸ تا ۱۰ کد که هر کدام دست‌کم ۶۴ بیت دارند، فقط یک بار نمایش داده می‌شوند، hash‌شده ذخیره می‌شوند و با استفاده می‌سوزند؛ گزینهٔ «دانلود / چاپ» و تأیید «ذخیره کردم» هنگام ثبت؛ اعلان برای هر استفاده؛ مسیری کند، ممیزی‌شده و out-of-band برای «همه‌چیز را گم کردم» (اثبات هویت، دورهٔ انتظار)؛ و هرگز اجازه ندهید SMS به‌تنهایی هم رمز و هم عامل دوم را بازنشانی کند.

Session سمت سرور و cookie حیاتی ​

به زبان ساده: بعد از ورود، سرور ثبت می‌کند «session x7Kp... مال حساب ۴۲ است، ساعت ۰۹:۰۰ با رمز + TOTP وارد شده» و فقط همان x7Kp... تصادفی را در یک cookie به مرورگر می‌دهد. هر درخواست cookie را برمی‌گرداند و سرور آن را جست‌وجو می‌کند.

بدفهمی رایج: «sessionها مقیاس‌پذیر نیستند.» جست‌وجو در Redis زیر یک میلی‌ثانیه است و Redis صدها هزار جست‌وجوی این‌چنینی را در ثانیه انجام می‌دهد؛ مسئلهٔ واقعی مقیاس، sticky session روی انبارهای درون‌حافظه‌ای است که با یک انبار مشترک حل می‌شود. برای ویژگی‌های cookie و CSRF، Web Sessions, Cookies, Serialization & CORS را ببینید.

تعریف: قواعد session در NIST SP 800-63B-4: secret مربوط به session "in direct response to an authentication event" ساخته می‌شود؛ cookieها "SHALL be tagged to be accessible only on secure (i.e., HTTPS) sessions"، "SHOULD be tagged as inaccessible via JavaScript (i.e., HttpOnly)"، "SHOULD have the "__Host-" prefix and set "Path=/""، "SHOULD set "SameSite=Lax" or "SameSite=Strict"" و "SHOULD contain only an opaque string". OWASP: شناسهٔ session به "at least 64 bits of entropy" نیاز دارد (اگر خودتان می‌سازید ۱۲۸ بیت توصیه می‌شود)؛ شناسه را "after any privilege level change" (ورود، step-up) عوض کنید تا جلوی Session fixation گرفته شود؛ و idle timeout و absolute timeout را اعمال کنید.

text
     Session fixation and the fix
1    attacker gets a pre-login session ID S from the site and plants it in the victim's browser (link, subdomain cookie)
2    victim logs in; naive server marks S as "user 42"
3    attacker, still holding S, is now user 42
     Fix: on login (and step-up) create a NEW ID: Laravel $request->session()->regenerate(); Go session.Store.Create
4    idle timeout 1 h (NIST AAL2 SHOULD), absolute 24 h: a session used every 30 min still ends at 24 h

سناریوی واقعی: monolith لاراولی با session driver از نوع database که در آن «خروج از همه‌جا» یعنی DELETE FROM sessions WHERE user_id = 42؛ سرویس Goی که sessionها را در Redis با EXPIRE برای idle timeout نگه می‌دارد؛ سایتی که sessionها را در حافظهٔ process نگه می‌داشت و با هر deploy همه را بیرون می‌انداخت؛ cookieی بدون HttpOnly که با یک XSS دزدیده شد.

چه چیزی آن را فراهم می‌کند:

محصولذخیره‌سازی و تنظیم‌ها
Laravel 13SESSION_DRIVER از میان file، cookie، database (پیش‌فرض در اپ‌های جدید)، redis، memcached، dynamodb، array؛ SESSION_LIFETIME به دقیقه؛ expire_on_close؛ secure، http_only، same_site؛ session()->regenerate()، invalidate()
Gosession داخلی ندارد: alexedwards/scs، gorilla/sessions یا یک انبار کوچک مثل بستهٔ session این فصل
Expressexpress-session با انبار Redis
SpringSpring Session (Redis، JDBC)
NGINX / Envoysessionهای اپ را مدیریت نمی‌کنند؛ شاید sticky routing انجام دهند (وقتی انبار مشترک است از آن پرهیز کنید)

راه درست: شناسهٔ تصادفی ۱۲۸+ بیتی؛ ذخیرهٔ user id، auth_time، amr، زمان ساخت، آخرین مشاهده، IP و user agent (برای صفحهٔ «دستگاه‌های شما»)؛ تعویض شناسه در ورود و step-up؛ اعمال idle و absolute timeout روی سرور، نه با انقضای cookie؛ cookie با __Host-، Secure، HttpOnly، SameSite=Lax؛ و یک index روی user id تا «خروج از همه‌جا» یک query باشد. کد: session.go.

توکن بی‌حالت (JWT)، توکن opaque و introspection حیاتی ​

به زبان ساده: JWT یک یادداشت امضاشده است که می‌گوید «این کاربر ۴۲ است، scopeهای X، معتبر تا ۰۹:۱۵»؛ هر کسی که کلید عمومی را دارد بدون پرسیدن از کسی آن را بررسی می‌کند. «توکن opaque» (Opaque token) یک رشتهٔ تصادفی است که خودش هیچ معنایی ندارد؛ API باید از authorization server بپرسد معنایش چیست.

بدفهمی رایج: «JWTها را با حذف از پایگاه داده باطل می‌کنیم.» چیزی برای حذف وجود ندارد: توکن تا exp هر جا ارائه شود معتبر است. ابطال یا به deny list نیاز دارد (که lookup را برمی‌گرداند) یا به عمر کوتاه به‌علاوهٔ refresh token.

تعریف: «توکن بی‌حالت» (Stateless token) یا خودبسنده claimها و یک امضا (JWS) را با خود دارد و بررسی‌اش محلی است. توکن opaque (مرجع) دسته‌ای به وضعیت سمت سرور است. Token introspection در RFC 7662 اجازه می‌دهد resource server توکن را به authorization server POST کند و JSONی با boolean «REQUIRED» به نام active به‌علاوهٔ scope، client_id، sub، exp بگیرد. بسیاری از سیستم‌ها ترکیبی کار می‌کنند: opaque یا session در لبه و JWT کوتاه بین سرویس‌های داخلی (الگوی «phantom token»: gateway توکن را introspect می‌کند و یک JWT جلو می‌فرستد). قالب، الگوریتم‌ها و دام‌های اعتبارسنجی JWT مال JWT Deep Dive است.

Server-side sessionStateless JWTOpaque token + introspectionBrowserAppRedis / tableClientServicedeny list?ClientAPIAuth servercookie: opaque ID onlyHttpOnly, Secure, SameSitelookup on every requestrevoke: delete row, instantbest for browserssigned claims, verify locallyno lookup, scales freelyrevoke: wait for expkeep exp at 5 to 15 minbest between servicesrandom string, RFC 7662active: true / falsecache the answer brieflyrevoke: instant (or TTL)best for third-party APIsHybrid: session or opaque token at the edge (BFF, gateway), short JWT inside, rotating refresh tokens for mobile apps.

این تصویر سه راه حمل اثبات را کنار هم می‌گذارد: session سمت سرور با cookie و جست‌وجو در Redis یا جدول (ابطال فوری)، JWT بی‌حالت که هر سرویس محلی بررسی می‌کند (ابطال با انتظار تا exp)، و توکن opaque که API با introspection از authorization server می‌پرسد (ابطال فوری یا به‌اندازهٔ TTL کش). خط پایین الگوی ترکیبی را نشان می‌دهد.

text
     User 42 is fired at 10:00; admin revokes access
1    session cookie      10:00:01 next request: row deleted -> 401                         (instant)
2    JWT exp 15 min      10:00:01 .. 10:14:59 every service still accepts the token          (up to 15 min)
3    JWT exp 24 h        valid until tomorrow 09:00 unless every service checks a deny list  (do not do this)
4    opaque + introspect 10:00:01 introspection returns {"active": false}; with a 30 s cache: up to 30 s

سناریوی واقعی: mesh میکروسرویسی که در آن gateway session کاربر را بررسی می‌کند و برای سرویس‌های پایین‌دستی یک JWT پنج‌دقیقه‌ای می‌سازد؛ API عمومی با توکن opaque چون شرکا باید فوراً قطع شوند؛ اپ موبایلی که یک access token از نوع JWT پانزده‌دقیقه‌ای و یک refresh token چرخشی دارد؛ احراز هویت SPA در Laravel Sanctum که اصلاً توکن ندارد و فقط cookie session است ("Sanctum does not use tokens of any kind").

چه چیزی آن را فراهم می‌کند:

محصولسبک توکن
Laravel Sanctumpersonal access token از نوع opaque، ذخیره با SHA-256، abilityها، expiration اختیاری؛ حالت SPA با cookie session
Laravel Passportسرور کامل OAuth 2.0: access token از نوع JWT و refresh token
Keycloak، Auth0، Okta، Cognitoaccess token و ID token از نوع JWT؛ endpoint مربوط به introspection (Keycloak، Okta)؛ refresh token
Ory Hydraaccess token از نوع opaque یا JWT، introspection مطابق RFC 7662
Envoy / Kong / AWS API Gatewayفیلترها/authorizerهای احراز JWT؛ ext_authz در Envoy برای introspection

راه درست: مرورگر روی دامنهٔ خودتان: session سمت سرور. شخص ثالث و شرکا: توکن opaque با introspection (کش چند ثانیه، نه چند دقیقه). سرویس‌های داخلی: JWT کوتاه (۵ تا ۱۵ دقیقه) با audience محدود. هرگز JWT بلندمدت را در localStorage نگذارید.

Refresh token: چرخش، تشخیص استفادهٔ مجدد، DPoP و token binding حیاتی ​

به زبان ساده: access token را کوتاه‌عمر نگه دارید و به کلاینت توکن دوم و بلندتری بدهید که فقط برای گرفتن access token جدید کاربرد دارد. هر بار که استفاده می‌شود آن را با یکی تازه عوض کنید؛ اگر روزی یک نسخهٔ قدیمی برگشت، یعنی کسی آن را کپی کرده، پس کل زنجیره را لغو کنید.

بدفهمی رایج: «چرخش یعنی refresh token دزدیده‌شده بی‌خطر است.» چرخش (Rotation) دزدی را فقط وقتی تشخیص می‌دهد که هر دو طرف از توکن استفاده کنند؛ اگر دزد زودتر استفاده کند و کلاینت واقعی دیگر refresh نکند، دزد تا پایان عمر مطلق family یک session دارد. به همین دلیل family به انقضای مطلق نیاز دارد، و به همین دلیل sender-constraining (DPoP، mTLS) جایگزین قوی‌تر است.

تعریف: RFC 6749: "Refresh tokens MUST be kept confidential in transit and storage". RFC 9700 بخش 4.14.2: چرخش یعنی "the authorization server issues a new refresh token with every access token refresh response. The previous refresh token is invalidated, but information about the relationship is retained"؛ و در «تشخیص استفادهٔ مجدد» (Reuse detection): "The authorization server cannot determine which party submitted the invalid refresh token, but it will revoke the active refresh token." Family (grant) زنجیرهٔ توکن‌های یک ورود است. DPoP (RFC 9449) توکن‌ها را به کلیدی در دست کلاینت گره می‌زند: هر درخواست یک header به نام DPoP با یک proof JWT امضاشده دارد (htm، htu، iat، jti و برای access token، ath)؛ و توکن thumbprint کلید را حمل می‌کند (cnf.jkt). Token binding (RFC 8471، ۲۰۱۸) توکن‌ها را به لایهٔ TLS گره می‌زد؛ پشتیبانی گسترده در مرورگرها پیدا نکرد، و RFC 9700 دو روش mTLS (RFC 8705) و DPoP را به‌عنوان روش‌های "in use in practice" نام می‌برد.

ClientAuth serverAttackerRotation turns a stolen refresh token into an alarmloginissue RT1 (family F)refresh with RT1RT1 used, issue RT2RT1 presented againreuse: revoke Frefresh with RT2invalid_grantRT1 copied (XSS, log,backup, malware)thief replays RT1gets nothingRT2user signs in again(cost of the alarm)Store only SHA-256 of each token; lock the row while rotating; give the family an absolute lifetime.

تصویر چرخش را روی خط زمان نشان می‌دهد: کلاینت با RT1 وارد می‌شود و هنگام refresh توکن RT2 را می‌گیرد؛ مهاجمی که RT1 را دزدیده آن را دوباره ارائه می‌کند، سرور توکن استفاده‌شده را می‌بیند و کل family را باطل می‌کند، و RT2 کلاینت هم دیگر کار نمی‌کند. هزینهٔ این هشدار، ورود دوبارهٔ کاربر است.

text
     Family F, idle TTL 14 days, absolute TTL 30 days
1    day 0    login                       RT1 issued (F)
2    day 10   client refresh with RT1     RT1 used; RT2 issued
3    day 11   attacker replays RT1        RT1 already used -> revoke F, log refresh_token.reuse_detected
4    day 12   client refresh with RT2     invalid_grant -> user signs in again
5    day 30   any token of F              absolute lifetime over: invalid_grant even if never stolen

سناریوی واقعی: اپ بانکی موبایلی که refresh token را در Keychain/Keystore نگه می‌دارد؛ SPAی که refresh tokenش باید بچرخد چون مرورگر کلاینت عمومی است؛ دو زبانهٔ مرورگر که هم‌زمان refresh می‌کنند و تشخیص استفادهٔ مجدد را فعال می‌کنند (راه‌حل: بازهٔ کوتاه استفادهٔ مجدد یا فقط یک refresh در جریان)؛ endpoint خروجی که family را باطل می‌کند، نه فقط توکن فعلی را.

چه چیزی آن را فراهم می‌کند:

محصولرفتار
Auth0Refresh token rotation با "Automatic reuse detection": در استفادهٔ مجدد Auth0 "immediately invalidates the refresh token family"
Keycloakتنظیم realm با نام "Revoke Refresh Token": "When Enabled, Keycloak revokes refresh tokens and issues another token that the client must use"
Amazon Cognitoچرخش اختیاری refresh token به‌ازای app client؛ با فعال بودنش REFRESH_TOKEN_AUTH در InitiateAuth مجاز نیست و باید از GetTokensFromRefreshToken یا token endpoint استفاده کرد
Laravel Passportgrant از نوع refresh_token در OAuth 2.0؛ ابطال با متد revoke روی مدل Laravel\Passport\RefreshToken
این فصلبستهٔ Go refresh و سرویس RefreshTokens در Laravel: ذخیرهٔ SHA-256، family، عمر مطلق، تشخیص استفادهٔ مجدد

راه درست: refresh token از نوع opaque که با SHA-256 ذخیره می‌شود؛ چرخش با ابطال family هنگام استفادهٔ مجدد؛ عمر idle و مطلق؛ قفل ردیف هنگام چرخش؛ بازهٔ کوتاه استفادهٔ مجدد فقط اگر کلاینت‌های واقعی با هم مسابقه می‌دهند؛ DPoP یا mTLS برای کلاینت‌های پرارزش؛ ابطال familyها در logout، تغییر رمز و بازیابی. کد: refresh.go، RefreshTokens.php.

جریان بازنشانی رمز حیاتی ​

به زبان ساده: «رمز را فراموش کرده‌ام» خودش یک روش ورود است: هر کس لینک بازنشانی (Password reset) را در دست داشته باشد حساب را در دست دارد. پس لینک باید غیرقابل‌حدس، کوتاه‌عمر، یک‌بارمصرف و hash‌شده باشد و استفاده از آن باید همهٔ sessionهای قدیمی را تمام کند.

بدفهمی رایج: «لینکی با user id و یک timestamp ایمیل می‌کنیم.» هر چیز قابل‌پیش‌بینی جعل‌شدنی است؛ هر چیزی که به‌صورت متن ساده ذخیره شود از پایگاه داده دزدیدنی است؛ و هر چیزی که بعد از استفاده زنده بماند از لاگ‌های ایمیل replay می‌شود.

تعریف: OWASP Forgot Password Cheat Sheet: "Return a consistent message for both existent and non-existent accounts"؛ توکن‌ها "Single use and expire after an appropriate period"؛ با CSPRNG ساخته و امن ذخیره شوند؛ URL را از روی header Host نسازید ("Host Header Injection")؛ روی صفحهٔ بازنشانی Referrer-Policy بگذارید؛ بعد از بازنشانی "Ask the user if they want to invalidate all of their existing sessions, or invalidate the sessions automatically"؛ و کاربر را خودکار وارد نکنید. NIST رمز تغییریافته را رخدادی می‌داند که به اعلان نیاز دارد.

text
     Reset done right
1    POST /forgot-password ada@...       queue job; respond "If an account exists, we sent a link"   (same for unknown)
2    job                                  token = 256 random bits; store SHA-256 (Laravel: bcrypt) + expires_at; email link
3    POST /reset-password token, new pw   find by hash, check expiry, delete row (single use)
4                                         set new hash; rotate remember_token; delete sessions; revoke API + refresh tokens
5                                         notify "your password was changed" to the address; redirect to login (no auto-login)

سناریوی واقعی: لینک بازنشانی‌ای که از طریق header Referer به یک اسکریپت تحلیلی روی صفحهٔ بازنشانی نشت کرد؛ مهاجمی که با header Host مسموم درخواست بازنشانی فرستاد تا لینک‌ها به سرور خودش اشاره کنند؛ رمزی که مهاجم عوض کرد ولی session قدیمی‌اش هفته‌ها زنده ماند چون بازنشانی sessionها را باطل نمی‌کرد؛ endpoint بازنشانی بدون محدودیت نرخ که برای بمباران ایمیلی قربانی استفاده شد.

چه چیزی آن را فراهم می‌کند:

محصولرفتار
password broker در LaravelPassword::sendResetLink()، Password::reset()؛ driver از نوع database یک hash از نوع bcrypt از توکنی با شکل hash_hmac('sha256', Str::random(40), key) ذخیره می‌کند؛ expire شصت دقیقه، throttle شصت ثانیه؛ driver از نوع cache با کلید SHA-256 ایمیل؛ auth:clear-resets پاک‌سازی می‌کند
statusهای LaravelPassword::ResetLinkSent، PasswordReset، InvalidUser، InvalidToken، ResetThrottled (برای سه‌تای اول یک پیام نشان دهید)
Go (این فصل)بستهٔ reset: SHA-256، یک‌بارمصرف، فقط جدیدترین، base URL ثابت
Auth0، Okta، Cognito، Keycloakجریان‌های بازنشانی میزبانی‌شده با عمر لینک و قالب قابل‌تنظیم

راه درست: خط زمانی بالا را ببینید؛ به‌علاوهٔ محدودیت به‌ازای ایمیل و IP، header Referrer-Policy: no-referrer، و اگر حساب MFA دارد، MFA بعد از بازنشانی هم لازم بماند («توکن یک‌بارمصرف» (Single-use token) بازنشانی فقط کنترل صندوق ایمیل را ثابت می‌کند، نه عامل دوم را).

Remember me، logout everywhere و step-up authentication مهم ​

به زبان ساده: «مرا به خاطر بسپار» (Remember me) کاربر را بعد از بستن مرورگر هم وارد نگه می‌دارد؛ «خروج از همه‌جا» (Logout everywhere) همهٔ sessionها و توکن‌های کاربر را تمام می‌کند؛ step-up پیش از یک کار حساس اثبات تازه‌ای می‌خواهد، حتی اگر کاربر وارد باشد.

بدفهمی رایج: «خروج از همه‌جا یعنی حذف cookie فعلی.» گوشی کاربر، لپ‌تاپ قدیمی، توکن‌های API، familyهای refresh token و cookie مربوط به remember me همه credentialهای جدا هستند. هر کدام ابطال خودش را لازم دارد.

تعریف: Remember me یک توکن بلندمدت و چرخشی در cookie جداست که session را دوباره می‌سازد (Laravel: ستون remember_token، "authenticated indefinitely or until they manually logout"؛ NIST: این قابلیت‌ها "SHALL NOT be used instead of authentication" مگر برای احراز دوبارهٔ AAL2 بعد از سقف بی‌فعالیتی). Logout everywhere همهٔ sessionها و توکن‌های حساب را باطل می‌کند (Laravel: Auth::logoutOtherDevices($password) همراه middleware auth.session که رمز را دوباره hash می‌کند تا AuthenticateSession sessionهای دیگر را رد کند). Step-up authentication لازم می‌داند که auth_time تازه باشد یا amr روش قوی‌تری داشته باشد (در OIDC با max_age و acr_values؛ در Laravel با password.confirm و auth.password_timeout که پیش‌فرضش 10800 ثانیه یعنی ۳ ساعت است).

text
     Step-up before changing the account email
1    09:00  login with password + TOTP                 auth_time 09:00, amr [pwd, otp]
2    09:40  POST /settings/email                       now - auth_time = 40 min > 10 min -> 401, ask passkey or password
3    09:41  passkey assertion OK                       session ID rotated, auth_time 09:41, amr [pwd, otp, hwk]
4    09:41  POST /settings/email (retry)               fresh -> allowed; notify the OLD address

سناریوی واقعی: کاربری که لپ‌تاپش دزدیده شد و روی «خروج از همهٔ دستگاه‌ها» کلیک کرد؛ اپ بانکی که پیش از انتقال بیش از یک سقف Face ID می‌خواهد؛ middleware password.confirm در Laravel روی «حذف حساب»؛ توکن remember me که هرگز نچرخید و یک سال از روی cookie کپی‌شده کار کرد.

راه درست: توکن remember me با هر استفاده بچرخد و با تغییر رمز بمیرد؛ صفحهٔ «دستگاه‌های شما» sessionها را با زمان ساخت، آخرین مشاهده، IP و UA فهرست کند و اجازهٔ پایان دادن به هرکدام را بدهد؛ خروج از همه‌جا sessionها را حذف کند، remember_token را بچرخاند، توکن‌های API را حذف و familyهای refresh را باطل کند؛ step-up برای تغییر ایمیل/رمز/MFA، افزودن passkey، نمایش کدهای بازیابی، برداشت پول و کارهای مدیریتی. کد: session.go، SecurityController.php.

SSO، OAuth و احراز سرویس به سرویس تکمیلی ​

به زبان ساده: با SSO کاربر یک بار نزد ارائه‌دهندهٔ هویت احراز می‌شود و اپ شما یک بیانیهٔ امضاشده دربارهٔ آن می‌گیرد؛ ماشین‌ها با کلید یا گواهی احراز می‌شوند، نه با رمز.

بدفهمی رایج: «OAuth یک پروتکل احراز هویت است.» OAuth 2.0 مجوزدهی تفویضی است؛ OpenID Connect، ID token را اضافه می‌کند که احراز هویت را حمل می‌کند (sub، auth_time، amr، acr). جزئیات مال OAuth 2.0, OpenID Connect & Single Sign-On است.

تعریف: با OIDC اپ شما relying party برای Keycloak، Auth0، Okta، Entra ID یا Cognito می‌شود: redirect می‌کند، یک code می‌گیرد، آن را با توکن عوض می‌کند، ID token را بررسی می‌کند و session محلی خودش را می‌سازد. هویت ماشین‌ها با client credentials، mTLS (Mutual TLS)، هویت SPIFFE در mesh یا workload identity ابری است؛ هرگز با رمز سرویس مشترک در یک فایل تنظیمات.

text
1    user -> app: GET /login                 app redirects to IdP /authorize (PKCE)
2    IdP: password + passkey                  IdP session; redirect back with code
3    app -> IdP: POST /token                  ID token (sub, amr, auth_time) + access/refresh tokens
4    app: validate ID token, create session   local session; IdP logout handled via back-channel logout

سناریوی واقعی: اپ B2Bی که «ورود با SSO شرکت شما» را از طریق SAML/OIDC به‌ازای هر tenant پشتیبانی می‌کند؛ سرویس‌های داخلی که با گواهی‌های mTLS صادرشده توسط mesh (Istio) احراز می‌شوند؛ cron jobی که به‌جای کلید API ثابت از توکن کوتاه‌عمر workload ابری استفاده می‌کند.

راه درست: وقتی چند اپ یا تقاضای SSO سازمانی دارید یک IdP بخرید یا خودتان میزبانی کنید؛ sessionهای محلی را کوتاه نگه دارید و logout در IdP را رعایت کنید؛ به هر ماشین هویت خودش را با چرخش بدهید.

ممیزی رخدادهای احراز هویت مهم ​

به زبان ساده: هر ورود، شکست، تغییر MFA، تغییر رمز، بازنشانی و ابطال توکن را با چه کسی، کی، از کجا و چطور ثبت کنید، ولی هرگز خود secret را.

بدفهمی رایج: «بدنهٔ درخواست را برای دیباگ لاگ می‌کنیم.» آن‌وقت لاگ‌ها رمز، OTP و توکن بازنشانی دارند. رخداد را لاگ کنید، نه credential را.

تعریف: یک رخداد ممیزی احراز هویت نوعی دارد (login.succeeded، login.failed، login.throttled، mfa.enabled، mfa.disabled، recovery_code.used، password.changed، password.reset_requested، session.revoked، refresh_token.reuse_detected، passkey.registered)، به‌علاوهٔ حساب (یا hash شناسهٔ امتحان‌شده)، زمان، IP، user agent، amr، نتیجه و یک correlation id. NIST برای رخدادهای اتصال authenticator و بازیابی، اعلان به کاربر را الزامی می‌کند؛ OWASP Logging Cheat Sheet موفقیت و شکست احراز هویت را از رخدادهای قابل‌ثبت می‌داند.

text
     Event stream used for detection
1    09:00:01 login.failed email_hash=ab12.. ip=198.51.100.7
2    09:00:01 login.failed email_hash=cd34.. ip=198.51.100.7      (x 400 in 60 s from one /24 -> spraying alert)
3    09:05:12 login.succeeded user=42 amr=[pwd] new_device=true    -> email "new sign-in"
4    09:06:40 mfa.disabled user=42                                 -> email + push "MFA turned off"; high-risk flag

سناریوی واقعی: تشخیص stuffing از روی نسبت ورود ناموفق به موفق در هر دقیقه؛ قاعدهٔ SOC برای «MFA ظرف ۱۰ دقیقه بعد از ورود از دستگاه جدید خاموش شد»؛ لاگ‌های سازگار با GDPR که برای شکست حساب‌های ناموجود یک hash کلیددار از ایمیل نگه می‌دارند؛ ذخیره‌سازی تغییرناپذیر برای انطباق (SOC 2، PCI DSS).

راه درست: یک جدول auth_events یا جریان لاگ با فیلدهای بالا؛ «فعالیت اخیر» برای کاربر از روی آن؛ هشدار روی تغییر نرخ و نسبت؛ نگه‌داری طبق سیاست. لاگ‌گیری گسترده‌تر مال Secure SDLC, Logging & Incident Response است.

سازوکار ​

قالب hashهایی که می‌بینید ​

پیشوند / شکلطرحنمونه (کوتاه‌شده)چطور بخوانیم
$argon2id$v=19$m=65536,t=4,p=1$salt$hashArgon2id، قالب رشتهٔ PHC$argon2id$v=19$m=65536,t=4,p=1$S7Xu...$ylCv... (پیش‌فرض PHP 8.5، اندازه‌گیری‌شده)نسخهٔ 19 (0x13)، حافظه به KiB، تعداد گذر، lane، Base64 بدون padding
$2y$12$ به‌علاوهٔ ۵۳ نویسهbcrypt (در PHP)، cost 12$2y$12$SmVw2j1rEScoC.5CDpEMiu...salt ۲۲نویسه‌ای + hash ۳۱نویسه‌ای با الفبای Base64 خود bcrypt
$2a$ / $2b$bcrypt (در Go، OpenBSD، Node)$2a$10$...همان؛ Go پیشوندهای $2a$/$2b$ را می‌پذیرد؛ کد این فصل $2y$ را به $2a$ نگاشت می‌کند
$scrypt$ln=17,r=8,p=1$...scrypt (سبک PHC، passlib)ln همان log2(N) است
pbkdf2_sha256$600000$salt$hashPBKDF2 در Djangoتعداد تکرار داخل رشته است
{bcrypt}$2a$...DelegatingPasswordEncoder در Springشناسهٔ داخل آکولاد encoder را انتخاب می‌کند
۳۲ یا ۴۰ نویسهٔ hex بدون saltMD5 / SHA-1قدیمی: همین حالا wrap کنید و در ورود مهاجرت دهید

آنچه روی PHP 8.5.0 (همین ماشین) اندازه گرفتیم: password_hash(str_repeat("a", 80), PASSWORD_BCRYPT) موفق می‌شود و password_verify با ۷۲ نویسهٔ اول به‌علاوهٔ هر چیز دیگر true برمی‌گرداند؛ یعنی بایت ۷۳ به بعد نادیده گرفته می‌شود. BcryptHasher در Laravel فقط وقتی bcrypt.limit تنظیم شده باشد ورودی بلندتر را رد می‌کند ("Value is too long to hash. Value must be less than 72 bytes.")؛ bcrypt.GenerateFromPassword در Go همیشه ErrPasswordTooLong برمی‌گرداند.

هزینه و ظرفیت اندازه‌گیری‌شده ​

یک اجرای برنامهٔ آزمایشگاه این فصل روی Apple M4 Pro با Go 1.27، هر بار یک hash (عددها بین اجراها حدود ۳۰٪ جابه‌جا می‌شوند؛ روی نوع instance خودتان اندازه بگیرید):

تنظیمزمان هر hashhash در ثانیه (یک فراخوان)حافظهٔ هر hash
Argon2id با m=19 MiB t=2 p=1 (OWASP)16 ms6219 MiB
Argon2id با m=46 MiB t=1 p=1 (OWASP)21 ms4746 MiB
Argon2id با m=64 MiB t=4 p=1 (پیش‌فرض PHP و Laravel)131 ms864 MiB
Argon2id با m=64 MiB t=3 p=4 (گزینهٔ دوم RFC 9106، چهار goroutine)27 ms3764 MiB
bcrypt با cost 1048 ms214 KiB
bcrypt با cost 12 (پیش‌فرض Laravel)193 ms54 KiB
bcrypt با cost 14761 ms14 KiB

ظرفیت، حساب سرانگشتی (برآورد). اوج ۲۰۰ ورود در ثانیه با Argon2id با 19 MiB و t=2 که هر کدام حدود ۲۰ میلی‌ثانیه از یک هسته می‌گیرد: 200 x 0.02 = ۴ هستهٔ مشغول hash، و به‌طور میانگین حدود ۴ hash در جریان، یعنی تقریباً 4 x 19 MiB = 76 MiB حافظهٔ hash (برای burst ده برابر جا بگذارید: ظرفیت burst معادل ۴۰ هسته یا یک صف). همین نرخ با bcrypt و cost 12 به 200 x 0.19 = ۳۸ هسته نیاز دارد. یک burst از credential stuffing با ۵۰۰۰ تلاش در ثانیه که به hasher برسد با Argon2id صد هسته لازم دارد: برای همین throttling باید پیش از hash اجرا شود.

سمت مهاجم (برآورد). مهاجم آفلاینی که dump شما را دارد برای هر حدس و هر hash همین هزینه را می‌دهد. با ۶۲ حدس Argon2id در ثانیه به‌ازای هر هسته، امتحان ۱۰,۰۰۰ رمز رایج روی یک حساب حدود ۱۶۰ هسته-ثانیه و روی یک میلیون حساب حدود ۵ هسته-سال طول می‌کشد. با pepper اصلاً نمی‌تواند شروع کند.

حساب TOTP ​

کمیتمقدارمنبع
گام زمانی X۳۰ ثانیهٔ توصیه‌شدهRFC 6238
T00 (Unix epoch)RFC 6238
شمارندهfloor(unix_time / 30) در ۸ بایت big-endianRFC 6238 / RFC 4226
HMACSHA-1 (اپ‌ها)، SHA-256 و SHA-512 مجازRFC 6238
بریدن (Truncation)offset برابر ۴ بیت پایین بایت آخر؛ عدد ۳۱ بیتی؛ mod 10^digitsRFC 4226 بخش 5.3
طول secret۱۶۰ بیت توصیه‌شده (۲۰ بایت، ۳۲ نویسهٔ Base32)RFC 4226
انحراف"at most one time step" برای تأخیر شبکه؛ ثبت انحراف به‌ازای کاربرRFC 6238 بخش‌های 5.2 و 6
پنجره با skew برابر ۱سه کد هم‌زمان معتبر؛ هر کد تا ۹۰ ثانیه قابل‌استفادهحساب
حدس زدن کد شش‌رقمیبا skew برابر ۱، در هر تلاش ۳ در ۱,۰۰۰,۰۰۰حساب
حدس آنلاین مجازحداکثر ۱۰۰ شکست متوالی به‌ازای هر authenticatorNIST SP 800-63B-4
بردار آزمونsecret برابر "12345678901234567890"، t = 59 s، SHA-1، ۸ رقم = 94287082RFC 6238 پیوست B

داده‌هایی از WebAuthn که ذخیره می‌کنید ​

فیلداز کجاچرا
Credential IDثبتپیدا کردن کلید؛ ارسال در allowCredentials/excludeCredentials
کلید عمومی (COSE)ثبتبررسی امضای هر assertion
User handleشناسهٔ تصادفی ۶۴بایتی شماتوسط discoverable credential برگردانده می‌شود؛ نباید ایمیل باشد
Sign countهر assertionتشخیص کلون؛ passkeyهای همگام‌شونده اغلب 0 گزارش می‌کنند
پرچم‌های UP، UV، BE، BSauthenticatorDataUV یعنی دو عامل در یکی؛ BE/BS یعنی همگام‌شونده یا نه
AAGUID، قالب attestationثبتمدل authenticator (با attestation)؛ سیاست برای AAL3
Transportهاثبتراهنما (internal، usb، hybrid، nfc، ble)
نام، زمان ساخت، آخرین استفادهرابط کاربری شما«passkey مک‌بوک، آخرین استفاده دیروز»

DOMExceptionهایی که مرورگر برمی‌گرداند: NotAllowedError (کاربر لغو کرد، زمان تمام شد یا credentialی نبود)، InvalidStateError (یکی از authenticatorهای excludeCredentials قبلاً ثبت شده)، SecurityError (RP ID برای این origin دامنهٔ معتبری نیست).

تنظیم‌های هر محصول ​

محصولتنظیمپیش‌فرض (از مستندات یا کد منبع)
config/hashing.php در Laraveldriver، bcrypt.rounds، bcrypt.limit، argon.memory/time/threads، rehash_on_login، verifybcrypt، 12، null، 65536/4/1، true، true
config/auth.php در Laravelpasswords.users.expire، .throttle، password_timeout۶۰ دقیقه، ۶۰ ثانیه، 10800 ثانیه
SessionGuard در Laravelمدت Timebox برای attempt/validate200,000 µs
stub در Laravel Fortifylimiters.login، limiters.two-factor، limiters.passkeys، lowercase_usernames، twoFactorAuthentication(['confirm', 'confirmPassword', 'window'])۵ در دقیقه با ایمیل+IP، ۵ در دقیقه با login.id، ۱۰ در دقیقه با credential/session+IP، true، confirm روشن
Laravel Sanctumexpiration (دقیقه)، sanctum:prune-expirednull (هرگز منقضی نمی‌شود)
Go با x/crypto/bcryptcostDefaultCost برابر 10
Go با pquerna/otp/totpPeriod، Skew، Digits، Algorithm، SecretSize30، 0، 6، SHA1، ۲۰ بایت
Go با go-webauthnRPID، RPOrigins، AttestationPreference، AuthenticatorSelection، Timeoutsندارد؛ RPID و originها را باید خودتان بدهید
Keycloak Brute Force Detection (lockout دائمی)Max Login Failures، Quick Login Check Milliseconds، Minimum Quick Login Wait30، 1000 ms، یک دقیقه
NIST SP 800-63B-4احراز دوبارهٔ AAL2، کل / بی‌فعالیتیSHOULD حداکثر ۲۴ ساعت / ۱ ساعت
NIST SP 800-63B-4احراز دوبارهٔ AAL3، کل / بی‌فعالیتیحداکثر ۱۲ ساعت / SHOULD پانزده دقیقه
OWASP Session Managementآنتروپی شناسهٔ sessionدست‌کم ۶۴ بیت

پیام‌های خطا و status codeهایی که واقعاً می‌بینید ​

کجاپیام یا کدمعنا
auth.failed در Laravel"These credentials do not match our records."شکست ورود (یکسان)
auth.throttle در Laravel"Too many login attempts. Please try again in :seconds seconds."limiter ورود فعال شد (HTTP 429 از طریق ThrottleRequests، یا خطای اعتبارسنجی در starter kitها)
auth.password در Laravel"The provided password is incorrect."قاعدهٔ current_password شکست خورد
passwords.sent / .user / .throttled / .token / .reset در Laravel"We have emailed your password reset link." / "We can't find a user with that email address." / "Please wait before retrying." / "This password reset token is invalid." / "Your password has been reset."statusهای broker؛ نمایش .user و .throttled وجود حساب را لو می‌دهد
BcryptHasher در Laravel"This password does not use the Bcrypt algorithm." (RuntimeException)HASH_VERIFY=true و hashی از driver دیگر؛ در دوران مهاجرت HASH_VERIFY=false بگذارید
logoutOtherDevices در Laravel"The given password does not match the current password." (InvalidArgumentException)رمز تأیید غلط
XHR در Fortify422 با خطاهای اعتبارسنجی؛ 204 بعد از two-factor challenge موفق؛ two_factor: true در JSON ورودجریان دومرحله‌ای برای SPAها
Go با x/crypto/bcryptbcrypt: password length exceeds 72 bytes، crypto/bcrypt: hashedPassword is not the hash of the given passwordErrPasswordTooLong، ErrMismatchedHashAndPassword
token endpoint در OAuth 2.0400 {"error":"invalid_grant"}refresh token منقضی، باطل، تکراری یا ناشناخته
OAuth / DPoP401 با WWW-Authenticate: DPoP error="use_dpop_nonce"سرور nonce تازه در DPoP proof می‌خواهد
HTTP401 (شما کیستید؟)، 403 (مجاز نیستید)، 429 + Retry-After (آهسته‌تر)برای «چنین کاربری نداریم» از 404 استفاده نکنید

Schema ​

جدول‌هایی که یک سیستم ورود لازم دارد، با نحو PostgreSQL (migration لاراول در بخش Laravel همین‌ها را می‌سازد):

sql
CREATE TABLE users (
  id                 bigserial PRIMARY KEY,
  email              citext UNIQUE NOT NULL,          -- normalised, case-insensitive
  password_hash      text,                            -- PHC string; NULL for passkey-only accounts
  password_changed_at timestamptz,
  password_disabled_at timestamptz,                   -- set at the hard failure limit; cleared by reset
  disabled_at        timestamptz
);

CREATE TABLE mfa_totp (
  user_id      bigint PRIMARY KEY REFERENCES users(id) ON DELETE CASCADE,
  secret_enc   bytea NOT NULL,                        -- encrypted with a KMS key, never plaintext
  confirmed_at timestamptz,                           -- NULL until the first valid code
  last_step    bigint NOT NULL DEFAULT 0              -- replay guard: accepted step must be > last_step
);

CREATE TABLE recovery_codes (
  id        bigserial PRIMARY KEY,
  user_id   bigint NOT NULL REFERENCES users(id) ON DELETE CASCADE,
  code_hash text NOT NULL,                            -- Argon2id or SHA-256 of a 64+ bit code
  used_at   timestamptz
);

CREATE TABLE webauthn_credentials (
  id            bytea PRIMARY KEY,                    -- credential ID
  user_id       bigint NOT NULL REFERENCES users(id) ON DELETE CASCADE,
  public_key    bytea NOT NULL,                       -- COSE key
  sign_count    bigint NOT NULL DEFAULT 0,
  backup_eligible boolean NOT NULL, backup_state boolean NOT NULL,
  aaguid        uuid, transports text[], name text,
  created_at    timestamptz NOT NULL DEFAULT now(), last_used_at timestamptz
);

CREATE TABLE sessions (
  id          text PRIMARY KEY,                       -- 256-bit random, or its SHA-256
  user_id     bigint NOT NULL REFERENCES users(id) ON DELETE CASCADE,
  auth_time   timestamptz NOT NULL, amr text[] NOT NULL,
  created_at  timestamptz NOT NULL, last_seen_at timestamptz NOT NULL,
  ip inet, user_agent text
);
CREATE INDEX sessions_user ON sessions (user_id);     -- "log out everywhere" is one DELETE

CREATE TABLE refresh_token_families (
  id bigserial PRIMARY KEY, user_id bigint NOT NULL REFERENCES users(id) ON DELETE CASCADE,
  expires_at timestamptz NOT NULL, revoked_at timestamptz
);
CREATE TABLE refresh_tokens (
  id bigserial PRIMARY KEY,
  family_id bigint NOT NULL REFERENCES refresh_token_families(id) ON DELETE CASCADE,
  token_hash bytea UNIQUE NOT NULL,                   -- SHA-256; 256-bit tokens need no slow hash
  expires_at timestamptz NOT NULL, used_at timestamptz
);

CREATE TABLE password_reset_tokens (
  token_hash bytea PRIMARY KEY, user_id bigint NOT NULL REFERENCES users(id) ON DELETE CASCADE,
  expires_at timestamptz NOT NULL
);

CREATE TABLE auth_events (
  id bigserial PRIMARY KEY, user_id bigint REFERENCES users(id) ON DELETE SET NULL,
  type text NOT NULL, ip inet, user_agent text, meta jsonb, created_at timestamptz NOT NULL DEFAULT now()
);

-- Rotation, atomically: lock the presented token, then decide
BEGIN;
SELECT t.id, t.used_at, t.expires_at, f.revoked_at
  FROM refresh_tokens t JOIN refresh_token_families f ON f.id = t.family_id
 WHERE t.token_hash = sha256($1::bytea) FOR UPDATE OF t, f;
-- used_at IS NOT NULL -> UPDATE refresh_token_families SET revoked_at = now() WHERE id = ...; COMMIT; reject
UPDATE refresh_tokens SET used_at = now() WHERE id = $2;
INSERT INTO refresh_tokens (family_id, token_hash, expires_at) VALUES ($3, $4, least(now() + interval '14 days', $5));
COMMIT;

-- Log out everywhere
DELETE FROM sessions WHERE user_id = 42;
UPDATE refresh_token_families SET revoked_at = now() WHERE user_id = 42 AND revoked_at IS NULL;

چرا SHA-256 برای توکن بازنشانی، شناسهٔ session و refresh token کافی است ولی برای رمز نه: این secretها ۱۲۸ تا ۲۵۶ بیت تصادفی دارند، پس چیزی برای حدس زدن نیست؛ NIST hash کند و salt‌دار را فقط برای secretهای کم‌آنتروپی ("shorter than ... 112 bits") الزامی می‌داند. broker بازنشانی در Laravel با این حال از bcrypt استفاده می‌کند، که ضرری ندارد.

Go ​

ماژول Go (academy/authentication-passwords-mfa-sessions) برای هر ایده یک بسته دارد و یک ساعت جعلی تا هر تایمر بدون sleep آزموده شود. وابستگی‌ها: golang.org/x/crypto نسخهٔ v0.43.0 (argon2، bcrypt)، golang.org/x/text نسخهٔ v0.30.0 (NFC)، github.com/pquerna/otp نسخهٔ v1.5.0 (برای مقایسه در تست‌ها)، github.com/go-webauthn/webauthn نسخهٔ v0.15.0. دستور go برابر 1.24.0 است چون go-webauthn v0.15.0 همین را اعلام می‌کند؛ v0.18.2 (جدیدترین نسخه در pkg.go.dev) به Go 1.26 نیاز دارد.

Before ​

handler ورودی که کار می‌کند و از شش جهت غلط است: SHA-256 بدون salt، enumeration با پیام، status و زمان، مقایسه با !=، نبود throttling، هویت داخل cookie و نبود پرچم‌های cookie:

go
// Command before is a login endpoint that "works" and is still wrong in six ways.
// It compiles and runs; every comment marks a design flaw, not a bug.
package main

import (
	"crypto/sha256"
	"encoding/hex"
	"log"
	"net/http"
)

// Flaw 1: a fast, unsalted hash. One GPU tries billions of guesses per second,
// and two users with the same password have the same hash.
var users = map[string]string{
	"ada@example.com": hashOf("Password1!"),
}

func hashOf(pw string) string {
	sum := sha256.Sum256([]byte(pw))
	return hex.EncodeToString(sum[:])
}

func login(w http.ResponseWriter, r *http.Request) {
	email := r.FormValue("email")
	password := r.FormValue("password")

	stored, ok := users[email]
	if !ok {
		// Flaw 2: a different message, status code and (no hashing) a faster
		// response tell an attacker which emails have accounts.
		http.Error(w, "no account with that email", http.StatusNotFound)
		return
	}
	// Flaw 3: == on hex strings is not constant time.
	// Flaw 4: no limit per account or per IP: brute force, stuffing and spraying are free.
	if hashOf(password) != stored {
		http.Error(w, "wrong password", http.StatusUnauthorized)
		return
	}
	// Flaw 5: the cookie carries the identity itself, not a random session secret;
	// anyone can set "user=ada@example.com" in their browser.
	// Flaw 6: no Secure, HttpOnly or SameSite, no expiry, no server-side state to revoke.
	http.SetCookie(w, &http.Cookie{Name: "user", Value: email})
	w.WriteHeader(http.StatusNoContent)
}

func main() {
	http.HandleFunc("POST /login", login)
	log.Fatal(http.ListenAndServe("127.0.0.1:8080", nil))
}

After ​

ساعت جعلی که همهٔ بسته‌ها از آن استفاده می‌کنند:

go
// Package clock lets every security timer in this module be tested without sleeping.
package clock

import (
	"sync"
	"time"
)

// Clock returns the current time.
type Clock interface{ Now() time.Time }

// System is the real wall clock.
type System struct{}

// Now returns time.Now().
func (System) Now() time.Time { return time.Now() }

// Fake is a manually advanced clock for tests.
type Fake struct {
	mu sync.Mutex
	t  time.Time
}

// NewFake starts a fake clock at t.
func NewFake(t time.Time) *Fake { return &Fake{t: t} }

// Now returns the fake time.
func (f *Fake) Now() time.Time {
	f.mu.Lock()
	defer f.mu.Unlock()
	return f.t
}

// Advance moves the fake time forward.
func (f *Fake) Advance(d time.Duration) {
	f.mu.Lock()
	f.t = f.t.Add(d)
	f.mu.Unlock()
}

رشته‌های PHC برای Argon2id، نرمال‌سازی NFC، pepper اختیاری، بررسی bcrypt قدیمی و needsRehash، با تست برای salt، ارتقای پارامتر، hashهای $2y$، محدودیت ۷۲ بایت و Unicode:

go
// Package pwhash stores passwords as Argon2id PHC strings, verifies legacy
// bcrypt hashes, and tells the caller when a stored hash must be upgraded.
package pwhash

import (
	"crypto/hmac"
	"crypto/rand"
	"crypto/sha256"
	"crypto/subtle"
	"encoding/base64"
	"errors"
	"fmt"
	"strings"

	"golang.org/x/crypto/argon2"
	"golang.org/x/crypto/bcrypt"
	"golang.org/x/text/unicode/norm"
)

// Params are the Argon2id cost parameters. Memory is in KiB.
type Params struct {
	Memory  uint32
	Time    uint32
	Threads uint8
	SaltLen uint32
	KeyLen  uint32
}

// OWASPMinimum is the OWASP Password Storage Cheat Sheet floor (m=19 MiB, t=2, p=1).
var OWASPMinimum = Params{Memory: 19 * 1024, Time: 2, Threads: 1, SaltLen: 16, KeyLen: 32}

// RFC9106Second is the RFC 9106 "SECOND RECOMMENDED" option (64 MiB, t=3, p=4).
var RFC9106Second = Params{Memory: 64 * 1024, Time: 3, Threads: 4, SaltLen: 16, KeyLen: 32}

// MaxPasswordBytes caps the input so a 10 MB "password" cannot become a DoS.
// NIST SP 800-63B-4 asks verifiers to permit at least 64 characters.
const MaxPasswordBytes = 1024

var (
	ErrTooLong       = errors.New("pwhash: password too long")
	ErrUnknownFormat = errors.New("pwhash: unknown hash format")
	ErrMalformed     = errors.New("pwhash: malformed hash")
)

// Hasher hashes with the current Params and an optional pepper (a secret key
// kept outside the database, for example in a KMS or HSM).
type Hasher struct {
	Params Params
	Pepper []byte
}

// prepare normalises to Unicode NFC (NIST SP 800-63B-4) and applies the pepper
// as HMAC-SHA-256 before the slow hash ("pre-hashing pepper").
func (h Hasher) prepare(password string) ([]byte, error) {
	if len(password) > MaxPasswordBytes {
		return nil, ErrTooLong
	}
	b := []byte(norm.NFC.String(password))
	if len(h.Pepper) == 0 {
		return b, nil
	}
	m := hmac.New(sha256.New, h.Pepper)
	m.Write(b)
	return m.Sum(nil), nil
}

// Hash returns a PHC string: $argon2id$v=19$m=19456,t=2,p=1$<salt>$<hash>.
func (h Hasher) Hash(password string) (string, error) {
	in, err := h.prepare(password)
	if err != nil {
		return "", err
	}
	p := h.Params
	salt := make([]byte, p.SaltLen)
	if _, err := rand.Read(salt); err != nil {
		return "", err
	}
	key := argon2.IDKey(in, salt, p.Time, p.Memory, p.Threads, p.KeyLen)
	b64 := base64.RawStdEncoding
	return fmt.Sprintf("$argon2id$v=%d$m=%d,t=%d,p=%d$%s$%s",
		argon2.Version, p.Memory, p.Time, p.Threads, b64.EncodeToString(salt), b64.EncodeToString(key)), nil
}

// Verify checks password against encoded. needsRehash is true when the hash
// was made with other parameters or another algorithm (bcrypt), so the caller
// should store h.Hash(password) now that it knows the plaintext.
func (h Hasher) Verify(password, encoded string) (ok, needsRehash bool, err error) {
	switch {
	case strings.HasPrefix(encoded, "$argon2id$"):
		return h.verifyArgon(password, encoded)
	case strings.HasPrefix(encoded, "$2a$"), strings.HasPrefix(encoded, "$2b$"), strings.HasPrefix(encoded, "$2y$"):
		// Legacy bcrypt hashes were created before the pepper existed.
		if len(password) > MaxPasswordBytes {
			return false, false, ErrTooLong
		}
		e := strings.Replace(encoded, "$2y$", "$2a$", 1) // PHP writes $2y$
		err := bcrypt.CompareHashAndPassword([]byte(e), []byte(norm.NFC.String(password)))
		if errors.Is(err, bcrypt.ErrMismatchedHashAndPassword) {
			return false, false, nil
		}
		if err != nil {
			return false, false, err
		}
		return true, true, nil // correct: migrate to Argon2id
	default:
		return false, false, ErrUnknownFormat
	}
}

func (h Hasher) verifyArgon(password, encoded string) (bool, bool, error) {
	parts := strings.Split(encoded, "$") // "", "argon2id", "v=19", "m=..,t=..,p=..", salt, hash
	if len(parts) != 6 {
		return false, false, ErrMalformed
	}
	var version int
	if _, err := fmt.Sscanf(parts[2], "v=%d", &version); err != nil || version != argon2.Version {
		return false, false, ErrMalformed
	}
	var p Params
	if _, err := fmt.Sscanf(parts[3], "m=%d,t=%d,p=%d", &p.Memory, &p.Time, &p.Threads); err != nil {
		return false, false, ErrMalformed
	}
	b64 := base64.RawStdEncoding
	salt, err := b64.DecodeString(parts[4])
	if err != nil {
		return false, false, ErrMalformed
	}
	want, err := b64.DecodeString(parts[5])
	if err != nil {
		return false, false, ErrMalformed
	}
	in, err := h.prepare(password)
	if err != nil {
		return false, false, err
	}
	got := argon2.IDKey(in, salt, p.Time, p.Memory, p.Threads, uint32(len(want)))
	if subtle.ConstantTimeCompare(got, want) != 1 {
		return false, false, nil
	}
	cur := h.Params
	stale := p.Memory != cur.Memory || p.Time != cur.Time || p.Threads != cur.Threads ||
		uint32(len(salt)) != cur.SaltLen || uint32(len(want)) != cur.KeyLen
	return true, stale, nil
}
go
package pwhash

import (
	"strings"
	"testing"

	"golang.org/x/crypto/bcrypt"
)

// Small parameters keep the tests fast; production uses OWASPMinimum or more.
var fast = Params{Memory: 1024, Time: 1, Threads: 1, SaltLen: 16, KeyLen: 32}

func TestHashAndVerify(t *testing.T) {
	h := Hasher{Params: fast}
	enc, err := h.Hash("correct horse battery staple")
	if err != nil {
		t.Fatal(err)
	}
	if !strings.HasPrefix(enc, "$argon2id$v=19$m=1024,t=1,p=1$") {
		t.Fatalf("unexpected encoding %q", enc)
	}
	ok, rehash, err := h.Verify("correct horse battery staple", enc)
	if err != nil || !ok || rehash {
		t.Fatalf("ok=%v rehash=%v err=%v", ok, rehash, err)
	}
	if ok, _, _ := h.Verify("correct horse battery stapler", enc); ok {
		t.Fatal("wrong password accepted")
	}
}

func TestSamePasswordDifferentSalt(t *testing.T) {
	h := Hasher{Params: fast}
	a, _ := h.Hash("same")
	b, _ := h.Hash("same")
	if a == b {
		t.Fatal("two hashes of the same password must differ (random salt)")
	}
}

func TestNeedsRehashWhenParamsGrow(t *testing.T) {
	old := Hasher{Params: fast}
	enc, _ := old.Hash("pw-1234567890")
	stronger := Hasher{Params: Params{Memory: 2048, Time: 2, Threads: 1, SaltLen: 16, KeyLen: 32}}
	ok, rehash, err := stronger.Verify("pw-1234567890", enc)
	if err != nil || !ok || !rehash {
		t.Fatalf("ok=%v rehash=%v err=%v, want ok and rehash", ok, rehash, err)
	}
}

func TestLegacyBcryptVerifiesAndAsksForUpgrade(t *testing.T) {
	legacy, err := bcrypt.GenerateFromPassword([]byte("legacy-password"), bcrypt.MinCost)
	if err != nil {
		t.Fatal(err)
	}
	h := Hasher{Params: fast}
	ok, rehash, err := h.Verify("legacy-password", string(legacy))
	if err != nil || !ok || !rehash {
		t.Fatalf("ok=%v rehash=%v err=%v", ok, rehash, err)
	}
	// PHP's password_hash writes $2y$; it verifies too.
	php := strings.Replace(string(legacy), "$2a$", "$2y$", 1)
	if ok, _, _ := h.Verify("legacy-password", php); !ok {
		t.Fatal("$2y$ prefix not accepted")
	}
}

func TestBcrypt72ByteLimit(t *testing.T) {
	long := strings.Repeat("a", 73)
	if _, err := bcrypt.GenerateFromPassword([]byte(long), bcrypt.MinCost); err != bcrypt.ErrPasswordTooLong {
		t.Fatalf("x/crypto/bcrypt should refuse 73 bytes, got %v", err)
	}
	// Argon2id has no such limit: two passwords sharing the first 72 bytes differ.
	h := Hasher{Params: fast}
	enc, _ := h.Hash(strings.Repeat("a", 72) + "X")
	if ok, _, _ := h.Verify(strings.Repeat("a", 72)+"Y", enc); ok {
		t.Fatal("argon2id must use the whole password")
	}
}

func TestUnicodeNormalisation(t *testing.T) {
	h := Hasher{Params: fast}
	composed := "café-password"    // é as one code point
	decomposed := "café-password" // e + combining acute accent
	enc, _ := h.Hash(composed)
	if ok, _, _ := h.Verify(decomposed, enc); !ok {
		t.Fatal("NFC normalisation should make both spellings equal")
	}
}

func TestPepperIsRequired(t *testing.T) {
	with := Hasher{Params: fast, Pepper: []byte("0123456789abcdef0123456789abcdef")}
	enc, _ := with.Hash("pw-with-pepper")
	without := Hasher{Params: fast}
	if ok, _, _ := without.Verify("pw-with-pepper", enc); ok {
		t.Fatal("a stolen database without the pepper must not verify")
	}
	if ok, _, _ := with.Verify("pw-with-pepper", enc); !ok {
		t.Fatal("pepper round trip failed")
	}
}

func TestRejectsHugeInputAndGarbage(t *testing.T) {
	h := Hasher{Params: fast}
	if _, err := h.Hash(strings.Repeat("x", MaxPasswordBytes+1)); err != ErrTooLong {
		t.Fatalf("want ErrTooLong, got %v", err)
	}
	if _, _, err := h.Verify("x", "$1$md5crypt$abc"); err != ErrUnknownFormat {
		t.Fatalf("want ErrUnknownFormat, got %v", err)
	}
	if _, _, err := h.Verify("x", "$argon2id$v=19$broken"); err != ErrMalformed {
		t.Fatalf("want ErrMalformed, got %v", err)
	}
}

ورود با خطای یکسان، hash ساختگی برای کاربر ناموجود، تأخیر تدریجی به‌ازای حساب، پنجرهٔ per-IP و rehash هنگام ورود. تست‌ها ثابت می‌کنند شکست کاربر ناموجود و رمز غلط یکسان است، تلاش throttleشده هرگز به hasher نمی‌رسد و spraying از یک IP متوقف می‌شود:

go
// Package login verifies a password without telling an attacker whether the
// account exists, and throttles guessing per account and per client IP.
package login

import (
	"context"
	"errors"
	"fmt"
	"strings"
	"sync"
	"time"

	"academy/authentication-passwords-mfa-sessions/clock"
)

// ErrInvalidCredentials is the only failure a caller may show the user.
var ErrInvalidCredentials = errors.New("invalid email or password")

// ThrottledError carries Retry-After; it is returned before any password work.
type ThrottledError struct{ RetryAfter time.Duration }

func (e *ThrottledError) Error() string {
	return fmt.Sprintf("too many attempts, retry after %s", e.RetryAfter)
}

// User is what the store returns.
type User struct {
	ID           int64
	Email        string
	PasswordHash string
	Disabled     bool
}

// Store loads users and saves upgraded hashes.
type Store interface {
	FindByEmail(ctx context.Context, email string) (User, bool, error)
	UpdatePasswordHash(ctx context.Context, userID int64, hash string) error
}

// PasswordHasher is implemented by pwhash.Hasher.
type PasswordHasher interface {
	Hash(password string) (string, error)
	Verify(password, encoded string) (ok, needsRehash bool, err error)
}

// Policy: progressive delay per account (no hard lockout an attacker can
// trigger for you), a hard limit per account that disables the password until
// reset (NIST SP 800-63B-4 allows at most 100), and a window limit per IP.
type Policy struct {
	FreeFailures   int           // failures before delays start
	BaseDelay      time.Duration // first delay, doubled per further failure
	MaxDelay       time.Duration
	HardLimit      int // consecutive failures that disable password login
	PerIPFailures  int // failures per IP per window (password spraying from one IP)
	PerIPWindow    time.Duration
	DummyPHCString string // a real hash of a random value, used for unknown users
}

// DefaultPolicy is a reasonable start for a consumer web login.
func DefaultPolicy(dummy string) Policy {
	return Policy{FreeFailures: 5, BaseDelay: time.Second, MaxDelay: 15 * time.Minute,
		HardLimit: 100, PerIPFailures: 50, PerIPWindow: 10 * time.Minute, DummyPHCString: dummy}
}

type accountState struct {
	failures  int
	notBefore time.Time
}

type ipState struct {
	failures    int
	windowStart time.Time
}

// Service is safe for concurrent use. In production the counters live in
// Redis or the database so every instance sees the same numbers.
type Service struct {
	Store  Store
	Hasher PasswordHasher
	Clock  clock.Clock
	Policy Policy

	mu       sync.Mutex
	accounts map[string]*accountState
	ips      map[string]*ipState
}

// Normalize is the account key: trimmed, lower-cased email.
func Normalize(email string) string { return strings.ToLower(strings.TrimSpace(email)) }

// Login returns the user on success. Every failure is ErrInvalidCredentials
// or *ThrottledError; both are the same for existing and missing accounts.
func (s *Service) Login(ctx context.Context, email, password, ip string) (User, error) {
	key := Normalize(email)
	if wait := s.throttled(key, ip); wait > 0 {
		return User{}, &ThrottledError{RetryAfter: wait}
	}

	u, found, err := s.Store.FindByEmail(ctx, key)
	if err != nil {
		return User{}, err
	}
	if !found {
		// Burn the same CPU and memory as a real check so timing does not
		// reveal that the account is missing.
		_, _, _ = s.Hasher.Verify(password, s.Policy.DummyPHCString)
		s.fail(key, ip)
		return User{}, ErrInvalidCredentials
	}

	ok, needsRehash, err := s.Hasher.Verify(password, u.PasswordHash)
	if err != nil {
		return User{}, err
	}
	if !ok || u.Disabled {
		s.fail(key, ip)
		return User{}, ErrInvalidCredentials
	}
	s.succeed(key)

	if needsRehash {
		// Only now do we know the plaintext: upgrade cost or algorithm.
		if h, err := s.Hasher.Hash(password); err == nil {
			_ = s.Store.UpdatePasswordHash(ctx, u.ID, h) // best effort; retry next login
		}
	}
	return u, nil
}

func (s *Service) init() {
	if s.accounts == nil {
		s.accounts = map[string]*accountState{}
		s.ips = map[string]*ipState{}
	}
}

func (s *Service) throttled(key, ip string) time.Duration {
	s.mu.Lock()
	defer s.mu.Unlock()
	s.init()
	now := s.Clock.Now()
	if st, ok := s.ips[ip]; ok && now.Sub(st.windowStart) < s.Policy.PerIPWindow &&
		st.failures >= s.Policy.PerIPFailures {
		return st.windowStart.Add(s.Policy.PerIPWindow).Sub(now)
	}
	if st, ok := s.accounts[key]; ok {
		if st.failures >= s.Policy.HardLimit {
			return s.Policy.MaxDelay // password disabled: only a reset unlocks it
		}
		if now.Before(st.notBefore) {
			return st.notBefore.Sub(now)
		}
	}
	return 0
}

func (s *Service) fail(key, ip string) {
	s.mu.Lock()
	defer s.mu.Unlock()
	s.init()
	now := s.Clock.Now()

	st := s.accounts[key]
	if st == nil {
		st = &accountState{}
		s.accounts[key] = st
	}
	st.failures++
	if extra := st.failures - s.Policy.FreeFailures; extra > 0 {
		d := s.Policy.BaseDelay << min(extra-1, 30)
		if d > s.Policy.MaxDelay || d <= 0 {
			d = s.Policy.MaxDelay
		}
		st.notBefore = now.Add(d)
	}

	is := s.ips[ip]
	if is == nil || now.Sub(is.windowStart) >= s.Policy.PerIPWindow {
		is = &ipState{windowStart: now}
		s.ips[ip] = is
	}
	is.failures++
}

func (s *Service) succeed(key string) {
	s.mu.Lock()
	defer s.mu.Unlock()
	delete(s.accounts, key) // NIST: disregard earlier failures after a success
}

// ResetAccount clears the counters after a successful password reset.
func (s *Service) ResetAccount(email string) { s.succeed(Normalize(email)) }
go
package login

import (
	"context"
	"errors"
	"fmt"
	"testing"
	"time"

	"academy/authentication-passwords-mfa-sessions/clock"
)

type fakeHasher struct{ verifies int }

func (f *fakeHasher) Hash(pw string) (string, error) { return "new:" + pw, nil }
func (f *fakeHasher) Verify(pw, enc string) (bool, bool, error) {
	f.verifies++
	switch enc {
	case "old:" + pw:
		return true, true, nil
	case "new:" + pw:
		return true, false, nil
	}
	return false, false, nil
}

type memStore struct{ users map[string]User }

func (m *memStore) FindByEmail(_ context.Context, e string) (User, bool, error) {
	u, ok := m.users[e]
	return u, ok, nil
}
func (m *memStore) UpdatePasswordHash(_ context.Context, id int64, h string) error {
	for k, u := range m.users {
		if u.ID == id {
			u.PasswordHash = h
			m.users[k] = u
		}
	}
	return nil
}

func newService() (*Service, *fakeHasher, *memStore, *clock.Fake) {
	h := &fakeHasher{}
	st := &memStore{users: map[string]User{
		"ada@example.com": {ID: 1, Email: "ada@example.com", PasswordHash: "old:right-password"},
	}}
	clk := clock.NewFake(time.Date(2026, 11, 26, 9, 0, 0, 0, time.UTC))
	return &Service{Store: st, Hasher: h, Clock: clk, Policy: DefaultPolicy("dummy")}, h, st, clk
}

func TestUnknownAndWrongPasswordLookTheSame(t *testing.T) {
	s, h, _, _ := newService()
	_, errUnknown := s.Login(context.Background(), "nobody@example.com", "x", "192.0.2.1")
	_, errWrong := s.Login(context.Background(), "ada@example.com", "x", "192.0.2.1")
	if errUnknown != ErrInvalidCredentials || errWrong != ErrInvalidCredentials {
		t.Fatalf("errors differ: %v / %v", errUnknown, errWrong)
	}
	if h.verifies != 2 {
		t.Fatalf("unknown user must still run one hash verification, got %d calls", h.verifies)
	}
}

func TestRehashOnLogin(t *testing.T) {
	s, _, st, _ := newService()
	if _, err := s.Login(context.Background(), " ADA@example.com ", "right-password", "192.0.2.1"); err != nil {
		t.Fatal(err)
	}
	if got := st.users["ada@example.com"].PasswordHash; got != "new:right-password" {
		t.Fatalf("hash not upgraded: %q", got)
	}
}

func TestProgressiveDelayPerAccount(t *testing.T) {
	s, h, _, clk := newService()
	ctx := context.Background()
	for i := 0; i < 5; i++ { // free failures, from different IPs (a botnet)
		_, _ = s.Login(ctx, "ada@example.com", "guess", fmt.Sprintf("198.51.100.%d", i))
	}
	_, _ = s.Login(ctx, "ada@example.com", "guess", "198.51.100.99") // 6th: sets 1 s delay
	before := h.verifies
	_, err := s.Login(ctx, "ada@example.com", "right-password", "203.0.113.7")
	var te *ThrottledError
	if !errors.As(err, &te) || te.RetryAfter != time.Second {
		t.Fatalf("want 1s throttle, got %v", err)
	}
	if h.verifies != before {
		t.Fatal("a throttled attempt must not reach the hasher")
	}
	clk.Advance(time.Second)
	if _, err := s.Login(ctx, "ada@example.com", "right-password", "203.0.113.7"); err != nil {
		t.Fatalf("after the delay the real user gets in: %v", err)
	}
}

func TestDelayDoublesAndCaps(t *testing.T) {
	s, _, _, clk := newService()
	ctx := context.Background()
	var last time.Duration
	for i := 1; i <= 20; i++ {
		_, _ = s.Login(ctx, "ada@example.com", "guess", fmt.Sprintf("198.51.100.%d", i))
		_, err := s.Login(ctx, "ada@example.com", "guess", "198.51.100.250")
		var te *ThrottledError
		if errors.As(err, &te) {
			last = te.RetryAfter
			clk.Advance(te.RetryAfter)
		}
	}
	if last != 15*time.Minute {
		t.Fatalf("delay should cap at 15m, got %s", last)
	}
}

func TestPerIPLimitStopsSpraying(t *testing.T) {
	s, _, _, clk := newService()
	ctx := context.Background()
	for i := 0; i < 50; i++ { // one IP, one common password, many accounts
		_, _ = s.Login(ctx, fmt.Sprintf("user%d@example.com", i), "Winter2026!", "192.0.2.66")
	}
	_, err := s.Login(ctx, "user51@example.com", "Winter2026!", "192.0.2.66")
	var te *ThrottledError
	if !errors.As(err, &te) {
		t.Fatalf("51st attempt from one IP should be throttled, got %v", err)
	}
	clk.Advance(10 * time.Minute)
	if _, err := s.Login(ctx, "user52@example.com", "Winter2026!", "192.0.2.66"); err != ErrInvalidCredentials {
		t.Fatalf("new window should allow the attempt, got %v", err)
	}
}

TOTP و HOTP فقط با کتابخانهٔ استاندارد، با همهٔ بردارهای آزمون RFC 4226 و RFC 6238، تست انحراف و replay، و مقایسه با pquerna/otp:

go
// Package totp implements HOTP (RFC 4226) and TOTP (RFC 6238) with a drift
// window and replay protection, using only the standard library.
package totp

import (
	"crypto/hmac"
	"crypto/rand"
	"crypto/sha1"
	"crypto/sha256"
	"crypto/sha512"
	"crypto/subtle"
	"encoding/base32"
	"encoding/binary"
	"fmt"
	"hash"
	"net/url"
	"time"

	"academy/authentication-passwords-mfa-sessions/clock"
)

// Algorithm selects the HMAC hash. Authenticator apps almost all use SHA1.
type Algorithm string

const (
	SHA1   Algorithm = "SHA1"
	SHA256 Algorithm = "SHA256"
	SHA512 Algorithm = "SHA512"
)

func (a Algorithm) newHash() func() hash.Hash {
	switch a {
	case SHA256:
		return sha256.New
	case SHA512:
		return sha512.New
	default:
		return sha1.New
	}
}

// HOTP is RFC 4226 section 5.3: HMAC, dynamic truncation, modulo 10^digits.
func HOTP(key []byte, counter uint64, digits int, alg Algorithm) string {
	var msg [8]byte
	binary.BigEndian.PutUint64(msg[:], counter)
	m := hmac.New(alg.newHash(), key)
	m.Write(msg[:])
	sum := m.Sum(nil)
	off := sum[len(sum)-1] & 0x0f
	bin := (uint32(sum[off])&0x7f)<<24 | uint32(sum[off+1])<<16 | uint32(sum[off+2])<<8 | uint32(sum[off+3])
	mod := uint32(1)
	for i := 0; i < digits; i++ {
		mod *= 10
	}
	return fmt.Sprintf("%0*d", digits, bin%mod)
}

// Verifier checks TOTP codes. The zero value is not usable; use New.
type Verifier struct {
	Step   time.Duration // RFC 6238 recommends 30 s
	Digits int
	Skew   int // time steps accepted on each side; RFC 6238 allows one step of delay
	Alg    Algorithm
	Clock  clock.Clock
}

// New returns the Google Authenticator compatible defaults: 30 s, 6 digits, SHA1, skew 1.
func New(c clock.Clock) Verifier {
	return Verifier{Step: 30 * time.Second, Digits: 6, Skew: 1, Alg: SHA1, Clock: c}
}

// StepAt is the RFC 6238 counter T = floor((t - T0) / X) with T0 = 0.
func (v Verifier) StepAt(t time.Time) int64 { return t.Unix() / int64(v.Step/time.Second) }

// Code returns the code for time t.
func (v Verifier) Code(key []byte, t time.Time) string {
	return HOTP(key, uint64(v.StepAt(t)), v.Digits, v.Alg)
}

// Verify accepts code if it matches a step within the skew window that is
// strictly newer than lastStep (the step of the last accepted code for this
// user, 0 if none). It returns the matched step, which the caller must store
// atomically with the login: that is the replay protection RFC 6238 section 5.2 and
// NIST SP 800-63B-4 require ("accept a given OTP only once").
func (v Verifier) Verify(key []byte, code string, lastStep int64) (int64, bool) {
	if len(code) != v.Digits {
		return 0, false
	}
	now := v.StepAt(v.Clock.Now())
	matched, found := int64(0), 0
	for i := -v.Skew; i <= v.Skew; i++ { // always loop the whole window: no early exit
		s := now + int64(i)
		want := HOTP(key, uint64(s), v.Digits, v.Alg)
		eq := subtle.ConstantTimeCompare([]byte(want), []byte(code))
		if eq == 1 && s > lastStep && found == 0 {
			matched, found = s, 1
		}
	}
	return matched, found == 1
}

// NewSecret returns 20 random bytes (160 bits, the RFC 4226 recommended length).
func NewSecret() ([]byte, error) {
	b := make([]byte, 20)
	_, err := rand.Read(b)
	return b, err
}

// ProvisioningURI builds the otpauth:// URI that the QR code encodes.
func (v Verifier) ProvisioningURI(issuer, account string, secret []byte) string {
	q := url.Values{}
	q.Set("secret", base32.StdEncoding.WithPadding(base32.NoPadding).EncodeToString(secret))
	q.Set("issuer", issuer)
	q.Set("algorithm", string(v.Alg))
	q.Set("digits", fmt.Sprint(v.Digits))
	q.Set("period", fmt.Sprint(int(v.Step/time.Second)))
	u := url.URL{Scheme: "otpauth", Host: "totp", Path: "/" + issuer + ":" + account, RawQuery: q.Encode()}
	return u.String()
}
go
package totp

import (
	"testing"
	"time"

	"github.com/pquerna/otp"
	pq "github.com/pquerna/otp/totp"

	"academy/authentication-passwords-mfa-sessions/clock"
)

var (
	seed20 = []byte("12345678901234567890")
	seed32 = []byte("12345678901234567890123456789012")
	seed64 = []byte("1234567890123456789012345678901234567890123456789012345678901234")
)

// RFC 4226 Appendix D: HOTP values for counters 0..9.
func TestRFC4226Vectors(t *testing.T) {
	want := []string{"755224", "287082", "359152", "969429", "338314",
		"254676", "287922", "162583", "399871", "520489"}
	for c, w := range want {
		if got := HOTP(seed20, uint64(c), 6, SHA1); got != w {
			t.Errorf("counter %d: got %s want %s", c, got, w)
		}
	}
}

// RFC 6238 Appendix B: 8-digit TOTP values, 30 s step.
func TestRFC6238Vectors(t *testing.T) {
	cases := []struct {
		unix int64
		alg  Algorithm
		key  []byte
		want string
	}{
		{59, SHA1, seed20, "94287082"}, {59, SHA256, seed32, "46119246"}, {59, SHA512, seed64, "90693936"},
		{1111111109, SHA1, seed20, "07081804"}, {1111111109, SHA256, seed32, "68084774"},
		{1111111109, SHA512, seed64, "25091201"}, {1234567890, SHA1, seed20, "89005924"},
		{1234567890, SHA256, seed32, "91819424"}, {1234567890, SHA512, seed64, "93441116"},
		{20000000000, SHA1, seed20, "65353130"}, {20000000000, SHA256, seed32, "77737706"},
		{20000000000, SHA512, seed64, "47863826"},
	}
	for _, c := range cases {
		v := Verifier{Step: 30 * time.Second, Digits: 8, Alg: c.alg}
		if got := v.Code(c.key, time.Unix(c.unix, 0)); got != c.want {
			t.Errorf("%d %s: got %s want %s", c.unix, c.alg, got, c.want)
		}
	}
}

func TestDriftWindowAndReplay(t *testing.T) {
	clk := clock.NewFake(time.Unix(1_800_000_000, 0))
	v := New(clk)
	code := v.Code(seed20, clk.Now())

	step, ok := v.Verify(seed20, code, 0)
	if !ok {
		t.Fatal("current code rejected")
	}
	if _, ok := v.Verify(seed20, code, step); ok {
		t.Fatal("replay of the same code must be rejected")
	}

	prev := v.Code(seed20, clk.Now().Add(-30*time.Second)) // phone 30 s slow
	if _, ok := v.Verify(seed20, prev, 0); !ok {
		t.Fatal("one step of drift should be accepted")
	}
	old := v.Code(seed20, clk.Now().Add(-61*time.Second)) // two steps back
	if _, ok := v.Verify(seed20, old, 0); ok {
		t.Fatal("two steps of drift must be rejected with Skew=1")
	}
	if _, ok := v.Verify(seed20, "12345", 0); ok {
		t.Fatal("wrong length accepted")
	}
}

// Cross-check against github.com/pquerna/otp, the library most Go services use.
func TestMatchesPquernaOTP(t *testing.T) {
	clk := clock.NewFake(time.Unix(1_800_000_123, 0))
	v := New(clk)
	secret, err := NewSecret()
	if err != nil {
		t.Fatal(err)
	}
	uri := v.ProvisioningURI("Example", "ada@example.com", secret)
	key, err := otp.NewKeyFromURL(uri)
	if err != nil {
		t.Fatal(err)
	}
	if key.Issuer() != "Example" || key.AccountName() != "ada@example.com" || key.Period() != 30 {
		t.Fatalf("URI parsed wrong: %s", uri)
	}
	theirs, err := pq.GenerateCodeCustom(key.Secret(), clk.Now(), pq.ValidateOpts{
		Period: 30, Digits: otp.DigitsSix, Algorithm: otp.AlgorithmSHA1})
	if err != nil {
		t.Fatal(err)
	}
	if ours := v.Code(secret, clk.Now()); ours != theirs {
		t.Fatalf("ours %s, pquerna %s", ours, theirs)
	}
}

Passkey با go-webauthn: تنظیم relying party، handlerهای ثبت و ورود discoverable، ceremonyهای یک‌بارمصرف، clone warning. تست، گزینه‌های ساخت credential را بررسی می‌کند؛ ceremony کامل به authenticator واقعی یا مجازی نیاز دارد، پس handlerهای finish فقط کامپایل بررسی شده‌اند:

go
// Package passkey wires github.com/go-webauthn/webauthn into net/http for the
// two WebAuthn ceremonies: registration (create a passkey) and authentication
// (sign in with a discoverable credential, no username typed).
package passkey

import (
	"context"
	"crypto/rand"
	"encoding/base64"
	"encoding/json"
	"errors"
	"net/http"
	"sync"
	"time"

	"github.com/go-webauthn/webauthn/protocol"
	"github.com/go-webauthn/webauthn/webauthn"
)

// User adapts an account to webauthn.User. ID is a random 64-byte user
// handle, never the email: it is stored on the authenticator.
type User struct {
	ID          []byte
	Name        string
	DisplayName string
	Credentials []webauthn.Credential
}

func (u *User) WebAuthnID() []byte                         { return u.ID }
func (u *User) WebAuthnName() string                       { return u.Name }
func (u *User) WebAuthnDisplayName() string                { return u.DisplayName }
func (u *User) WebAuthnCredentials() []webauthn.Credential { return u.Credentials }

// Users is the account store.
type Users interface {
	ByHandle(ctx context.Context, handle []byte) (*User, error)
	SaveCredential(ctx context.Context, handle []byte, c webauthn.Credential) error
}

// Ceremonies stores the challenge between begin and finish. Take deletes, so
// every challenge is single-use. In production: the server-side session or Redis with a TTL.
type Ceremonies struct {
	mu sync.Mutex
	m  map[string]webauthn.SessionData
}

func (c *Ceremonies) put(s webauthn.SessionData) (string, error) {
	b := make([]byte, 16)
	if _, err := rand.Read(b); err != nil {
		return "", err
	}
	id := base64.RawURLEncoding.EncodeToString(b)
	c.mu.Lock()
	defer c.mu.Unlock()
	if c.m == nil {
		c.m = map[string]webauthn.SessionData{}
	}
	c.m[id] = s
	return id, nil
}

func (c *Ceremonies) take(id string) (webauthn.SessionData, bool) {
	c.mu.Lock()
	defer c.mu.Unlock()
	s, ok := c.m[id]
	delete(c.m, id)
	return s, ok
}

// NewRelyingParty configures the RP: the RP ID is the registrable domain the
// passkey is scoped to; origins must match exactly what the browser reports.
func NewRelyingParty(rpID, displayName string, origins []string) (*webauthn.WebAuthn, error) {
	return webauthn.New(&webauthn.Config{
		RPID:          rpID,
		RPDisplayName: displayName,
		RPOrigins:     origins,
		// "none": we do not need to know the authenticator model (no enterprise policy).
		AttestationPreference: protocol.PreferNoAttestation,
		AuthenticatorSelection: protocol.AuthenticatorSelection{
			ResidentKey:      protocol.ResidentKeyRequirementRequired, // discoverable = passkey
			UserVerification: protocol.VerificationRequired,           // PIN/biometric: two factors in one
		},
		Timeouts: webauthn.TimeoutsConfig{
			Login:        webauthn.TimeoutConfig{Enforce: true, Timeout: 2 * time.Minute},
			Registration: webauthn.TimeoutConfig{Enforce: true, Timeout: 5 * time.Minute},
		},
	})
}

// Server holds the handlers.
type Server struct {
	RP         *webauthn.WebAuthn
	Users      Users
	Ceremonies *Ceremonies
	// Current returns the signed-in user; registration needs an existing session
	// (ideally a recent step-up), never an anonymous request.
	Current func(*http.Request) (*User, bool)
	// SignIn creates the application session after a successful assertion.
	SignIn func(w http.ResponseWriter, r *http.Request, u *User, c *webauthn.Credential)
}

const cookieName = "__Host-webauthn"

func (s *Server) remember(w http.ResponseWriter, sd *webauthn.SessionData) error {
	id, err := s.Ceremonies.put(*sd)
	if err != nil {
		return err
	}
	http.SetCookie(w, &http.Cookie{Name: cookieName, Value: id, Path: "/", MaxAge: 300,
		Secure: true, HttpOnly: true, SameSite: http.SameSiteStrictMode})
	return nil
}

func (s *Server) recall(r *http.Request) (webauthn.SessionData, error) {
	c, err := r.Cookie(cookieName)
	if err != nil {
		return webauthn.SessionData{}, errors.New("no ceremony in progress")
	}
	sd, ok := s.Ceremonies.take(c.Value)
	if !ok {
		return webauthn.SessionData{}, errors.New("ceremony expired or already used")
	}
	return sd, nil
}

// BeginRegistration returns PublicKeyCredentialCreationOptions for navigator.credentials.create().
func (s *Server) BeginRegistration(w http.ResponseWriter, r *http.Request) {
	u, ok := s.Current(r)
	if !ok {
		http.Error(w, "sign in first", http.StatusUnauthorized)
		return
	}
	exclude := make([]protocol.CredentialDescriptor, 0, len(u.Credentials))
	for _, c := range u.Credentials {
		exclude = append(exclude, c.Descriptor()) // do not register the same authenticator twice
	}
	opts, sd, err := s.RP.BeginRegistration(u, webauthn.WithExclusions(exclude))
	if err != nil || s.remember(w, sd) != nil {
		http.Error(w, "cannot start registration", http.StatusInternalServerError)
		return
	}
	writeJSON(w, opts)
}

// FinishRegistration verifies the attestation response and stores the credential.
func (s *Server) FinishRegistration(w http.ResponseWriter, r *http.Request) {
	u, ok := s.Current(r)
	if !ok {
		http.Error(w, "sign in first", http.StatusUnauthorized)
		return
	}
	sd, err := s.recall(r)
	if err != nil {
		http.Error(w, err.Error(), http.StatusBadRequest)
		return
	}
	cred, err := s.RP.FinishRegistration(u, sd, r) // checks challenge, origin, RP ID hash, flags
	if err != nil {
		http.Error(w, "registration failed", http.StatusBadRequest)
		return
	}
	if err := s.Users.SaveCredential(r.Context(), u.ID, *cred); err != nil {
		http.Error(w, "cannot save credential", http.StatusInternalServerError)
		return
	}
	w.WriteHeader(http.StatusCreated)
}

// BeginLogin starts a discoverable (username-less) authentication ceremony.
func (s *Server) BeginLogin(w http.ResponseWriter, r *http.Request) {
	opts, sd, err := s.RP.BeginDiscoverableLogin(webauthn.WithUserVerification(protocol.VerificationRequired))
	if err != nil || s.remember(w, sd) != nil {
		http.Error(w, "cannot start login", http.StatusInternalServerError)
		return
	}
	writeJSON(w, opts)
}

// FinishLogin verifies the assertion signature with the stored public key.
func (s *Server) FinishLogin(w http.ResponseWriter, r *http.Request) {
	sd, err := s.recall(r)
	if err != nil {
		http.Error(w, err.Error(), http.StatusBadRequest)
		return
	}
	lookup := func(rawID, userHandle []byte) (webauthn.User, error) {
		return s.Users.ByHandle(r.Context(), userHandle)
	}
	wu, cred, err := s.RP.FinishPasskeyLogin(lookup, sd, r)
	if err != nil {
		http.Error(w, "authentication failed", http.StatusUnauthorized)
		return
	}
	u := wu.(*User)
	if cred.Authenticator.CloneWarning {
		// Signature counter went backwards: a signal, not proof. Synced passkeys
		// usually report 0, so this only fires for counters that are in use.
		http.Error(w, "authenticator needs review", http.StatusUnauthorized)
		return
	}
	// Persist the new sign count and backup state (BS can change over time).
	if err := s.Users.SaveCredential(r.Context(), u.ID, *cred); err != nil {
		http.Error(w, "cannot update credential", http.StatusInternalServerError)
		return
	}
	s.SignIn(w, r, u, cred)
}

func writeJSON(w http.ResponseWriter, v any) {
	w.Header().Set("Content-Type", "application/json")
	_ = json.NewEncoder(w).Encode(v)
}
go
package passkey

import (
	"bytes"
	"encoding/json"
	"net/http"
	"net/http/httptest"
	"testing"

	"github.com/go-webauthn/webauthn/protocol"
)

func TestBeginRegistrationOptions(t *testing.T) {
	rp, err := NewRelyingParty("example.com", "Example", []string{"https://example.com"})
	if err != nil {
		t.Fatal(err)
	}
	u := &User{ID: bytes.Repeat([]byte{7}, 64), Name: "ada@example.com", DisplayName: "Ada"}
	s := &Server{RP: rp, Ceremonies: &Ceremonies{},
		Current: func(*http.Request) (*User, bool) { return u, true }}

	rec := httptest.NewRecorder()
	s.BeginRegistration(rec, httptest.NewRequest("POST", "/passkeys/register/options", nil))
	if rec.Code != 200 {
		t.Fatalf("status %d: %s", rec.Code, rec.Body)
	}
	var got protocol.CredentialCreation
	if err := json.Unmarshal(rec.Body.Bytes(), &got); err != nil {
		t.Fatal(err)
	}
	o := got.Response
	if o.RelyingParty.ID != "example.com" || len(o.Challenge) < 16 {
		t.Fatalf("rp=%q challenge=%d bytes", o.RelyingParty.ID, len(o.Challenge))
	}
	if o.AuthenticatorSelection.ResidentKey != protocol.ResidentKeyRequirementRequired ||
		o.Attestation != protocol.PreferNoAttestation {
		t.Fatalf("selection %+v attestation %q", o.AuthenticatorSelection, o.Attestation)
	}

	// The challenge is single-use: the cookie maps to one stored ceremony.
	cookie := rec.Result().Cookies()[0]
	req := httptest.NewRequest("POST", "/x", nil)
	req.AddCookie(cookie)
	if _, err := s.recall(req); err != nil {
		t.Fatal(err)
	}
	if _, err := s.recall(req); err == nil {
		t.Fatal("second use of the same challenge must fail")
	}
}

func TestRejectsBadConfig(t *testing.T) {
	if _, err := NewRelyingParty("", "Example", nil); err == nil {
		t.Fatal("empty RP ID and origins should be rejected by webauthn.New")
	}
}

Refresh token با چرخش، family، عمر idle و مطلق، و تشخیص استفادهٔ مجدد:

go
// Package refresh issues opaque refresh tokens with rotation and reuse
// detection (RFC 9700 section 4.14.2): every refresh returns a new token, the old one
// is marked used, and presenting a used token revokes the whole family.
package refresh

import (
	"crypto/rand"
	"crypto/sha256"
	"crypto/subtle"
	"encoding/base64"
	"errors"
	"strings"
	"sync"
	"time"

	"academy/authentication-passwords-mfa-sessions/clock"
)

var (
	ErrInvalid  = errors.New("invalid_grant") // unknown, tampered or revoked
	ErrExpired  = errors.New("invalid_grant: expired")
	ErrReused   = errors.New("invalid_grant: reuse detected, family revoked")
	b64         = base64.RawURLEncoding
	errNotFound = errors.New("not found")
)

type record struct {
	ID        string
	FamilyID  string
	UserID    int64
	Hash      [32]byte // SHA-256 of the secret part; the plaintext is never stored
	ExpiresAt time.Time
	UsedAt    time.Time // zero until rotated
}

type family struct {
	UserID    int64
	ExpiresAt time.Time // absolute lifetime: rotation never extends it
	RevokedAt time.Time
}

// Service keeps state in memory; the SQL version is the refresh_tokens table
// with SELECT ... FOR UPDATE around Rotate.
type Service struct {
	Clock       clock.Clock
	IdleTTL     time.Duration // a token unused this long expires
	AbsoluteTTL time.Duration // the family (the login) ends after this, whatever happens

	mu       sync.Mutex
	tokens   map[string]*record
	families map[string]*family
}

func randomID(n int) (string, error) {
	b := make([]byte, n)
	if _, err := rand.Read(b); err != nil {
		return "", err
	}
	return b64.EncodeToString(b), nil
}

// Issue starts a new family after a full login. The token is "<id>.<secret>".
func (s *Service) Issue(userID int64) (string, error) {
	s.mu.Lock()
	defer s.mu.Unlock()
	s.init()
	fid, err := randomID(16)
	if err != nil {
		return "", err
	}
	s.families[fid] = &family{UserID: userID, ExpiresAt: s.Clock.Now().Add(s.AbsoluteTTL)}
	return s.mint(fid, userID)
}

func (s *Service) mint(fid string, userID int64) (string, error) {
	id, err := randomID(16)
	if err != nil {
		return "", err
	}
	secret, err := randomID(32)
	if err != nil {
		return "", err
	}
	exp := s.Clock.Now().Add(s.IdleTTL)
	if f := s.families[fid]; exp.After(f.ExpiresAt) {
		exp = f.ExpiresAt
	}
	s.tokens[id] = &record{ID: id, FamilyID: fid, UserID: userID,
		Hash: sha256.Sum256([]byte(secret)), ExpiresAt: exp}
	return id + "." + secret, nil
}

func (s *Service) lookup(token string) (*record, error) {
	id, secret, ok := strings.Cut(token, ".")
	if !ok {
		return nil, errNotFound
	}
	r := s.tokens[id]
	if r == nil {
		return nil, errNotFound
	}
	h := sha256.Sum256([]byte(secret))
	if subtle.ConstantTimeCompare(h[:], r.Hash[:]) != 1 {
		return nil, errNotFound
	}
	return r, nil
}

// Rotate exchanges a refresh token for a new one (and, in a real server, a new
// short-lived access token). It returns the user id for the access token.
func (s *Service) Rotate(token string) (string, int64, error) {
	s.mu.Lock()
	defer s.mu.Unlock()
	s.init()
	r, err := s.lookup(token)
	if err != nil {
		return "", 0, ErrInvalid
	}
	f := s.families[r.FamilyID]
	now := s.Clock.Now()
	switch {
	case !f.RevokedAt.IsZero():
		return "", 0, ErrInvalid
	case !r.UsedAt.IsZero():
		// Two parties hold this token: the client and a thief. We cannot tell
		// which one is calling, so we end the whole login for both.
		f.RevokedAt = now
		return "", 0, ErrReused
	case !now.Before(r.ExpiresAt):
		return "", 0, ErrExpired
	}
	r.UsedAt = now
	next, err := s.mint(r.FamilyID, r.UserID)
	return next, r.UserID, err
}

// RevokeUser ends every family of a user: "log out everywhere", password
// reset, account recovery, or an admin action.
func (s *Service) RevokeUser(userID int64) int {
	s.mu.Lock()
	defer s.mu.Unlock()
	s.init()
	n := 0
	for _, f := range s.families {
		if f.UserID == userID && f.RevokedAt.IsZero() {
			f.RevokedAt = s.Clock.Now()
			n++
		}
	}
	return n
}

func (s *Service) init() {
	if s.tokens == nil {
		s.tokens = map[string]*record{}
		s.families = map[string]*family{}
	}
}
go
package refresh

import (
	"testing"
	"time"

	"academy/authentication-passwords-mfa-sessions/clock"
)

func newSvc() (*Service, *clock.Fake) {
	clk := clock.NewFake(time.Date(2026, 11, 26, 9, 0, 0, 0, time.UTC))
	return &Service{Clock: clk, IdleTTL: 14 * 24 * time.Hour, AbsoluteTTL: 30 * 24 * time.Hour}, clk
}

func TestRotationReturnsNewTokenAndBurnsOld(t *testing.T) {
	s, _ := newSvc()
	t1, _ := s.Issue(42)
	t2, uid, err := s.Rotate(t1)
	if err != nil || uid != 42 || t2 == t1 {
		t.Fatalf("rotate: %v uid=%d", err, uid)
	}
	t3, _, err := s.Rotate(t2)
	if err != nil || t3 == t2 {
		t.Fatalf("second rotate: %v", err)
	}
}

func TestReuseRevokesWholeFamily(t *testing.T) {
	s, _ := newSvc()
	t1, _ := s.Issue(42)
	t2, _, _ := s.Rotate(t1) // legitimate client now holds t2

	if _, _, err := s.Rotate(t1); err != ErrReused { // attacker replays stolen t1
		t.Fatalf("want ErrReused, got %v", err)
	}
	if _, _, err := s.Rotate(t2); err != ErrInvalid { // the client's t2 is dead too
		t.Fatalf("family must be revoked, got %v", err)
	}
}

func TestTamperedAndUnknownTokens(t *testing.T) {
	s, _ := newSvc()
	t1, _ := s.Issue(1)
	if _, _, err := s.Rotate(t1 + "x"); err != ErrInvalid {
		t.Fatalf("tampered secret: %v", err)
	}
	if _, _, err := s.Rotate("no-dot"); err != ErrInvalid {
		t.Fatalf("malformed: %v", err)
	}
}

func TestIdleAndAbsoluteExpiry(t *testing.T) {
	s, clk := newSvc()
	t1, _ := s.Issue(1)
	clk.Advance(15 * 24 * time.Hour) // idle longer than 14 days
	if _, _, err := s.Rotate(t1); err != ErrExpired {
		t.Fatalf("idle expiry: %v", err)
	}

	t2, _ := s.Issue(1)
	for i := 0; i < 3; i++ { // keep using it every 10 days
		clk.Advance(10 * 24 * time.Hour)
		next, _, err := s.Rotate(t2)
		if i < 2 && err != nil {
			t.Fatalf("rotation %d: %v", i, err)
		}
		if i == 2 && err != ErrExpired {
			t.Fatalf("day 30: absolute lifetime must end the family, got %v", err)
		}
		t2 = next
	}
}

func TestLogoutEverywhere(t *testing.T) {
	s, _ := newSvc()
	phone, _ := s.Issue(7)
	laptop, _ := s.Issue(7)
	other, _ := s.Issue(8)
	if n := s.RevokeUser(7); n != 2 {
		t.Fatalf("revoked %d families", n)
	}
	for _, tok := range []string{phone, laptop} {
		if _, _, err := s.Rotate(tok); err != ErrInvalid {
			t.Fatalf("revoked token still works: %v", err)
		}
	}
	if _, _, err := s.Rotate(other); err != nil {
		t.Fatalf("other user affected: %v", err)
	}
}

توکن‌های بازنشانی رمز: ۲۵۶ بیت، SHA-256 در ذخیره‌سازی، یک‌بارمصرف، فقط جدیدترین، یک پیام عمومی:

go
// Package reset implements password reset tokens: 256 random bits, stored as
// SHA-256, single-use, short-lived, one outstanding token per user, and a
// response that is identical whether or not the email exists.
package reset

import (
	"context"
	"crypto/rand"
	"crypto/sha256"
	"encoding/base64"
	"errors"
	"sync"
	"time"

	"academy/authentication-passwords-mfa-sessions/clock"
)

// ErrInvalidToken covers unknown, used and expired tokens alike.
var ErrInvalidToken = errors.New("this reset link is invalid or has expired")

// PublicMessage is shown for every request, existing account or not.
const PublicMessage = "If an account exists for that address, we have sent a reset link."

// Users finds accounts; Mailer sends the link (asynchronously in production,
// so the response time does not depend on whether a mail was sent).
type Users interface {
	IDByEmail(ctx context.Context, email string) (int64, bool, error)
}
type Mailer interface {
	SendReset(ctx context.Context, userID int64, link string)
}

// AfterReset must change the hash, revoke sessions and refresh tokens, clear
// login throttles and notify the user.
type AfterReset func(ctx context.Context, userID int64, newPassword string) error

type entry struct {
	userID  int64
	expires time.Time
}

// Service holds hashed tokens. SQL: password_reset_tokens(token_hash PK, user_id, expires_at).
type Service struct {
	Clock   clock.Clock
	TTL     time.Duration // OWASP: "Single use and expire after an appropriate period"
	BaseURL string        // fixed, never built from the Host header
	Users   Users
	Mailer  Mailer
	After   AfterReset

	mu     sync.Mutex
	byHash map[[32]byte]entry
	byUser map[int64][32]byte
}

// Request always returns PublicMessage.
func (s *Service) Request(ctx context.Context, email string) (string, error) {
	id, ok, err := s.Users.IDByEmail(ctx, email)
	if err != nil || !ok {
		return PublicMessage, err
	}
	raw := make([]byte, 32)
	if _, err := rand.Read(raw); err != nil {
		return PublicMessage, err
	}
	token := base64.RawURLEncoding.EncodeToString(raw)
	h := sha256.Sum256([]byte(token))

	s.mu.Lock()
	s.init()
	if old, ok := s.byUser[id]; ok {
		delete(s.byHash, old) // a new request invalidates the previous link
	}
	s.byHash[h] = entry{userID: id, expires: s.Clock.Now().Add(s.TTL)}
	s.byUser[id] = h
	s.mu.Unlock()

	s.Mailer.SendReset(ctx, id, s.BaseURL+"/reset-password?token="+token)
	return PublicMessage, nil
}

// Consume validates and burns the token, then runs After.
func (s *Service) Consume(ctx context.Context, token, newPassword string) error {
	h := sha256.Sum256([]byte(token))
	s.mu.Lock()
	s.init()
	e, ok := s.byHash[h]
	if ok {
		delete(s.byHash, h) // single use, even if the rest fails
		delete(s.byUser, e.userID)
	}
	s.mu.Unlock()
	if !ok || !s.Clock.Now().Before(e.expires) {
		return ErrInvalidToken
	}
	return s.After(ctx, e.userID, newPassword)
}

func (s *Service) init() {
	if s.byHash == nil {
		s.byHash = map[[32]byte]entry{}
		s.byUser = map[int64][32]byte{}
	}
}
go
package reset

import (
	"context"
	"net/url"
	"strings"
	"testing"
	"time"

	"academy/authentication-passwords-mfa-sessions/clock"
)

type users map[string]int64

func (u users) IDByEmail(_ context.Context, e string) (int64, bool, error) {
	id, ok := u[e]
	return id, ok, nil
}

type mailer struct{ links []string }

func (m *mailer) SendReset(_ context.Context, _ int64, link string) { m.links = append(m.links, link) }

func setup() (*Service, *mailer, *clock.Fake, *[]int64) {
	clk := clock.NewFake(time.Date(2026, 11, 26, 9, 0, 0, 0, time.UTC))
	m := &mailer{}
	var resets []int64
	s := &Service{Clock: clk, TTL: 30 * time.Minute, BaseURL: "https://example.com",
		Users: users{"ada@example.com": 1}, Mailer: m,
		After: func(_ context.Context, id int64, _ string) error { resets = append(resets, id); return nil }}
	return s, m, clk, &resets
}

func token(t *testing.T, link string) string {
	u, err := url.Parse(link)
	if err != nil {
		t.Fatal(err)
	}
	return u.Query().Get("token")
}

func TestSameAnswerForUnknownEmail(t *testing.T) {
	s, m, _, _ := setup()
	a, _ := s.Request(context.Background(), "ada@example.com")
	b, _ := s.Request(context.Background(), "mallory@example.com")
	if a != b || a != PublicMessage {
		t.Fatalf("responses differ: %q vs %q", a, b)
	}
	if len(m.links) != 1 || !strings.HasPrefix(m.links[0], "https://example.com/reset-password?token=") {
		t.Fatalf("links: %v", m.links)
	}
}

func TestSingleUse(t *testing.T) {
	s, m, _, resets := setup()
	ctx := context.Background()
	_, _ = s.Request(ctx, "ada@example.com")
	tok := token(t, m.links[0])
	if err := s.Consume(ctx, tok, "new long passphrase"); err != nil {
		t.Fatal(err)
	}
	if err := s.Consume(ctx, tok, "again"); err != ErrInvalidToken {
		t.Fatalf("second use: %v", err)
	}
	if len(*resets) != 1 {
		t.Fatalf("AfterReset ran %d times", len(*resets))
	}
}

func TestExpiryAndNewerRequestInvalidatesOlder(t *testing.T) {
	s, m, clk, _ := setup()
	ctx := context.Background()
	_, _ = s.Request(ctx, "ada@example.com")
	_, _ = s.Request(ctx, "ada@example.com")
	first, second := token(t, m.links[0]), token(t, m.links[1])
	if err := s.Consume(ctx, first, "x"); err != ErrInvalidToken {
		t.Fatalf("older link must be dead: %v", err)
	}
	clk.Advance(31 * time.Minute)
	if err := s.Consume(ctx, second, "x"); err != ErrInvalidToken {
		t.Fatalf("expired link accepted: %v", err)
	}
}

Session سمت سرور: idle و absolute timeout، تعویض شناسه در step-up، بررسی تازگی، خروج از دستگاه‌های دیگر، cookie با __Host-:

go
// Package session is a server-side session store with idle and absolute
// timeouts, ID rotation, step-up checks and "log out everywhere".
package session

import (
	"crypto/rand"
	"encoding/base64"
	"errors"
	"net/http"
	"slices"
	"sync"
	"time"

	"academy/authentication-passwords-mfa-sessions/clock"
)

var ErrNoSession = errors.New("session missing or expired")

// Session is the server-side record; the cookie holds only ID.
type Session struct {
	ID       string
	UserID   int64
	Created  time.Time
	LastSeen time.Time
	AuthTime time.Time // last time the user proved who they are (login or step-up)
	AMR      []string  // authentication methods: "pwd", "otp", "hwk", ... (RFC 8176)
}

// Store keeps sessions in memory; production uses Redis or a sessions table.
type Store struct {
	Clock    clock.Clock
	Idle     time.Duration // NIST SP 800-63B-4 AAL2: inactivity SHOULD be <= 1 hour
	Absolute time.Duration // AAL2: overall SHOULD be <= 24 hours

	mu sync.Mutex
	m  map[string]*Session
}

func newID() (string, error) {
	b := make([]byte, 32) // 256 bits; OWASP asks for at least 64 bits of entropy
	if _, err := rand.Read(b); err != nil {
		return "", err
	}
	return base64.RawURLEncoding.EncodeToString(b), nil
}

// Create starts a session after authentication. Never reuse a pre-login ID
// (session fixation): always call Create, not "attach user to existing".
func (s *Store) Create(userID int64, amr ...string) (*Session, error) {
	id, err := newID()
	if err != nil {
		return nil, err
	}
	now := s.Clock.Now()
	ss := &Session{ID: id, UserID: userID, Created: now, LastSeen: now, AuthTime: now, AMR: amr}
	s.mu.Lock()
	defer s.mu.Unlock()
	if s.m == nil {
		s.m = map[string]*Session{}
	}
	s.m[id] = ss
	c := *ss
	return &c, nil
}

// Get returns a live session and slides the idle timer.
func (s *Store) Get(id string) (*Session, error) {
	s.mu.Lock()
	defer s.mu.Unlock()
	ss, ok := s.m[id]
	now := s.Clock.Now()
	if !ok || now.Sub(ss.LastSeen) >= s.Idle || now.Sub(ss.Created) >= s.Absolute {
		delete(s.m, id)
		return nil, ErrNoSession
	}
	ss.LastSeen = now
	c := *ss
	return &c, nil
}

// StepUp records a fresh proof (password, TOTP, passkey) and rotates the ID,
// because the privilege level changed.
func (s *Store) StepUp(id string, method string) (*Session, error) {
	s.mu.Lock()
	defer s.mu.Unlock()
	ss, ok := s.m[id]
	if !ok {
		return nil, ErrNoSession
	}
	nid, err := newID()
	if err != nil {
		return nil, err
	}
	delete(s.m, id)
	ss.ID, ss.AuthTime = nid, s.Clock.Now()
	if !slices.Contains(ss.AMR, method) {
		ss.AMR = append(ss.AMR, method)
	}
	s.m[nid] = ss
	c := *ss
	return &c, nil
}

// Fresh reports whether the user authenticated within maxAge: the check for
// "change email", "add passkey", "show recovery codes", "pay".
func Fresh(ss *Session, now time.Time, maxAge time.Duration) bool {
	return now.Sub(ss.AuthTime) <= maxAge
}

// Destroy ends one session (logout).
func (s *Store) Destroy(id string) {
	s.mu.Lock()
	delete(s.m, id)
	s.mu.Unlock()
}

// DestroyUser ends every session of a user except keep ("log out other devices").
func (s *Store) DestroyUser(userID int64, keep string) int {
	s.mu.Lock()
	defer s.mu.Unlock()
	n := 0
	for id, ss := range s.m {
		if ss.UserID == userID && id != keep {
			delete(s.m, id)
			n++
		}
	}
	return n
}

// Cookie follows NIST SP 800-63B-4 section 5.1.1: __Host- prefix, Path=/, Secure,
// HttpOnly, SameSite=Lax, opaque value only.
func Cookie(id string) *http.Cookie {
	return &http.Cookie{Name: "__Host-session", Value: id, Path: "/",
		Secure: true, HttpOnly: true, SameSite: http.SameSiteLaxMode}
}
go
package session

import (
	"testing"
	"time"

	"academy/authentication-passwords-mfa-sessions/clock"
)

func store() (*Store, *clock.Fake) {
	clk := clock.NewFake(time.Date(2026, 11, 26, 9, 0, 0, 0, time.UTC))
	return &Store{Clock: clk, Idle: time.Hour, Absolute: 24 * time.Hour}, clk
}

func TestIdleTimeout(t *testing.T) {
	s, clk := store()
	ss, _ := s.Create(1, "pwd")
	clk.Advance(59 * time.Minute)
	if _, err := s.Get(ss.ID); err != nil {
		t.Fatal("active session expired early")
	}
	clk.Advance(61 * time.Minute)
	if _, err := s.Get(ss.ID); err != ErrNoSession {
		t.Fatal("idle session should be gone")
	}
}

func TestAbsoluteTimeoutDespiteActivity(t *testing.T) {
	s, clk := store()
	ss, _ := s.Create(1, "pwd")
	for i := 0; i < 47; i++ { // a request every 30 minutes for 23.5 hours
		clk.Advance(30 * time.Minute)
		if _, err := s.Get(ss.ID); err != nil {
			t.Fatalf("expired at step %d", i)
		}
	}
	clk.Advance(30 * time.Minute)
	if _, err := s.Get(ss.ID); err != ErrNoSession {
		t.Fatal("24 h absolute limit ignored")
	}
}

func TestStepUpRotatesIDAndRefreshesAuthTime(t *testing.T) {
	s, clk := store()
	ss, _ := s.Create(1, "pwd")
	clk.Advance(20 * time.Minute)
	if Fresh(ss, clk.Now(), 10*time.Minute) {
		t.Fatal("20-minute-old login is not fresh for a 10-minute step-up")
	}
	up, err := s.StepUp(ss.ID, "otp")
	if err != nil || up.ID == ss.ID || !Fresh(up, clk.Now(), 10*time.Minute) {
		t.Fatalf("step-up: %v", err)
	}
	if _, err := s.Get(ss.ID); err != ErrNoSession {
		t.Fatal("old session ID must stop working after rotation")
	}
	if len(up.AMR) != 2 {
		t.Fatalf("amr = %v", up.AMR)
	}
}

func TestLogoutOtherDevices(t *testing.T) {
	s, _ := store()
	cur, _ := s.Create(1, "pwd")
	_, _ = s.Create(1, "pwd")
	_, _ = s.Create(1, "hwk")
	other, _ := s.Create(2, "pwd")
	if n := s.DestroyUser(1, cur.ID); n != 2 {
		t.Fatalf("destroyed %d", n)
	}
	if _, err := s.Get(cur.ID); err != nil {
		t.Fatal("current device logged out")
	}
	if _, err := s.Get(other.ID); err != nil {
		t.Fatal("other user logged out")
	}
	c := Cookie(cur.ID)
	if !c.Secure || !c.HttpOnly || c.Path != "/" || c.Name != "__Host-session" {
		t.Fatalf("cookie flags: %+v", c)
	}
}

The Go angle ​

قابلیت Goکاربرد در احراز هویتنکته
golang.org/x/crypto/argon2IDKey(pw, salt, t, m, p, keyLen)بایت خام برمی‌گرداند؛ encode و parse رشتهٔ PHC را خودتان می‌نویسید
golang.org/x/crypto/bcryptGenerateFromPassword، CompareHashAndPassword، Costبیش از ۷۲ بایت را با ErrPasswordTooLong رد می‌کند
golang.org/x/crypto/scrypt، pbkdf2scrypt.Key، pbkdf2.Key (Go 1.24 بستهٔ crypto/pbkdf2 را هم دارد)PBKDF2 برای buildهای FIPS (GOFIPS140)
crypto/subtle.ConstantTimeCompareهر مقایسهٔ secretورودی هم‌طول؛ hash را مقایسه کنید، نه رشتهٔ خام با طول متفاوت
crypto/randsalt، شناسهٔ session، توکن، secret مربوط به TOTPاز Go 1.24 روی پلتفرم‌های پشتیبانی‌شده rand.Read خطا نمی‌دهد؛ باز هم خطا را بررسی کنید
crypto/hmac، crypto/sha256pepper، HOTP، hash توکنhmac.Equal برای MAC
golang.org/x/text/unicode/normNFC پیش از hashNIST SP 800-63B-4
github.com/pquerna/otpTOTP/HOTP، کلیدهای otpauth://، تصویر QR (Key.Image)انبار replay را خودتان اضافه کنید
github.com/go-webauthn/webauthnRP در WebAuthn: ceremonyها، قالب‌های attestation، MDSنسخه‌ای را pin کنید که با toolchain Go شما جور است
Cookie در net/httpSecure، HttpOnly، SameSite، __Host-http.SameSiteLaxMode
کتابخانه‌های sessionalexedwards/scs (انبار Redis و Postgres)، gorilla/sessionsیا یک انبار کوچک مثل بالا
بدون frameworkGo چیزی مثل Fortify ندارد: قطعه‌ها را خودتان کنار هم می‌گذاریدAuthentication in Go یک سرویس کامل می‌سازد

Laravel ​

Before ​

MD5، enumeration، نبود throttling، نبود regenerate برای session:

php
<?php

namespace App\Http\Controllers\Auth;

use App\Http\Controllers\Controller;
use App\Models\User;
use Illuminate\Http\Request;

// Works, and is wrong: every comment is a design flaw.
class LoginController extends Controller
{
    public function store(Request $request)
    {
        $user = User::where('email', $request->input('email'))->first();

        if (! $user) {
            // Enumeration: a different message and a faster answer for unknown emails.
            return back()->withErrors(['email' => 'We have no account with this email.']);
        }

        // Fast unsalted hash and a non-constant-time comparison.
        if (md5($request->input('password')) !== $user->password) {
            // No throttling: brute force, stuffing and spraying cost nothing.
            return back()->withErrors(['password' => 'Wrong password.']);
        }

        // No session ID regeneration (session fixation), no MFA, no event for the audit log.
        session(['user_id' => $user->id]);

        return redirect('/dashboard');
    }
}

After ​

تنظیم hash: Argon2id، محدودیت صریح bcrypt برای hashهای قدیمی، rehash هنگام ورود:

php
<?php

// config/hashing.php (published with: php artisan config:publish hashing)

return [

    // bcrypt is Laravel's default; argon2id is the OWASP first choice.
    'driver' => env('HASH_DRIVER', 'argon2id'),

    'bcrypt' => [
        'rounds' => env('BCRYPT_ROUNDS', 12),
        'verify' => env('HASH_VERIFY', true),
        // Refuse inputs bcrypt would silently truncate (72 bytes).
        'limit' => env('BCRYPT_LIMIT', 72),
    ],

    'argon' => [
        'memory' => env('ARGON_MEMORY', 65536), // KiB = 64 MiB
        'threads' => env('ARGON_THREADS', 1),
        'time' => env('ARGON_TIME', 4),
        'verify' => env('HASH_VERIFY', true),
    ],

    // Auth::attempt() and the starter kits rehash when the cost or driver changed.
    'rehash_on_login' => true,

];

پیش‌فرض‌های رمز و limiterهای نام‌دار (حساب+IP، حساب، IP؛ دومرحله‌ای؛ بازنشانی):

php
<?php

namespace App\Providers;

use Illuminate\Cache\RateLimiting\Limit;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\RateLimiter;
use Illuminate\Support\ServiceProvider;
use Illuminate\Support\Str;
use Illuminate\Validation\Rules\Password;

class AppServiceProvider extends ServiceProvider
{
    public function boot(): void
    {
        // NIST SP 800-63B-4: length and a breached-password check, no composition rules.
        Password::defaults(function () {
            return Password::min(15)->max(128)->uncompromised();
        });

        // Two keys per login: the account (stops a botnet on one victim) and the IP
        // (stops one host spraying many accounts).
        RateLimiter::for('login', function (Request $request) {
            $account = Str::transliterate(Str::lower((string) $request->input('email')));

            return [
                Limit::perMinute(5)->by('acct:'.$account.'|'.$request->ip()),
                Limit::perHour(100)->by('acct:'.$account),
                Limit::perMinute(50)->by('ip:'.$request->ip()),
            ];
        });

        RateLimiter::for('two-factor', function (Request $request) {
            return Limit::perMinute(5)->by('2fa:'.$request->session()->get('login.id'));
        });

        // Same response for known and unknown emails, so limit by IP and by address.
        RateLimiter::for('password-reset', function (Request $request) {
            return [
                Limit::perHour(5)->by('reset:'.Str::lower((string) $request->input('email'))),
                Limit::perHour(20)->by('reset-ip:'.$request->ip()),
            ];
        });
    }
}

controller ورود دستی: Auth::validate() داخل timebox دویست‌میلی‌ثانیه‌ای Laravel، یک پیام، rehash، تحویل به MFA، regenerate برای session، لاگ ممیزی:

php
<?php

namespace App\Http\Controllers\Auth;

use App\Http\Controllers\Controller;
use App\Models\User;
use Illuminate\Http\RedirectResponse;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\Hash;
use Illuminate\Support\Facades\Log;
use Illuminate\Validation\ValidationException;

class LoginController extends Controller
{
    // Route: Route::post('/login', ...)->middleware(['guest', 'throttle:login'])
    public function store(Request $request): RedirectResponse
    {
        $credentials = $request->validate([
            'email' => ['required', 'string', 'email', 'max:254'],
            'password' => ['required', 'string', 'max:1024'],
        ]);

        // Validate without logging in yet: MFA may still be required.
        // Auth::validate() runs inside a 200 ms Timebox in SessionGuard, so unknown
        // emails do not answer faster than wrong passwords (keep the hash under 200 ms).
        if (! Auth::validate($credentials)) {
            Log::channel('auth')->notice('login.failed', [
                'email_hash' => hash('sha256', strtolower($credentials['email'])),
                'ip' => $request->ip(),
            ]);

            throw ValidationException::withMessages([
                'email' => __('auth.failed'), // "These credentials do not match our records."
            ]);
        }

        /** @var User $user */
        $user = Auth::getLastAttempted();

        // Rehash on login (Auth::attempt does this itself; validate() does not).
        if (Hash::needsRehash($user->password)) {
            $user->forceFill(['password' => Hash::make($credentials['password'])])->save();
        }

        if ($user->two_factor_confirmed_at !== null) {
            // Remember who passed step one, but do not authenticate the session yet.
            $request->session()->put('login.id', $user->getKey());
            $request->session()->put('login.remember', $request->boolean('remember'));

            return redirect()->route('two-factor.challenge');
        }

        Auth::login($user, $request->boolean('remember'));
        $request->session()->regenerate(); // new session ID: no session fixation

        Log::channel('auth')->info('login.succeeded', ['user_id' => $user->getKey(), 'amr' => ['pwd']]);

        return redirect()->intended('/dashboard');
    }

    public function destroy(Request $request): RedirectResponse
    {
        Auth::guard('web')->logout();
        $request->session()->invalidate();
        $request->session()->regenerateToken();

        return redirect('/');
    }
}

چالش دومرحله‌ای با قفل ردیف، محافظ replay برای TOTP و کدهای بازیابی hash‌شده که می‌سوزند:

php
<?php

namespace App\Http\Controllers\Auth;

use App\Http\Controllers\Controller;
use App\Models\User;
use App\Support\Totp;
use Illuminate\Http\RedirectResponse;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Hash;
use Illuminate\Validation\ValidationException;

class TwoFactorChallengeController extends Controller
{
    // Route: Route::post('/two-factor-challenge', ...)->middleware(['guest', 'throttle:two-factor'])
    public function store(Request $request, Totp $totp): RedirectResponse
    {
        $userId = $request->session()->get('login.id');
        $user = $userId ? User::find($userId) : null;

        if (! $user) {
            return redirect()->route('login');
        }

        $ok = DB::transaction(function () use ($request, $user, $totp) {
            $locked = User::whereKey($user->getKey())->lockForUpdate()->first();

            if ($code = $request->input('code')) {
                $step = $totp->verify(decrypt($locked->two_factor_secret), $code, (int) $locked->two_factor_last_step);
                if ($step === null) {
                    return false;
                }
                // Replay protection: the step is stored in the same transaction.
                $locked->forceFill(['two_factor_last_step' => $step])->save();

                return true;
            }

            // Recovery codes are stored hashed and burned on use.
            $codes = collect(json_decode(decrypt($locked->two_factor_recovery_codes), true));
            $match = $codes->first(fn (string $hash) => Hash::check((string) $request->input('recovery_code'), $hash));
            if ($match === null) {
                return false;
            }
            $locked->forceFill([
                'two_factor_recovery_codes' => encrypt(json_encode($codes->reject(fn ($h) => $h === $match)->values())),
            ])->save();

            return true;
        });

        if (! $ok) {
            throw ValidationException::withMessages(['code' => __('The provided two factor authentication code was invalid.')]);
        }

        Auth::login($user, (bool) $request->session()->pull('login.remember', false));
        $request->session()->forget('login.id');
        $request->session()->regenerate();
        $request->session()->put('auth.amr', ['pwd', $request->filled('code') ? 'otp' : 'recovery']);
        $request->session()->put('auth.password_confirmed_at', time());

        return redirect()->intended('/dashboard');
    }
}

پیاده‌سازی خام RFC 6238 در PHP و اسکریپتی که آن را با بردارهای آزمون RFC بررسی می‌کند (اجرا کردیم: all TOTP/HOTP vectors pass):

php
<?php

namespace App\Support;

// RFC 4226 / RFC 6238 without a package. Pure PHP: no Laravel dependency, so
// tests/totp_vectors.php can run it with the php CLI.
final class Totp
{
    public function __construct(
        private int $step = 30,
        private int $digits = 6,
        private int $skew = 1,
        private string $algo = 'sha1',
    ) {}

    public function hotp(string $key, int $counter): string
    {
        $mac = hash_hmac($this->algo, pack('J', $counter), $key, true);
        $offset = ord($mac[strlen($mac) - 1]) & 0x0F;
        $bin = ((ord($mac[$offset]) & 0x7F) << 24)
            | (ord($mac[$offset + 1]) << 16)
            | (ord($mac[$offset + 2]) << 8)
            | ord($mac[$offset + 3]);

        return str_pad((string) ($bin % (10 ** $this->digits)), $this->digits, '0', STR_PAD_LEFT);
    }

    public function at(string $key, int $unixTime): string
    {
        return $this->hotp($key, intdiv($unixTime, $this->step));
    }

    // Returns the matched time step (store it as two_factor_last_step) or null.
    public function verify(string $key, string $code, int $lastStep, ?int $now = null): ?int
    {
        if (strlen($code) !== $this->digits || ! ctype_digit($code)) {
            return null;
        }
        $current = intdiv($now ?? time(), $this->step);
        $matched = null;
        for ($i = -$this->skew; $i <= $this->skew; $i++) {
            $step = $current + $i;
            if (hash_equals($this->hotp($key, $step), $code) && $step > $lastStep && $matched === null) {
                $matched = $step;
            }
        }

        return $matched;
    }

    public static function newSecret(): string
    {
        return random_bytes(20);
    }

    public static function base32(string $bytes): string
    {
        $alphabet = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ234567';
        $bits = '';
        foreach (str_split($bytes) as $c) {
            $bits .= str_pad(decbin(ord($c)), 8, '0', STR_PAD_LEFT);
        }
        $out = '';
        foreach (str_split($bits, 5) as $chunk) {
            $out .= $alphabet[bindec(str_pad($chunk, 5, '0'))];
        }

        return $out;
    }

    public function provisioningUri(string $issuer, string $account, string $secret): string
    {
        return 'otpauth://totp/'.rawurlencode($issuer).':'.rawurlencode($account).'?'.http_build_query([
            'secret' => self::base32($secret),
            'issuer' => $issuer,
            'algorithm' => strtoupper($this->algo),
            'digits' => $this->digits,
            'period' => $this->step,
        ]);
    }
}
php
<?php

// Run: php tests/totp_vectors.php  (checks RFC 4226 and RFC 6238 test vectors)

require __DIR__.'/../app/Support/Totp.php';

use App\Support\Totp;

$fail = 0;
$hotp = new Totp(digits: 6);
foreach (['755224', '287082', '359152', '969429', '338314', '254676', '287922', '162583', '399871', '520489'] as $c => $want) {
    $got = $hotp->hotp('12345678901234567890', $c);
    if ($got !== $want) {
        echo "HOTP counter $c: got $got want $want\n";
        $fail++;
    }
}

$keys = [
    'sha1' => '12345678901234567890',
    'sha256' => '12345678901234567890123456789012',
    'sha512' => '1234567890123456789012345678901234567890123456789012345678901234',
];
$vectors = [
    [59, 'sha1', '94287082'], [59, 'sha256', '46119246'], [59, 'sha512', '90693936'],
    [1111111109, 'sha1', '07081804'], [1234567890, 'sha256', '91819424'], [20000000000, 'sha512', '47863826'],
];
foreach ($vectors as [$t, $algo, $want]) {
    $got = (new Totp(digits: 8, algo: $algo))->at($keys[$algo], $t);
    if ($got !== $want) {
        echo "TOTP $t $algo: got $got want $want\n";
        $fail++;
    }
}

$totp = new Totp();
$now = 1_800_000_000;
$code = $totp->at($keys['sha1'], $now);
$step = $totp->verify($keys['sha1'], $code, 0, $now);
$replay = $totp->verify($keys['sha1'], $code, $step ?? 0, $now);
$drift = $totp->verify($keys['sha1'], $totp->at($keys['sha1'], $now - 30), 0, $now);
$tooOld = $totp->verify($keys['sha1'], $totp->at($keys['sha1'], $now - 61), 0, $now);
if ($step === null || $replay !== null || $drift === null || $tooOld !== null) {
    echo "window/replay checks failed\n";
    $fail++;
}

echo $fail === 0 ? "all TOTP/HOTP vectors pass\n" : "$fail failures\n";
exit($fail === 0 ? 0 : 1);

بازنشانی رمز با broker مربوط به Password، یک پیام عمومی و «خروج از همه‌جا» بعد از بازنشانی:

php
<?php

namespace App\Http\Controllers\Auth;

use App\Http\Controllers\Controller;
use App\Models\User;
use Illuminate\Auth\Events\PasswordReset;
use Illuminate\Http\RedirectResponse;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Hash;
use Illuminate\Support\Facades\Password;
use Illuminate\Support\Str;
use Illuminate\Validation\Rules\Password as PasswordRule;

class PasswordResetController extends Controller
{
    // Route: Route::post('/forgot-password', ...)->middleware(['guest', 'throttle:password-reset'])
    public function sendLink(Request $request): RedirectResponse
    {
        $request->validate(['email' => ['required', 'email', 'max:254']]);

        // The broker stores a bcrypt hash of the token (DatabaseTokenRepository) and
        // returns ResetLinkSent, InvalidUser or ResetThrottled. We show one message
        // for all three: anything else tells an attacker which emails exist.
        // For equal timing, dispatch this call to a queued job instead.
        Password::sendResetLink($request->only('email'));

        return back()->with('status', __('If an account exists for that address, we have sent a reset link.'));
    }

    // Route: Route::post('/reset-password', ...)->middleware('guest')->name('password.update')
    public function reset(Request $request): RedirectResponse
    {
        $request->validate([
            'token' => ['required', 'string'],
            'email' => ['required', 'email'],
            'password' => ['required', 'confirmed', PasswordRule::defaults()],
        ]);

        $status = Password::reset(
            $request->only('email', 'password', 'password_confirmation', 'token'),
            function (User $user, string $password) {
                $user->forceFill(['password' => Hash::make($password)])
                    ->setRememberToken(Str::random(60)); // kills every "remember me" cookie
                $user->save();

                // Log out everywhere: database sessions, API tokens, refresh token families.
                DB::table('sessions')->where('user_id', $user->getKey())->delete();
                $user->tokens()->delete(); // Sanctum personal access tokens
                DB::table('refresh_token_families')->where('user_id', $user->getKey())
                    ->whereNull('revoked_at')->update(['revoked_at' => now()]);

                event(new PasswordReset($user)); // listener mails "your password was changed"
            }
        );

        // The broker deletes the token on success: single use.
        return $status === Password::PasswordReset
            ? redirect()->route('login')->with('status', __($status))
            : back()->withErrors(['email' => __('This password reset link is invalid or has expired.')]);
    }
}

خروج از دستگاه‌های دیگر و step-up (Auth::logoutOtherDevices، auth.session، password.confirm):

php
<?php

namespace App\Http\Controllers\Settings;

use App\Http\Controllers\Controller;
use Illuminate\Http\RedirectResponse;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\DB;

class SecurityController extends Controller
{
    // Route: Route::post('/settings/logout-others', ...)->middleware(['auth', 'auth.session', 'throttle:6,1'])
    // AuthenticateSession (alias auth.session) compares a hash of the password
    // stored in each session; logoutOtherDevices() rehashes it, so every other
    // session fails that check on its next request.
    public function logoutOtherDevices(Request $request): RedirectResponse
    {
        $request->validate(['password' => ['required', 'current_password']]);

        Auth::logoutOtherDevices($request->input('password'));

        // With the database session driver, also delete the rows immediately.
        DB::table('sessions')
            ->where('user_id', $request->user()->getKey())
            ->where('id', '!=', $request->session()->getId())
            ->delete();

        // API tokens are separate credentials: revoke them too.
        $request->user()->tokens()->delete();

        return back()->with('status', 'Signed out of all other devices.');
    }

    // Route: Route::delete('/settings/two-factor', ...)->middleware(['auth', 'password.confirm'])
    // password.confirm is step-up: it asks again if the last confirmation is older
    // than auth.password_timeout (10800 s = 3 hours by default; we set 900).
    public function disableTwoFactor(Request $request): RedirectResponse
    {
        $request->user()->forceFill([
            'two_factor_secret' => null,
            'two_factor_recovery_codes' => null,
            'two_factor_confirmed_at' => null,
        ])->save();

        // Notify out of band: a disabled second factor is a takeover signal.
        $request->user()->notify(new \App\Notifications\SecurityChange('two_factor_disabled'));

        return back()->with('status', 'Two-factor authentication disabled.');
    }
}

personal access tokenهای Sanctum با ability و انقضا:

php
<?php

namespace App\Http\Controllers\Api;

use App\Http\Controllers\Controller;
use Illuminate\Http\JsonResponse;
use Illuminate\Http\Request;

// Sanctum personal access tokens: opaque, stored as SHA-256, revocable, scoped by abilities.
class TokenController extends Controller
{
    // Route: Route::post('/settings/tokens', ...)->middleware(['auth', 'password.confirm'])
    public function store(Request $request): JsonResponse
    {
        $data = $request->validate([
            'name' => ['required', 'string', 'max:100'],
            'abilities' => ['array'],
            'abilities.*' => ['in:orders:read,orders:write'],
        ]);

        $token = $request->user()->createToken(
            $data['name'],
            $data['abilities'] ?? ['orders:read'],
            now()->plus(days: 90), // Sanctum tokens never expire unless you say so
        );

        // Shown once; the database only has hash('sha256', ...).
        return response()->json(['token' => $token->plainTextToken], 201);
    }

    // Route: Route::get('/api/orders', ...)->middleware('auth:sanctum')
    public function orders(Request $request): JsonResponse
    {
        abort_unless($request->user()->tokenCan('orders:read'), 403);

        return response()->json($request->user()->orders()->latest()->limit(20)->get());
    }

    public function destroy(Request $request, int $id): JsonResponse
    {
        $request->user()->tokens()->whereKey($id)->delete();

        return response()->json(null, 204);
    }
}

چرخش refresh token با تشخیص استفادهٔ مجدد برای کلاینت موبایل یک API لاراولی:

php
<?php

namespace App\Services;

use Illuminate\Support\Facades\DB;
use RuntimeException;

// Opaque refresh tokens with rotation and reuse detection (RFC 9700 section 4.14.2),
// for a mobile app talking to a Laravel API. Tables: see the migration.
final class RefreshTokens
{
    public function __construct(
        private int $idleDays = 14,
        private int $absoluteDays = 30,
    ) {}

    public function issue(int $userId): string
    {
        return DB::transaction(function () use ($userId) {
            $familyId = DB::table('refresh_token_families')->insertGetId([
                'user_id' => $userId,
                'expires_at' => now()->plus(days: $this->absoluteDays),
                'created_at' => now(),
            ]);

            return $this->mint($familyId, $userId);
        });
    }

    /** @return array{0: string, 1: int} [new refresh token, user id] */
    public function rotate(string $presented): array
    {
        return DB::transaction(function () use ($presented) {
            $row = DB::table('refresh_tokens')
                ->where('token_hash', hash('sha256', $presented))
                ->lockForUpdate() // two parallel refreshes must not both succeed
                ->first();

            if (! $row) {
                throw new RuntimeException('invalid_grant');
            }

            $family = DB::table('refresh_token_families')->where('id', $row->family_id)->lockForUpdate()->first();

            if ($family->revoked_at !== null) {
                throw new RuntimeException('invalid_grant');
            }

            if ($row->used_at !== null) {
                // Reuse: a copy exists somewhere. End the whole login.
                DB::table('refresh_token_families')->where('id', $family->id)->update(['revoked_at' => now()]);
                DB::table('auth_events')->insert([
                    'user_id' => $row->user_id, 'type' => 'refresh_token.reuse_detected',
                    'meta' => json_encode(['family_id' => $family->id]), 'created_at' => now(),
                ]);

                throw new RuntimeException('invalid_grant');
            }

            if (now()->greaterThanOrEqualTo($row->expires_at)) {
                throw new RuntimeException('invalid_grant');
            }

            DB::table('refresh_tokens')->where('id', $row->id)->update(['used_at' => now()]);

            return [$this->mint($family->id, $row->user_id), (int) $row->user_id];
        });
    }

    private function mint(int $familyId, int $userId): string
    {
        $plain = rtrim(strtr(base64_encode(random_bytes(32)), '+/', '-_'), '=');
        $family = DB::table('refresh_token_families')->where('id', $familyId)->first();
        $expires = min(now()->plus(days: $this->idleDays)->getTimestamp(), strtotime($family->expires_at));

        DB::table('refresh_tokens')->insert([
            'family_id' => $familyId,
            'user_id' => $userId,
            'token_hash' => hash('sha256', $plain),
            'expires_at' => date('Y-m-d H:i:s', $expires),
            'created_at' => now(),
        ]);

        return $plain;
    }
}

Migration و routeها:

php
<?php

use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;

return new class extends Migration
{
    public function up(): void
    {
        Schema::table('users', function (Blueprint $table) {
            // Fortify adds two_factor_secret, two_factor_recovery_codes, two_factor_confirmed_at.
            $table->unsignedBigInteger('two_factor_last_step')->nullable(); // TOTP replay guard
            $table->timestamp('password_changed_at')->nullable();
        });

        Schema::create('refresh_token_families', function (Blueprint $table) {
            $table->id();
            $table->foreignId('user_id')->constrained()->cascadeOnDelete();
            $table->string('device_name')->nullable();
            $table->timestamp('expires_at');
            $table->timestamp('revoked_at')->nullable();
            $table->timestamp('created_at');
            $table->index(['user_id', 'revoked_at']);
        });

        Schema::create('refresh_tokens', function (Blueprint $table) {
            $table->id();
            $table->foreignId('family_id')->constrained('refresh_token_families')->cascadeOnDelete();
            $table->foreignId('user_id')->constrained()->cascadeOnDelete();
            $table->char('token_hash', 64)->unique(); // sha256 hex; plaintext never stored
            $table->timestamp('expires_at');
            $table->timestamp('used_at')->nullable();
            $table->timestamp('created_at');
        });

        Schema::create('auth_events', function (Blueprint $table) {
            $table->id();
            $table->foreignId('user_id')->nullable()->constrained()->nullOnDelete();
            $table->string('type', 64); // login.succeeded, login.failed, mfa.enabled, password.reset ...
            $table->string('ip', 45)->nullable();
            $table->string('user_agent', 512)->nullable();
            $table->json('meta')->nullable(); // never passwords, codes or tokens
            $table->timestamp('created_at')->index();
            $table->index(['user_id', 'created_at']);
        });
    }

    public function down(): void
    {
        Schema::dropIfExists('auth_events');
        Schema::dropIfExists('refresh_tokens');
        Schema::dropIfExists('refresh_token_families');
        Schema::table('users', function (Blueprint $table) {
            $table->dropColumn(['two_factor_last_step', 'password_changed_at']);
        });
    }
};
php
<?php

use App\Http\Controllers\Api\TokenController;
use App\Http\Controllers\Auth\LoginController;
use App\Http\Controllers\Auth\PasswordResetController;
use App\Http\Controllers\Auth\TwoFactorChallengeController;
use App\Http\Controllers\Settings\SecurityController;
use Illuminate\Support\Facades\Route;

Route::middleware('guest')->group(function () {
    Route::post('/login', [LoginController::class, 'store'])->middleware('throttle:login');
    Route::post('/two-factor-challenge', [TwoFactorChallengeController::class, 'store'])
        ->middleware('throttle:two-factor');
    Route::post('/forgot-password', [PasswordResetController::class, 'sendLink'])
        ->middleware('throttle:password-reset')->name('password.email');
    Route::post('/reset-password', [PasswordResetController::class, 'reset'])->name('password.update');
});

Route::middleware(['auth', 'auth.session'])->group(function () {
    Route::post('/logout', [LoginController::class, 'destroy']);
    Route::post('/settings/logout-others', [SecurityController::class, 'logoutOtherDevices'])
        ->middleware('throttle:6,1');
    Route::delete('/settings/two-factor', [SecurityController::class, 'disableTwoFactor'])
        ->middleware('password.confirm');
    Route::post('/settings/tokens', [TokenController::class, 'store'])->middleware('password.confirm');
    Route::delete('/settings/tokens/{id}', [TokenController::class, 'destroy']);
});

Route::get('/api/orders', [TokenController::class, 'orders'])->middleware('auth:sanctum');

همین سیاست با Fortify (backend بدون رابط برای هر frontend):

php
<?php

namespace App\Providers;

use App\Models\User;
use Illuminate\Cache\RateLimiting\Limit;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Hash;
use Illuminate\Support\Facades\RateLimiter;
use Illuminate\Support\ServiceProvider;
use Illuminate\Support\Str;
use Laravel\Fortify\Fortify;

// The same policy with Laravel Fortify (headless). config/fortify.php enables:
//   Features::resetPasswords(), Features::updatePasswords(),
//   Features::twoFactorAuthentication(['confirm' => true, 'confirmPassword' => true, 'window' => 1]),
//   Features::passkeys(['confirmPassword' => true]),
// and 'limiters' => ['login' => 'login', 'two-factor' => 'two-factor', 'passkeys' => 'passkeys'].
class FortifyServiceProvider extends ServiceProvider
{
    public function boot(): void
    {
        Fortify::loginView(fn () => view('auth.login'));
        Fortify::twoFactorChallengeView(fn () => view('auth.two-factor-challenge'));

        // Optional: custom lookup, e.g. refuse disabled accounts with the SAME error.
        Fortify::authenticateUsing(function (Request $request) {
            $user = User::where('email', Str::lower($request->input('email')))->first();

            $valid = $user
                ? Hash::check($request->input('password'), $user->password)
                : Hash::check($request->input('password'), config('auth.dummy_hash')); // equal work

            return $valid && $user->disabled_at === null ? $user : null;
        });

        RateLimiter::for('login', function (Request $request) {
            $key = Str::transliterate(Str::lower($request->input(Fortify::username())));

            return [
                Limit::perMinute(5)->by($key.'|'.$request->ip()), // Fortify's stub default
                Limit::perMinute(50)->by($request->ip()),           // add: spraying from one IP
            ];
        });

        RateLimiter::for('two-factor', function (Request $request) {
            return Limit::perMinute(5)->by($request->session()->get('login.id'));
        });

        RateLimiter::for('passkeys', function (Request $request) {
            return Limit::perMinute(10)->by(
                ($request->input('credential.id') ?: $request->session()->getId()).'|'.$request->ip()
            );
        });
    }
}

The Laravel angle ​

قابلیت Laravel 13چه کاری برای احراز هویت می‌کندمراقب باشید
Hash::make، Hash::check، Hash::needsRehashdriverهای bcrypt (پیش‌فرض)، argon، argon2idوقتی hash ذخیره‌شده الگوریتم دیگری دارد HASH_VERIFY استثنا پرتاب می‌کند؛ در مهاجرت خاموشش کنید
rehash_on_loginAuth::attempt() hashها را ارتقا می‌دهدAuth::validate() و بررسی‌های سفارشی این کار را نمی‌کنند: خودتان needsRehash را صدا بزنید
Auth::attempt، Auth::validate، Auth::loginورود با session؛ timebox دویست‌میلی‌ثانیه‌ای برای شکستبعد از ورود $request->session()->regenerate() را صدا بزنید
RateLimiter::for، Limit::perMinute()->by()، middleware throttle:limiterهای نام‌دار؛ آرایه‌ای از limitهاکلید را با ایمیل نرمال‌شده و IP بسازید
Password::defaults()، Password::min()->uncompromised()طول و بررسی k-anonymity در HIBPطبق NIST از mixedCase()/symbols() استفاده نکنید
broker مربوط به Passwordلینک بازنشانی، expire، throttle، driver از نوع database یا cacheبرای همهٔ statusها یک پیام نشان دهید
Auth::logoutOtherDevices() + auth.sessionsessionهای دیگر را با rehash باطل می‌کندsessionهای پایگاه داده و توکن‌های API را هم حذف کنید
middleware password.confirm و password_timeoutstep-up برای routeهای حساسپیش‌فرض ۳ ساعت طولانی است؛ ۱۰ تا ۱۵ دقیقه بگذارید
«Remember me» (Auth::attempt($creds, $remember)، remember_token)cookie بلندمدت برای ورود دوبارهدر بازنشانی remember_token را بچرخانید
Fortifyورود، ثبت‌نام، بازنشانی، تأیید ایمیل، 2FA با TOTP، کدهای بازیابی و passkey بدون رابطviewها را خودتان می‌سازید (یا starter kit)
starter kitها (React، Vue، Svelte، Livewire)صفحه‌های آمادهٔ مبتنی بر Fortifyپیش‌فرض kitها bcrypt است
Sanctumاحراز SPA با session + personal access token (SHA-256، ability، expiration)توکن‌ها تا تنظیم نکنید منقضی نمی‌شوند
Passportسرور کامل OAuth 2.0 (authorization code + PKCE، client credentials، refresh token)فقط وقتی شخص ثالث به OAuth نیاز دارد
Socialiteورود با Google، GitHub، Apple و دیگرانsession محلی را باز هم خودتان می‌سازید

حل مسئله‌های کلاسیک ​

رمزها با hash سریع ذخیره شده‌اند ​

راه‌حلچطورمزیتهزینه / محدودیت
همین حالا wrap کنیدargon2id(old_md5) برای همهٔ ردیف‌ها در یک migrationهمهٔ ردیف‌ها از امروز محافظت می‌شوندverify باید بداند wrap شده
rehash هنگام ورودطرح قدیمی را بررسی و Argon2id ذخیره کنیدبدون اثر روی کاربرکاربران غیرفعال ضعیف می‌مانند
بازنشانی اجباری برای بقیهبعد از N ماه hashهای تبدیل‌نشده را منقضی کنیددنبالهٔ بلند حذف می‌شودبار پشتیبانی

موج credential stuffing ​

راه‌حلچطورمزیتهزینه
بررسی رمز لورفته هنگام ورودAPI محدوده‌ای HIBP یا فهرست آفلاین؛ با تطابق بازنشانی اجباریورودی حمله را از بین می‌بردیک فراخوان HTTP (کش کنید یا فهرست را mirror کنید)
دفاع bot در لبهCloudflare Bot Management/Turnstile، AWS WAF ATPترافیک پیش از hasher متوقف می‌شودهزینهٔ فروشنده، مثبت کاذب
MFATOTP یا passkeyرمز به‌تنهایی بی‌فایده استپذیرش کاربران، پشتیبانی
هشدار سراسریهشدار برای افت نسبت ورود موفقموج‌های جدید را سریع تشخیص می‌دهدتنظیم

کاربرانی که مهاجم قفلشان کرده ​

راه‌حلچطورمزیتهزینه
تأخیر تدریجی1 s، 2 s، 4 s ... تا سقف ۱۵ دقیقهکاربر واقعی چند ثانیه صبر می‌کندحمله کند می‌شود، نه متوقف
CAPTCHA بعد از N شکستTurnstile/hCaptchabotها هزینه می‌دهند، انسان‌ها کلیکحل‌کننده‌ها وجود دارند
عبور برای دستگاه شناخته‌شدهcookie دستگاه از ورود MFA قبلی از تأخیر عبور می‌کندصاحب حساب بی‌اثر می‌مانددزدی cookie دستگاه
بازنشانی دوباره فعال می‌کندسقف سخت رمز را غیرفعال می‌کند، بازنشانی پاکش می‌کندمهاجم نمی‌تواند شما را بیرون نگه داردصندوق ایمیل کلید می‌شود

Enumeration از طریق بازنشانی و ثبت‌نام ​

راه‌حلچطورمزیتهزینه
یک پیام«اگر حسابی وجود داشته باشد...»oracle نداردتجربهٔ کاربری کمی بدتر
ایمیل صف‌شدهفراخوان broker را در یک job بفرستیدزمان یکسانزیرساخت async
ثبت‌نام با لینک ایمیلی«صندوق ایمیل را ببینید»؛ به صاحب فعلی اطلاع بدهیدثبت‌نام دیگر نشت نمی‌کندیک مرحلهٔ اضافه

replay کد TOTP ​

راه‌حلچطورمزیتهزینه
آخرین گام پذیرفته‌شدهstep > last_step را در تراکنش ورود ذخیره و الزام کنیددقیقاً همان الزام RFC 6238یک ستون
کش کدهای استفاده‌شدهFortify timestampهای استفاده‌شده را به‌ازای کد کش می‌کندبدون تغییر schemaکش باید بین همهٔ instanceها مشترک باشد

OTPهای فیش‌شده و push fatigue ​

راه‌حلچطورمزیتهزینه
PasskeyWebAuthn با UVوابسته به origin؛ چیزی برای رله نیستطراحی بازیابی
Number matchingpush عددی از صفحهٔ ورود نشان می‌دهدتأیید کورکورانه ناممکن می‌شودپشتیبانی ارائه‌دهندهٔ push
سقف pushN درخواست در هر ۱۰ دقیقهبمباران تمام می‌شودحالت‌های مرزی

عامل دوم گم‌شده ​

کدهای بازیابی (hash‌شده، یک‌بارمصرف، قابل‌بازسازی)، دست‌کم دو عامل ثبت‌شده، passkeyهای همگام‌شونده، و یک فرایند انسانی کند و ممیزی‌شده با اعلان و دورهٔ انتظار. هرگز نگذارید پشتیبانی «فقط MFA را خاموش کند».

logout واقعاً خارج نمی‌کند ​

session سمت سرور را حذف کنید، remember_token را بچرخانید، توکن‌های API را حذف و familyهای refresh را باطل کنید؛ برای JWT، access tokenها را ۵ تا ۱۵ دقیقه‌ای نگه دارید و برای کارهای پرخطر فهرست ابطال را بررسی کنید.

refresh token دزدیده‌شده ​

چرخش با ابطال family، عمر مطلق، ذخیره در keystore سیستم‌عامل روی موبایل، cookie با HttpOnly یا یک BFF برای مرورگرها، و اتصال با DPoP یا mTLS برای کلاینت‌های پرارزش.

ربوده شدن لینک بازنشانی ​

base URL ثابت (هرگز header Host)، Referrer-Policy: no-referrer، توکن ۲۵۶بیتی hash‌شده، عمر ۱۵ تا ۶۰ دقیقه، یک‌بارمصرف، فقط جدیدترین، ابطال sessionها بعد از استفاده، و MFA همچنان لازم.

hash کردن سرورهای ورود را ذوب می‌کند ​

throttle پیش از hash، تعیین حافظهٔ Argon2id بر اساس اوج هم‌زمانی، اجرای hash در یک worker pool محدود (در Go یک کانال semaphore)، مقیاس‌دهی جدای سرویس ورود، و پرهیز از costی که ورود را از حدود ۱۰۰ میلی‌ثانیه بالاتر ببرد.

انتخاب ​

کدام hash رمز ​

وضعیتانتخابپارامترهادلیل
سیستم جدید، Go یا PHPArgon2id19 MiB با t=2 و p=1 یا بیشتر، اندازه‌گیری‌شدهانتخاب اول OWASP، memory-hard
podهای کم‌حافظهArgon2id با حافظهٔ کمتر و t بیشتر (12 MiB با t=3، 9 MiB با t=4)ردیف‌های هم‌ارز OWASPهمان دفاع، RAM کمتر
FIPS 140 الزامی استPBKDF2-HMAC-SHA256600,000 تکرارتأییدشده و اعتبارسنجی‌شده
bcrypt موجودنگه دارید، cost را بالا ببرید، در ورود مهاجرت دهیدcost 12امن، اگر ورودی به ۷۲ بایت محدود شود
مقاومت در برابر dump آفلاین فراتر از hashpepper در KMS/HSM اضافه کنیدHMAC-SHA-256dump به‌تنهایی بی‌فایده است

کدام عامل دوم ​

کاربرانانتخاب اولجایگزینپرهیز
مصرف‌کنندگانpasskey (همگام‌شونده)TOTP، OTP ایمیلی برای اپ‌های کم‌خطرSMS به‌عنوان تنها گزینه
کارمندانpasskey یا Okta FastPass / platform authenticatorTOTP، push با number matchingpush سادهٔ تأیید/رد
مدیران، دسترسی productionsecurity key وابسته به دستگاه (AAL3)security key دومهر چیز فیش‌شدنی
حوزه‌های تحت نظارت (بانک)passkey + اتصال دستگاه، step-up برای هر تراکنشTOTPSMS بدون بررسی SIM swap

Session یا توکن ​

کلاینتحاملعمردلیل
اپ وب رندرشده در سرورcookie مربوط به session سمت سرورidle یک ساعت، absolute ۲۴ ساعت (AAL2)ابطال فوری، توکنی در JS نیست
SPA روی همان سایتcookie session با حالت SPA در Sanctum یا یک BFFهمانتوکن‌ها بیرون از JavaScript می‌مانند
اپ موبایلaccess token کوتاه + refresh token چرخشی۵ تا ۱۵ دقیقه / idle چهارده روز، مطلق ۳۰ تا ۹۰ روزبعد از راه‌اندازی دوباره زنده می‌ماند، باطل‌شدنی است
کلاینت API شخص ثالثتوکن opaque + introspection، یا OAuth client credentialsطبق قراردادقطع فوری
سرویس به سرویس داخلیهویت mTLS + JWT کوتاه۵ دقیقهبدون secret مشترک

ساختن یا خریدن ​

وضعیتتوصیهمحصولات
یک اپ، تیم کوچک، Laravelامکانات داخلی: Fortify یا یک starter kit، SanctumLaravel
یک سرویس Goکتابخانه‌ها + الگوهای این فصلx/crypto، go-webauthn، pquerna/otp، scs
چند اپ، SSO، مشتریان سازمانییک ارائه‌دهندهٔ هویتKeycloak (خودمیزبان)، Ory (متن‌باز / ابری)، Auth0/Okta، Amazon Cognito، Microsoft Entra ID
الزام سخت محل داده، کنترل کاملIdP خودمیزبانKeycloak، Ory Kratos + Hydra

در معماری: از یک process تا سیستم توزیع‌شده ​

Monolith (یکپارچه): یک process، یک پایگاه داده ​

یک monolith لاراولی با Fortify، session driver از نوع database و Argon2id یک طراحی کامل و درست است: throttling ورود در کش، sessionها در یک جدول (خروج از همه‌جا یک DELETE است)، secretهای TOTP رمزگذاری‌شده با رمزگذاری مبتنی بر APP_KEY، و رخدادهای ممیزی در یک جدول. دام‌ها محلی‌اند: انبار کشی که به‌ازای process است (driver از نوع array یا file روی چند سرور limiter را می‌شکند)، و APP_KEYی که secretهای TOTP را رمزگذاری می‌کند و کنار پایگاه داده زندگی می‌کند.

Modular monolith: مرز بدون شبکه ​

«Identity» را ماژولی کنید که مالک کاربران، credentialها، sessionها و رخدادهای ممیزی است، با یک interface کوچک: authenticate(credentials) -> AuthResult{user_id, amr, auth_time}، revokeAll(user_id)، requireFresh(maxAge). ماژول‌های دیگر (Billing، Orders) هرگز مستقیم users.password_hash یا sessions را نمی‌خوانند. همین مرز است که بعداً اجازه می‌دهد ماژول را بی‌آنکه به بقیه دست بزنید با یک IdP عوض کنید.

Microservices (میکروسرویس‌ها): هر پیکان یک تصمیم است ​

text
1    browser -> gateway/BFF        session cookie (opaque)          gateway looks up the session in Redis
2    gateway -> orders-service     JWT, 5 min, aud=orders           minted by the gateway from the session ("phantom token")
3    orders  -> payments-service   mTLS identity + user JWT          payments checks both: which service, on behalf of whom
4    identity-service              owns login, MFA, sessions        publishes user.password_changed, session.revoked events
5    consumers                     drop caches, close websockets    revocation reaches every service within seconds

احراز هویت متمرکز است (یک سرویس هویت یا یک IdP)، بررسی توزیع‌شده است (هر سرویس یک JWT کوتاه را با JWKS کش‌شده به‌صورت محلی بررسی می‌کند)، و ابطال به‌صورت رخداد یا با عمر کوتاه جریان پیدا می‌کند. هویت سرویس mTLS یا workload identity است؛ Mutual TLS و API Gateway, BFF & Service Mesh را ببینید.

داده‌های توزیع‌شده: replica، cache، region ​

  • Read replica. sessionی که روی primary باطل شده ممکن است هنوز از یک replica عقب‌مانده خوانده شود: sessionها و ابطال توکن را از primary یا Redis بخوانید، هرگز از replica ناهمگام.
  • کش. نتیجهٔ introspection و JWKS کش می‌شوند؛ TTL کش همان تأخیر ابطال شماست. برای introspection آن را در حد چند ثانیه نگه دارید.
  • وضعیت محدودیت نرخ. شمارنده‌ها باید مشترک باشند (Redis)، وگرنه مهاجم محدودیت شما را در تعداد instanceها ضرب می‌کند (Rate Limiting).
  • چند region. sessionها در یک انبار سراسری (DynamoDB global tables، Redis active-active با CRDT) یا کاربران سنجاق‌شده به یک region؛ تغییر رمز در یک region باید sessionها را در regionهای دیگر باطل کند، پس ابطال‌ها را به‌صورت رخداد منتشر کنید. RP ID در WebAuthn یک دامنه برای همهٔ regionهاست.
  • ساعت‌ها. TOTP و exp در JWT به ساعت همگام (NTP) وابسته‌اند؛ برای exp/nbf اندکی leeway بگذارید (چند ثانیه، نه چند دقیقه).

مسیر مقیاس: ۱ برابر، ۱۰ برابر، ۱۰۰ برابر ​

مقیاسورود در ثانیهطراحی
۱ برابر۱ تا ۱۰monolith، جدول sessions، Argon2id با 19 تا 64 MiB، throttling مبتنی بر کش
۱۰ برابر۱۰۰session در Redis، podهای ورود با اندازهٔ متناسب با حافظهٔ hash، قواعد bot در WAF روی /login، mirror فهرست رمزهای لورفته
۱۰۰ برابر۱۰۰۰+ و burstهای stuffingسرویس هویت اختصاصی یا IdP، مدیریت bot در لبه، worker pool برای hash، موتور ریسک، ابطال رخدادمحور، JWT کوتاه در داخل

آزمایشگاه: اندازه بگیرید، تست کنید، به ورود خودتان حمله کنید ​

همهٔ موارد در یک process اجرا می‌شوند؛ آزمایش‌های HTTP خروجی موردانتظار؛ اجرا نشده هستند.

۱. هزینهٔ hash را روی ماشین خودتان اندازه بگیرید (اجرا شد؛ عددهای این صفحه از همین آمده‌اند):

go
// Command lab measures what each password hashing setting costs on this
// machine (one call at a time; p=4 uses four goroutines inside IDKey),
// so the cost factor is chosen from numbers instead of folklore.
package main

import (
	"fmt"
	"time"

	"golang.org/x/crypto/argon2"
	"golang.org/x/crypto/bcrypt"
)

func timeIt(n int, f func()) time.Duration {
	f() // warm up
	start := time.Now()
	for i := 0; i < n; i++ {
		f()
	}
	return time.Since(start) / time.Duration(n)
}

func main() {
	pw, salt := []byte("correct horse battery staple"), []byte("0123456789abcdef")
	argon := []struct {
		name    string
		t, m    uint32
		threads uint8
	}{
		{"argon2id OWASP m=19MiB t=2 p=1", 2, 19 * 1024, 1},
		{"argon2id OWASP m=46MiB t=1 p=1", 1, 46 * 1024, 1},
		{"argon2id PHP/Laravel default m=64MiB t=4 p=1", 4, 64 * 1024, 1},
		{"argon2id RFC 9106 second m=64MiB t=3 p=4", 3, 64 * 1024, 4},
	}
	for _, a := range argon {
		d := timeIt(5, func() { argon2.IDKey(pw, salt, a.t, a.m, a.threads, 32) })
		fmt.Printf("%-46s %8.1f ms  %6.0f hashes/s\n", a.name, ms(d), 1/d.Seconds())
	}
	for _, cost := range []int{10, 12, 14} {
		d := timeIt(3, func() { _, _ = bcrypt.GenerateFromPassword(pw, cost) })
		fmt.Printf("%-46s %8.1f ms  %6.0f hashes/s\n", fmt.Sprintf("bcrypt cost %d", cost), ms(d), 1/d.Seconds())
	}
}

func ms(d time.Duration) float64 { return float64(d.Microseconds()) / 1000 }
text
$ cd docs/snippets/system-design/authentication-passwords-mfa-sessions/go && go run ./lab
argon2id OWASP m=19MiB t=2 p=1                     16.2 ms      62 hashes/s
argon2id OWASP m=46MiB t=1 p=1                     21.1 ms      47 hashes/s
argon2id PHP/Laravel default m=64MiB t=4 p=1      130.7 ms       8 hashes/s
argon2id RFC 9106 second m=64MiB t=3 p=4           27.3 ms      37 hashes/s
bcrypt cost 10                                     48.4 ms      21 hashes/s
bcrypt cost 12                                    192.5 ms       5 hashes/s
bcrypt cost 14                                    760.5 ms       1 hashes/s

۲. تست‌ها را اجرا کنید (اجرا شد):

text
$ go test ./...
ok  academy/authentication-passwords-mfa-sessions/login     (uniform errors, delays, spraying)
ok  academy/authentication-passwords-mfa-sessions/passkey   (creation options, single-use challenge)
ok  academy/authentication-passwords-mfa-sessions/pwhash    (salts, rehash, bcrypt, 72 bytes, NFC, pepper)
ok  academy/authentication-passwords-mfa-sessions/refresh   (rotation, reuse, expiry, logout everywhere)
ok  academy/authentication-passwords-mfa-sessions/reset     (one message, single use, newest only)
ok  academy/authentication-passwords-mfa-sessions/session   (idle, absolute, step-up rotation)
ok  academy/authentication-passwords-mfa-sessions/totp      (RFC 4226/6238 vectors, drift, replay, pquerna)
$ php php/tests/totp_vectors.php
all TOTP/HOTP vectors pass

۳. oracle زمانی علیه یک اپ Laravel (خروجی موردانتظار؛ اجرا نشده). با bcrypt و cost 12 (حدود ۱۹۰ ms) و timebox دویست‌میلی‌ثانیه‌ای، هر دو پاسخ حدود ۲۰۰ ms طول می‌کشند. BCRYPT_ROUNDS را به 14 برسانید (حدود ۷۶۰ ms) و حالت رمز غلط حدود ۵۶۰ ms کندتر از ایمیل ناموجود می‌شود:

text
$ for e in nobody@example.test ada@example.test; do
    curl -s -o /dev/null -w "$e %{http_code} %{time_total}\n" -X POST https://app.test/login \
      -d "email=$e&password=wrong" -H 'Accept: application/json'; done
nobody@example.test 422 0.203
ada@example.test 422 0.204          # rounds=12: indistinguishable
ada@example.test 422 0.771          # rounds=14: the timebox no longer hides the hash

۴. Throttling (خروجی موردانتظار؛ اجرا نشده): شش تلاش غلط برای یک ایمیل در یک دقیقه از یک IP.

text
1..5  422 {"message":"These credentials do not match our records."}
6     429 Retry-After: 60   {"message":"Too Many Attempts."}

۵. replay در TOTP (خروجی موردانتظار؛ اجرا نشده): یک کد معتبر را دو بار در ۳۰ ثانیه به /two-factor-challenge بفرستید؛ اولی 204 و دومی 422 برمی‌گرداند.

۶. استفادهٔ مجدد از refresh token (خروجی موردانتظار؛ اجرا نشده): token endpoint را با RT1 صدا بزنید (200 و RT2 برمی‌گردد)، دوباره با RT1 (400 با invalid_grant و یک ردیف refresh_token.reuse_detected در auth_events)، و بعد با RT2 (400 با invalid_grant).

بدفهمی‌های رایج ​

باورواقعیت
قواعد ترکیب رمز را قوی می‌کنندNIST SP 800-63B-4 ممنوعشان کرده؛ طول و blocklist کار می‌کنند
رمز باید هر ۹۰ روز منقضی شودبدون شاهد نشت ممنوع است
SHA-256 با salt کافی استhashهای سریع جلوی GPU می‌افتند؛ Argon2id، scrypt، bcrypt یا PBKDF2 با تعداد تکرار بالا
bcrypt کل رمز را hash می‌کندفقط ۷۲ بایت اول؛ PHP بی‌صدا می‌بُرد، Go رد می‌کند
pepper یک salt دوم استیک کلید مخفی است که بیرون از پایگاه داده نگه داشته می‌شود؛ چرخاندنش متن ساده لازم دارد
قفل کردن حساب بعد از ۵ شکست بهترین روش استابزار منع سرویس است؛ تأخیر، CAPTCHA و سقف ۱۰۰ شکست NIST
پیام خطای یکسان جلوی enumeration را می‌گیردزمان، status code و جریان‌های بازنشانی/ثبت‌نام هم نشت می‌دهند
2FA پیامکی برای مدیران کافی استNIST، PSTN را محدود کرده؛ SIM swap و رله امری روزمره‌اند
TOTP در برابر فیشینگ مقاوم استکدها بلادرنگ رله می‌شوند؛ فقط اتصال به origin مثل WebAuthn مقاوم است
passkey روی سرور ذخیره می‌شودفقط کلید عمومی؛ کلید خصوصی روی دستگاه یا keychain همگام‌شده می‌ماند
JWT از session امن‌تر استابطال را با بی‌حالتی معامله می‌کند
چرخش refresh token دزدی را بی‌خطر می‌کندفقط وقتی هر دو طرف refresh کنند تشخیص می‌دهد؛ عمر مطلق و DPoP اضافه کنید
logout یعنی پاک کردن cookie و تمامهر session، توکن remember me، توکن API و family مربوط به refresh باید باطل شود
بازنشانی رمز باید کاربر را وارد کندباید sessionهای دیگر را تمام کند و کاربر را به ورود (با MFA) بفرستد

چکیده ​

موضوعبه خاطر بسپارید
سیاست رمز۱۵+ نویسه (۸+ با MFA)، اجازهٔ ۶۴+، Unicode با NFC، blocklist، بدون ترکیب، بدون تعویض دوره‌ای، نمایش رمز
Hashحداقل Argon2id با m=19 MiB، t=2، p=1؛ رشتهٔ PHC را ذخیره کنید
bcryptcost 12، محدودیت ۷۲ بایت، مهاجرت هنگام ورود
FIPSPBKDF2-HMAC-SHA256 با 600,000
PepperHMAC با کلیدی در KMS/HSM، نسخه‌دار
Rehashدر همهٔ مسیرهای ورود موفق
شکست یکسانپیام، status، شکل و زمان یکسان؛ hash ساختگی
Throttlingپیش از hash؛ حساب + IP + سراسری؛ تأخیر تدریجی؛ حداکثر ۱۰۰
TOTPsecret ۱۶۰بیتی، ۳۰ ثانیه، skew برابر ۱، ذخیرهٔ آخرین گام، محدودیت نرخ
مقاومت در برابر فیشینگفقط passkey/WebAuthn یا گواهی کلاینت
کدهای بازیابی۶۴+ بیت، hash‌شده، یک‌بارمصرف، اعلان
Sessionشناسهٔ ۱۲۸+ بیتی، تعویض در ورود/step-up، idle یک ساعت، absolute ۲۴ ساعت، __Host-، HttpOnly، Secure، SameSite
توکن‌هاaccess ۵ تا ۱۵ دقیقه؛ refresh چرخشی با family و عمر مطلق
بازنشانی۲۵۶ بیت، hash‌شده، ۱۵ تا ۶۰ دقیقه، یک‌بارمصرف، ابطال sessionها، base URL ثابت
Step-upتازگی auth_time برای تغییر ایمیل/رمز/MFA و پرداخت
ممیزیهر رخداد احراز، هرگز خود secret

خودآزمایی: پرسش و پاسخ ​

نمایش:
  • حیاتی تقریباً در هر مصاحبه پرسیده می‌شود
  • مهم پرتکرار؛ در سطح senior انتظار می‌رود
  • تکمیلی عمق بیشتر؛ تمایز ایجاد می‌کند

۱ — چرا NIST SP 800-63B-4 قواعد ترکیب را ممنوع می‌کند و به‌جایش چه می‌خواهد؟ مهم ​

پاسخ

پاسخ: کاربران قابل‌پیش‌بینی واکنش نشان می‌دهند (Password1!)، پس قواعد ترکیب قدرت واقعی کمی اضافه می‌کنند و به کاربرپذیری آسیب می‌زنند. به‌جایش حداقل طول (۱۵ برای تک‌عاملی و ۸ وقتی بخشی از MFA است)، پشتیبانی از دست‌کم ۶۴ نویسه و Unicode، بررسی کل رمز با blocklist مقادیر رایج و لورفته، و محدودیت نرخ را می‌خواهد.

۲ — باید برای podهای ورود با 512 MiB حافظه که تا ۲۰ ورود هم‌زمان را پاسخ می‌دهند پارامتر Argon2id انتخاب کنید. چه انتخاب می‌کنید؟ تکمیلی ​

پاسخ

پاسخ: 20 x 19 MiB = 380 MiB جا می‌شود؛ 20 x 46 MiB = 920 MiB نه. m=19 MiB با t=2 و p=1 (یا 12 MiB با t=3 برای جای خالی بیشتر) را انتخاب کنید، زمان را روی همان نوع pod اندازه بگیرید و hash هم‌زمان را با یک semaphore محدود کنید تا burst به‌جای تمام کردن حافظه در صف بماند.

۳ — رمز bcrypt یک کاربر ۸۰ نویسه است. در PHP، در Go و در Laravel با bcrypt.limit برابر ۷۲ چه اتفاقی می‌افتد؟ تکمیلی ​

پاسخ

پاسخ: password_hash در PHP 8.5 بی‌صدا فقط ۷۲ بایت اول را hash می‌کند (بررسی کردیم که پسوند متفاوت هم verify می‌شود). bcrypt.GenerateFromPassword در Go خطای ErrPasswordTooLong برمی‌گرداند. Laravel با limit استثنای "Value is too long to hash" پرتاب می‌کند. Argon2id چنین محدودیتی ندارد.

۴ — چرا hash ساختگی حتی با پیام خطای یکسان اهمیت دارد؟ در Laravel چه چیزی آن را می‌شکند؟ مهم ​

پاسخ

پاسخ: بدون hash برای کاربران ناموجود، آن‌ها در چند میلی‌ثانیه و کاربران موجود در صدها میلی‌ثانیه پاسخ می‌گیرند و وجود حساب لو می‌رود. attempt/validate در Laravel این را با timebox دویست‌میلی‌ثانیه‌ای برای شکست‌ها پنهان می‌کنند؛ اگر خود hash بیش از ۲۰۰ ms طول بکشد (bcrypt با cost 14)، شکست با رمز غلط دوباره کندتر می‌شود و oracle برمی‌گردد.

۵ — یک botnet رمز «Winter2026!» را یک بار روی هر کدام از ۱۰۰,۰۰۰ حساب از ۲۰,۰۰۰ IP امتحان می‌کند. کدام کنترل آن را می‌گیرد؟ مهم ​

پاسخ

پاسخ: نه محدودیت به‌ازای حساب (هر کدام یک تلاش) و به‌سختی محدودیت per-IP (پنج تلاش به‌ازای هر IP). blocklist از اول نمی‌گذارد کاربران آن رمز را داشته باشند؛ هشدار سراسری روی نرخ شکست و روی یکسان بودن hash رمز در حساب‌های مختلف کارزار را تشخیص می‌دهد؛ تشخیص bot در لبه و MFA موفقیت را بی‌فایده می‌کنند.

۶ — قاعده‌ای را که verifier مربوط به TOTP برای جلوگیری از replay لازم دارد بنویسید و بگویید وضعیتش کجا نگه داشته می‌شود. مهم ​

پاسخ

پاسخ: کد را فقط وقتی بپذیرید که با گامی داخل پنجره مطابق باشد و آن گام اکیداً از آخرین گام پذیرفته‌شده برای همین کاربر بزرگ‌تر باشد؛ گام جدید را در همان تراکنش ورود ذخیره کنید (ستونی مثل mfa_totp.last_step). RFC 6238: verifier "MUST NOT accept the second attempt of the OTP".

۷ — چرا passkey در برابر فیشینگ مقاوم است و TOTP نه؟ حیاتی ​

پاسخ

پاسخ: مرورگر credential را به RP ID محدود می‌کند و origin واقعی را در clientDataJSON می‌گذارد که authenticator امضایش می‌کند. دامنهٔ شبیه‌سازی‌شده credentialی برای استفاده ندارد و challenge رله‌شده با origin غلط امضا می‌شود که سرور ردش می‌کند. کد TOTP فقط شش رقم است که کاربر را می‌شود فریب داد هر جایی تایپش کند.

۸ — تشخیص استفادهٔ مجدد از refresh token با دیدن یک توکن استفاده‌شده چه می‌کند و چرا کلاینت واقعی را هم تنبیه می‌کند؟ مهم ​

پاسخ

پاسخ: کل family (همهٔ توکن‌های آن ورود) را باطل می‌کند. سرور نمی‌تواند بفهمد توکن قدیمی را کلاینت ارائه کرده یا دزد، پس پایان دادن به grant برای هر دو تنها پاسخ امن است؛ کاربر دوباره وارد می‌شود.

۹ — همهٔ چیزهایی را که «خروج از همه‌جا» در یک اپ Laravel با Sanctum و یک کلاینت موبایل باید باطل کند فهرست کنید. حیاتی ​

پاسخ

پاسخ: همهٔ sessionهای پایگاه داده یا Redis برای این کاربر (و logoutOtherDevices برای auth.session)، remember_token، personal access tokenهای Sanctum، familyهای refresh token و هر نتیجهٔ introspection کش‌شده؛ و بعد اطلاع دادن به کاربر.

۱۰ — کدام کارها step-up لازم دارند و چطور آن را با session پیاده می‌کنید؟ حیاتی ​

پاسخ

پاسخ: تغییر ایمیل، رمز یا MFA، افزودن یا حذف passkey، دیدن کدهای بازیابی، برداشت پول، حذف حساب و کارهای مدیریتی. auth_time و amr را در session نگه دارید، الزام کنید now - auth_time زیر چند دقیقه باشد (در Laravel با password.confirm و password_timeout کوتاه‌تر)، دوباره احراز کنید، شناسهٔ session را عوض کنید و auth_time جدید را ثبت کنید.

واژه‌نامه ​

واژهمعنا
سطح اطمینان احراز (AAL)سطح‌های ۱ تا ۳ اطمینان به یک احراز در NIST SP 800-63B
مهلت مطلق (Absolute timeout)حداکثر عمر session صرف‌نظر از فعالیت
شمارش حساب‌ها (Account enumeration)فهمیدن اینکه کدام شناسه‌ها حساب دارند از روی پاسخ‌های متفاوت
AMRAuthentication Methods References در RFC 8176: pwd، otp، hwk، mfa، sms
Argon2idhash رمز memory-hard (RFC 9106)، ترکیبی از Argon2i و Argon2d
Assertionپاسخ احراز در WebAuthn: امضا روی authenticatorData و clientDataJSON
Attestationبیانیهٔ زمان ثبت دربارهٔ مدل authenticator؛ conveyance با none، indirect، direct، enterprise
احراز هویت (Authentication)اثبات اینکه یک درخواست از یک هویت مشخص آمده
Authenticatorچیزی که کاربر برای احراز در اختیار دارد: رمز، دستگاه OTP، passkey، security key
مجوزدهی (Authorization)تصمیم دربارهٔ اینکه هویت احرازشده چه کاری مجاز است
Backup eligibility / backup state (BE/BS)پرچم‌های WebAuthn برای credentialهای چنددستگاهی (همگام‌شونده)
bcrypthash رمز تطبیقی با cost factor و محدودیت ورودی ۷۲ بایت (72-byte limit)
بررسی رمز لورفته (Breached password check)مقایسهٔ رمز با مجموعهٔ رمزهای نشت‌کرده (مثل HIBP Pwned Passwords)
Brute forceحدس‌های زیاد روی یک حساب
CAPTCHAچالشی که انسان را از bot جدا می‌کند؛ Turnstile، hCaptcha، reCAPTCHA
Challengeمقدار تصادفی‌ای که سرور از authenticator می‌خواهد امضا کند
قواعد ترکیب (Composition rules)الزام ترکیب کلاس‌های نویسه؛ در NIST ممنوع
مقایسهٔ زمان‌ثابت (Constant-time compare)مقایسه‌ای که زمانش به محل تفاوت ورودی‌ها بستگی ندارد
Cookieمقداری که مرورگر نگه می‌دارد و به origin برمی‌گرداند؛ شناسهٔ session را حمل می‌کند
ضریب هزینه (Cost factor)پارامتر کار قابل‌تنظیم hash رمز (cost در bcrypt، m/t/p در Argon2، تعداد تکرار PBKDF2)
Credentialداده‌ای متصل به یک هویت که برای احراز به کار می‌رود
Credential stuffingامتحان دوبارهٔ جفت‌های نام کاربری/رمز لورفته از سایت‌های دیگر
Discoverable credential (resident key)credential در WebAuthn که همراه user handle روی authenticator ذخیره می‌شود؛ ورود بدون نام کاربری را ممکن می‌کند
DPoPDemonstrating Proof of Possession (RFC 9449): توکن‌های گره‌خورده به کلید کلاینت با proofهای امضاشده
پنجرهٔ انحراف (Drift window)تعداد گام‌های زمانی TOTP که اطراف گام فعلی پذیرفته می‌شوند
FIDO2WebAuthn به‌علاوهٔ CTAP2، استانداردهای FIDO Alliance برای احراز بدون رمز
Fortifybackend احراز هویت بدون رابط در Laravel
HOTPرمز یک‌بارمصرف مبتنی بر شمارنده (RFC 4226)
هویت (Identity)حساب و ویژگی‌هایی که یک شخص یا سرویس را نمایندگی می‌کنند
مهلت بی‌فعالیتی (Idle timeout)پایان session بعد از مدتی بدون فعالیت
Introspectionendpoint در RFC 7662 که می‌گوید توکن active است یا نه و فرادادهٔ آن چیست
JWTJSON Web Token، claimهای امضاشده که بدون lookup بررسی می‌شوند
قفل حساب (Lockout)مسدود کردن حساب یا authenticator بعد از تلاش‌های ناموفق
خروج از همه‌جا (Logout everywhere)باطل کردن همهٔ sessionها و توکن‌های یک حساب
هزینهٔ حافظه / زمان / موازی‌سازی (Memory cost / time cost / parallelism)پارامترهای m (KiB)، t (گذر)، p (lane) در Argon2
MFA / 2FAاحراز با دو یا چند نوع عامل؛ 2FA یعنی دقیقاً دو
MFA fatigueبمباران push تا کاربر تأیید کند
Number matchingpush MFA که کاربر عدد نمایش‌داده‌شده روی صفحهٔ ورود را تایپ یا انتخاب می‌کند
توکن opaque (Opaque token)توکن مرجع تصادفی بدون محتوای خوانا
PasskeyFIDO credential قابل‌کشف، همگام‌شونده یا وابسته به دستگاه
Password sprayingیک رمز رایج روی تعداد زیادی حساب
PBKDF2مشتق‌سازی کلید با HMAC تکراری؛ hash رمز تأییدشدهٔ FIPS
Pepperکلید مخفی اعمال‌شده روی همهٔ hashهای رمز که بیرون از پایگاه داده نگه داشته می‌شود
مقاوم در برابر فیشینگ (Phishing-resistant)احرازی که نمی‌شود آن را به verifier جعلی رله کرد (WebAuthn، TLS کلاینت)
کد بازیابی (Recovery code)secret ذخیره‌شدهٔ یک‌بارمصرف برای بازگرداندن دسترسی
Refresh tokenتوکن بلندمدتی که فقط برای گرفتن access token جدید به کار می‌رود
Rehashجایگزینی hash ذخیره‌شده با hashی با الگوریتم/پارامترهای فعلی هنگام ورود
Relying party (RP)سایتی که برای احراز به WebAuthn یا federation تکیه می‌کند؛ RP ID دامنهٔ آن است
Remember meتوکن بلندمدتی که بعد از بستن مرورگر session را دوباره می‌سازد
Replayاستفادهٔ دوباره از کد یا توکن رهگیری‌شده
تشخیص استفادهٔ مجدد (Reuse detection)ابطال family مربوط به refresh token وقتی یک توکن استفاده‌شده دوباره ارائه می‌شود
احراز هویت مبتنی بر ریسک (Risk-based authentication)تطبیق اثبات لازم با سیگنال‌هایی مثل دستگاه، IP و مکان
چرخش (Rotation)برای توکن: صدور refresh token جدید در هر استفاده؛ برای رمز: تعویض اجباری دوره‌ای که NIST ممنوع کرده
Saltمقدار تصادفی مخصوص هر hash که کنار آن ذخیره می‌شود
Sanctumبستهٔ Laravel برای احراز SPA با session و personal access token
Passportسرور OAuth 2.0 در Laravel
scryptتابع مشتق‌سازی کلید memory-hard (N، r، p)
Sessionوضعیت سمت سرور که یک شناسهٔ تصادفی را به هویت احرازشده وصل می‌کند
Session fixationمهاجم پیش از ورود شناسهٔ session را جا می‌اندازد؛ با regenerate کردن شناسه جلوگیری می‌شود
Sign countشمارندهٔ WebAuthn برای تشخیص authenticatorهای کلون‌شده
توکن یک‌بارمصرف (Single-use token)توکنی که با اولین استفاده حذف می‌شود (لینک بازنشانی، کد بازیابی)
SIM swapانتقال شمارهٔ تلفن قربانی به سیم‌کارت مهاجم
SMS OTPکد یک‌بارمصرف از طریق شبکهٔ تلفن؛ authenticator محدودشده در NIST
توکن بی‌حالت (Stateless token)توکن خودبسنده که بدون وضعیت سرور بررسی می‌شود
Step-up authenticationالزام اثبات تازه پیش از یک کار حساس
Passkey همگام‌شونده (Synced passkey)passkeyی که ارائه‌دهندهٔ passkey آن را با رمزگذاری سرتاسری بین دستگاه‌ها کپی می‌کند
Timing attackاستنتاج secret یا وجود حساب از زمان پاسخ
Token bindingگره زدن توکن به کانال TLS (RFC 8471)؛ در عمل DPoP و mTLS جایش را گرفته‌اند
TOTPرمز یک‌بارمصرف زمان‌محور (RFC 6238)
User verification (UV)پرچم WebAuthn: authenticator یک PIN یا biometric را بررسی کرده
WebAuthnAPI در W3C برای public key credentialهای محدود به یک relying party
Keycloak / Auth0 / Okta / Cognito / Oryارائه‌دهندگان هویت: متن‌باز خودمیزبان، SaaS، مدیریت‌شده در AWS، متن‌باز با نسخهٔ ابری
go-webauthn / pquerna/otpکتابخانه‌های Go برای relying party در WebAuthn و برای TOTP/HOTP

منابع ​

ساخته‌شده توسط Morteza Negahi