Skip to content

Authentication in Go: Argon2/bcrypt, Sessions, JWT, Middleware, CSRF, Sanitization, Password Reset ​

"Once an authenticated session has been established, the session ID (or token) is temporarily equivalent to the strongest authentication method used by the application, such as username and password, passphrases, one-time passwords (OTP), client-based digital certificates, smartcards, or biometrics (such as fingerprint or eye retina)." — OWASP Session Management Cheat Sheet

خلاصه (Summary): احراز هویت (Authentication) در Go زنجیره‌ای از قطعه‌های کوچک و آزمون‌پذیر است: هش گذرواژه (Password hashing) کند و saltدار با Argon2id یا bcrypt، بررسی زمان‌ثابت، نشستی (Session) پشت cookie با پیشوند __Host- یا JWT کوتاه‌عمر همراه refresh چرخشی، میان‌افزاری (Middleware) که هویت تأییدشده را در context می‌گذارد، کنترل مجوز (Authorization) در هر handler و دفاع مرورگر با CSRF و کدگذاری خروجی (Output encoding). مسیرهای reset، تأیید ایمیل، lockout، TOTP و logout هم جزو همین زنجیره‌اند؛ رخنه‌ها اغلب در همین حاشیه‌ها اتفاق می‌افتند. تمرکز (Focus): هش گذرواژه با golang.org/x/crypto/argon2 و bcrypt، پارامترهای RFC 9106 و OWASP، قالب رشتهٔ PHC، مقایسه با crypto/subtle، نمک و secret مشترک (Salt و Pepper)، قواعد گذرواژه در NIST SP 800-63B-4، ساخت شناسهٔ نشست با crypto/rand، ویژگی‌ها و پیشوندهای cookie و چرخش و مهلت نشست؛ مدیریت نشست با alexedwards/scs و gorilla/sessions؛ JWT با golang-jwt/jwt/v5 و EdDSA، بررسی ادعاها و چرخش kid، سردرگمی الگوریتم، چرخش refresh token و ابطال آن، دریافت JWKS و کلاینت‌های x/oauth2 و go-oidc؛ هویت در context و کنترل مجوز هر handler برای جلوگیری از IDOR؛ توکن CSRF و http.CrossOriginProtection در Go 1.25؛ تفاوت اعتبارسنجی ورودی، پاک‌سازی با bluemonday و escaping با html/template؛ توکن بازیابی و تأیید ایمیل، محدودسازی حساب و نرخ تلاش، حملهٔ زمانی، TOTP با pquerna/otp، passkey با go-webauthn، خروج امن و شیوهٔ بسته‌بندی همین تصمیم‌ها در starter kitها، Fortify و Sanctum در Laravel. هدف یادگیری (Learning goal): با stdlib و چند بستهٔ شناخته‌شده لایهٔ login و session و token بسازید، دلیل هر flag و پارامتر را بدانید و با دیدن کد، hash سریع، == روی secret، enumeration، fixation، اعتماد به alg، نبود aud، IDOR، cookie بدون CSRF، reset token خام و logout صرفاً مرورگری را تشخیص دهید.

موضوع این صفحه پیاده‌سازی Authentication در Go است: کد، بسته، پارامتر و ترتیب بررسی. مبانی hash و HMAC و HKDF و APIهای crypto/rand در Hashing & Crypto، مفهوم ذخیرهٔ password و امضای token در Password Hashing & Signed Tokens، الگوی middleware و security header و CORS و شرح http.CrossOriginProtection در Middlewares، مسیریابی ServeMux و r.PathValue در net/http، فرم و flash و layout در html/template و الگوریتم محدودسازی در Rate Limiting in Go است. طراحی سطح سیستم را در Authentication: Passwords, MFA & Sessions، JWT Deep Dive، OAuth2, OIDC & SSO، Web Sessions, Cookies & CORS و OWASP Top 10 دنبال کنید.

مطالب این صفحه با سورس کتابخانهٔ استاندارد Go 1.27 در go.dev بررسی شده‌اند: crypto/subtle، crypto/rand، crypto/hmac، فایل‌های cookie.go و csrf.go و server.go در net/http و html/template؛ pkg.go.dev به دریافت اسکریپتی 403 می‌داد. یادداشت‌های Go 1.22 و 1.24 و 1.25 و سورس golang.org/x/crypto (بسته‌های argon2 و bcrypt)، golang-jwt/jwt/v5، alexedwards/scs/v2، gorilla/sessions، pquerna/otp، microcosm-cc/bluemonday، coreos/go-oidc/v3، golang.org/x/oauth2، go-webauthn/webauthn و MicahParks/keyfunc هم مبنا بوده‌اند. منابع استاندارد شامل RFC 9106 (Argon2)، 7515/7517/7518/7519 (JOSE و JWT)، 8725 (بهترین رویه‌های JWT)، 9068، 9700 (رویه‌های امنیت OAuth 2.0)، 6238 و 4226 (TOTP و HOTP)، 6265، مشخصات C2SP PHC و NIST SP 800-63B-4 است؛ همراه راهنماهای OWASP برای Authentication، Session Management، Password Storage، CSRF، Forgot Password، JWT، MFA، XSS، Input Validation و Credential Stuffing، راهنماهای Set-Cookie و cookie در MDN و نوشتهٔ CSRF از Filippo Valsorda. مستندات Laravel 13 برای authentication، Sanctum، hashing، passwords، verification، CSRF، session، rate limiting، Fortify و starter kit و برای سابقهٔ Breeze مستند Laravel 11 و یادداشت Laravel 12 بررسی شده‌اند. snippetها go 1.24 اعلام و golang.org/x/crypto v0.48.0 (v0.49.0 به Go 1.25 نیاز دارد)، golang.org/x/time v0.14.0، github.com/golang-jwt/jwt/v5 v5.3.1، github.com/alexedwards/scs/v2 v2.9.0، github.com/pquerna/otp v1.5.0 و github.com/microcosm-cc/bluemonday v1.0.27 را pin کرده‌اند. فایل API جدید Go 1.25 قید //go:build go1.25 دارد. هر 14 بسته در اجرای ثبت‌شده با Go 1.27.4 روی macOS و Apple M4 Pro کامپایل، vet و با -race تست شده‌اند؛ عددهای آزمایشگاه از همان اجراست.

نقشهٔ صفحه (Page map) ​

اگر دنبال این هستیدبروید به
جدول‌های قابل حفظ در یک دقیقههمه‌چیز در یک دقیقه
چرا احراز هویت یک زنجیره استچرا وجود دارد
پیشینهٔ bcrypt، PHC، Argon2، JWT و TOTPاز کجا آمده
handler ورود، قبل و بعدGo
هش گذرواژه، salt و pepperهش گذرواژه
Argon2id با x/crypto/argon2، پارامترهای RFC 9106 و قالب رشتهٔ PHCArgon2id
bcrypt با x/crypto/bcrypt، هزینهٔ محاسبه و سقف 72 بایتbcrypt
مقایسهٔ زمان‌ثابت با crypto/subtle و حمله‌های زمانیزمان‌ثابت
سیاست گذرواژه طبق NIST 800-63Bسیاست گذرواژه
نشست سمت سرور، entropy شناسه با crypto/rand، ویژگی‌های HttpOnly و Secure و SameSite، چرخش هنگام ورود و مهلت بی‌فعالیتی و مطلقنشست‌ها
مدیریت نشست با alexedwards/scs و gorilla/sessionsکتابخانه‌های نشست
JWT با golang-jwt/jwt نسخهٔ 5، مقایسهٔ HS256 با RS256 و ES256 و EdDSA، بررسی exp و nbf و iat و aud و issJWT
سردرگمی الگوریتم و چرخش کلید با kidالگوریتم و کلید
access token کوتاه‌عمر، refresh token و ابطال آن‌هانوسازی و ابطال
دریافت مجموعهٔ کلیدهای JWKSJWKS
راهنمای کلاینت OAuth2 و OIDC با x/oauth2 و coreos/go-oidcOAuth2 و OIDC
میان‌افزار احراز هویت، هویت در context و کنترل مجوز هر handlerمیان‌افزار و مجوز
دفاع CSRF با double-submit cookie، SameSite، بررسی Origin و http.CrossOriginProtection در Go 1.25CSRF
تفاوت اعتبارسنجی ورودی، پاک‌سازی با bluemonday و encoding خروجی با auto-escaping در html/templateاعتبارسنجی، پاک‌سازی و encoding
بازیابی گذرواژه با token یک‌بارمصرف، ذخیرهٔ hash، انقضا و پاسخ بدون افشای وجود حساببازیابی گذرواژه
تأیید مالکیت آدرس ایمیلتأیید ایمیل
محدودسازی حساب و نرخ تلاش‌های ورودمحدودسازی
احراز چندعاملی با TOTP و pquerna/otp طبق RFC 6238 و کدهای بازیابیTOTP
راهنمای passkey و WebAuthn با go-webauthnکلید عبور
خروج امن از حسابخروج
مدل داده، headerها، متن خطاها و schemaسازوکار
باگ‌های رایج و اصلاحشانحل مسئله‌ها
چه وقت از چه استفاده کنیمانتخاب
از monolith تا سیستم توزیع‌شدهمعماری
بازسازی روی ماشین خودتانآزمایشگاه
مقایسه با Laravel Breeze و Sanctumبرای توسعه‌دهندگان PHP/Laravel

همه‌چیز در یک دقیقه (One minute) ​

زنجیره. هر درخواست احرازشده از این حلقه‌ها به همین ترتیب می‌گذرد؛ ضعف هر حلقه ضعف کل مسیر است. هر سطر در فهرست مفاهیم باز می‌شود.

حلقهابزار Goبه زبان سادهشکست رایج
ذخیرهٔ passwordargon2.IDKey / bcrypt.GenerateFromPasswordهزینهٔ هر حدس، میلی‌ثانیه و مگابایتsha256(password)، بدون salt
بررسی passwordsubtle.ConstantTimeCompare، hash ساختگی (Dummy hash)زمان و جواب شکست یکسانتفاوت کاربر ناموجود و password غلط
محدودسازی حدسbackoff حساب و x/time/rate برای IPحدس آنلاین صرف نکندتلاش نامحدود یا lockout قابل DoS
حمل نتیجه__Host- session cookie یا JWTbearer secret هم‌ارز password می‌شودID قابل حدس، بدون rotation، اعتماد به alg
هویت در ctxcontext.WithValue و کلید unexportedhandler از From(ctx) بخواندهویت از header یا query
کنترل مجوز (Authorization)بررسی handler پس از load«فاکتور مال شماست؟»IDOR و خواندن هر ID
دفاع مرورگرCSRF token، SameSite، CrossOriginProtection، html/templateسایت دیگر از جانب کاربر عمل یا تزریق نکندنبود CSRF، template.HTML(userInput)
پایانحذف session سرور، ابطال refresh familylogout روی سرور هم اثر کندcookie پاک، session معتبر

Session در برابر token.

ویژگیSession سمت سرور با cookieJWT access token از نوع bearer
دارایی کلاینتID تصادفی opaque با 256 بیتJSON امضاشده؛ این‌جا حدود 350 بایت
بررسی درخواستlookup با sha256(id)امضا و exp/iss/aud بدون lookup
ابطال فوری (Revocation)حذف سطرپیش از exp بدون denylist ممکن نیست
عمر معمولidle برابر 30 min و absolute برابر 8-12 haccess برابر 5-15 min؛ refresh چند روز
CSRFبله، ارسال خودکار cookieدر Authorization خیر
XSSHttpOnly، cookie را پنهان می‌کندlocalStorage برای هر script خواندنی است
مناسبrender سرور، SPA خودتانسرویس‌به‌سرویس، موبایل، API شخص ثالث
بستهٔ Gostdlib، alexedwards/scs/v2، gorilla/sessionsgolang-jwt/jwt/v5، MicahParks/keyfunc

پارامترهای حفظ‌کردنی.

تنظیممقدارمنبع
حداقل Argon2id در OWASPm=19456 KiB (19 MiB), t=2, p=1OWASP Password Storage
گزینهٔ دوم RFC 9106t=3, p=4, m=64 MiB، salt برابر 128 بیت، tag برابر 256 بیتRFC 9106 بخش 4
bcrypt costحداقل 10؛ bcrypt.DefaultCost = 10؛ این‌جا 12؛ سقف 72 بایتOWASP، x/crypto
Saltحداقل 32 بیت؛ این‌جا 128NIST SP 800-63B-4
Session IDحداقل entropy برابر 64 بیت؛ این‌جا 256 از crypto/randOWASP Session Management
طول passwordحداقل 15 تک‌عامل، 8 با MFA؛ پذیرش حداقل 64؛ بدون composition ruleNIST SP 800-63B-4
idle / absolute timeoutحساس 2-5 min، کم‌خطر 15-30 min؛ absolute برای روز اداری 4-8 hOWASP Session Management
TOTPگام 30 s، طول 6 رقم، حداکثر یک گام skew، رد replayRFC 6238
شکست‌هاسقف 100 شکست متوالی هر حساب پیش از غیرفعال‌سازیNIST SP 800-63B-4
Reset tokenتصادفی و به‌اندازهٔ کافی بلند؛ 128+ بیت مطابق کف token session در OWASP؛ hash، یک‌بارمصرف، 30-60 minOWASP Forgot Password و Session Management، Laravel expire => 60

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

HTTP بی‌حالت (Stateless) است: هر درخواست مثل یک غریبه می‌رسد. احراز هویت (Authentication) راهی است که سرور «یک نفر یک بار password وارد کرده» را بارها و برای ساعت‌ها به «این درخواست از کاربر 7 است» تبدیل کند، بدون این‌که هر بار دوباره password بخواهد. هم‌زمان مهاجم تلاش می‌کند password را حدس بزند، چیزی را که جای آن نشسته بدزدد، از سایت دیگری سوار مرورگر کاربر شود یا صرفاً جدول کاربران را از یک backup بخواند. هیچ تابع واحدی همهٔ این‌ها را حل نمی‌کند. مجموعه‌ای از تصمیم‌هاست و کد هر تصمیم آن‌قدر کوچک است که می‌توان آن را درست ساخت؛ به همین دلیل این صفحه مسئله را به حدود دوازده بستهٔ آزموده تقسیم می‌کند.

ساخت آسان‌ترحمله سخت‌تر
sha256(password)Argon2id با salt هر کاربر و cost افزایشی
if hash == storedsubtle.ConstantTimeCompare و hash ساختگی (Dummy hash) برای کاربر ناشناخته
«این ایمیل حساب ندارد»پیام عمومی همهٔ شکست‌ها
ID افزایشی256 بیت crypto/rand و hash در store
حفظ ID در loginrotation هر تغییر privilege
JWT بلندعمرaccess ده‌دقیقه‌ای، refresh چرخشی، revocation list
اعتماد به algیک الگوریتم مجاز برای هر کلید
فقط role در middlewareload شیء و مالکیت در handler
حذف cookie در logoutحذف state سرور هم

تصویری از زندگی روزمره. هتل را تصور کنید. پذیرش یک بار گذرنامه را بررسی می‌کند (password verification) و سپس کارت اتاق می‌دهد (session ID یا token). کارت، اتاق شما را در طول اقامت باز می‌کند (lifetime) و اگر مدتی برنگردید از کار می‌افتد (idle timeout). اگر اتاق را به سوئیت عوض کنید، کارت تازه می‌گیرید و قبلی باطل می‌شود (rotation هنگام تغییر privilege). کارت معمولی فقط شماره‌ای است که قفل در، آن را در فهرست پذیرش جست‌وجو می‌کند (server-side session). هتل پیشرفته شمارهٔ اتاق و تاریخ خروج را روی خود کارت چاپ و امضا می‌کند تا قفل‌ها آفلاین بررسی کنند (JWT)؛ اما دیگر نمی‌تواند کارت گمشده را پیش از checkout باطل کند مگر به همهٔ قفل‌ها خبر بدهد (revocation). کارت فقط اتاق شما را باز می‌کند، نه همهٔ اتاق‌های طبقه (authorization). پذیرش هم هیچ‌وقت شمارهٔ گذرنامه را روی یادداشت چسبان نمی‌نویسد (password hashing).

سه بدفهمی از ابتدا ​

  1. «JWT از session cookie امن‌تر است.» این یک مبادلهٔ متفاوت است: lookup هر درخواست حذف می‌شود، در عوض ابطال فوری را از دست می‌دهید و خطرهای انتخاب الگوریتم و مدیریت کلید را می‌پذیرید. برای مرورگری که با backend خودش صحبت می‌کند، server-side session معمولاً انتخاب محکم‌تر و ساده‌تری است.
  2. «Hash کردن password با SHA-256 و salt کافی است.» salt جلوی جدول‌های ازپیش‌محاسبه‌شده را می‌گیرد، نه حدس‌زدن را؛ یک GPU میلیاردها hash از SHA-256 در ثانیه می‌سازد. Password hash باید عمداً کند و memory-hard مثل Argon2id باشد، یا دست‌کم کند مثل bcrypt.
  3. «Authentication middleware یعنی endpoint امن است.» middleware ثابت می‌کند چه کسی فراخواننده است. این‌که همان شخص اجازهٔ خواندن فاکتور 1001 را دارد، پرسشی است که فقط handler بارگیرندهٔ همان فاکتور می‌تواند جواب بدهد. حذف این بررسی، Broken Object Level Authorization یا IDOR است؛ API1:2023، اولین مورد OWASP API Security Top 10.

از کجا آمده ​

bcrypt را Niels Provos و David Mazières در USENIX سال ۱۹۹۹ منتشر کردند (همان مقاله‌ای که comment بستهٔ x/crypto/bcrypt به آن پیوند می‌دهد). ایده‌ای که هنوز مبنای password hashing است، ضریب کار (Work factor) قابل تنظیم بود تا با سریع‌تر شدن سخت‌افزار بتوان hash را کندتر کرد. Password Hashing Competition در ۲۰۱۵، Argon2 را برنده کرد؛ به‌گفتهٔ OWASP: "Argon2 was the winner of the 2015 Password Hashing Competition". RFC 9106 در سپتامبر ۲۰۲۱ آن را با پیشنهادهای مشخص پارامتر استاندارد کرد. قالب PHC string format با شکل $argon2id$v=19$m=...,t=...,p=...$salt$hash از همین مسابقه آغاز شد و به C2SP، در فایل phc-strings.md، منتقل شده است. در Go هر دو در golang.org/x/crypto هستند؛ خطوط copyright فایل‌ها برای bcrypt سال ۲۰۱۱ و برای argon2 سال ۲۰۱۷ را نشان می‌دهند. هیچ‌کدام جزو کتابخانهٔ استاندارد نیستند.

JWT در RFC 7519، مهٔ ۲۰۱۵، روی JWS (RFC 7515)، JWK (RFC 7517) و JWA (RFC 7518) بنا شد. کتابخانه‌های اولیه header نوع alg را باور می‌کردند؛ نتیجه حمله‌های "none" و RS256-to-HS256 بود که RFC 8725 در فوریهٔ ۲۰۲۰، با عنوان JWT Best Current Practices، فهرست کرد. در Go، dgrijalva/jwt-go کتابخانهٔ عملاً رایج بود تا تیمی از نگه‌دارندگان آن را به golang-jwt/jwt fork کردند؛ README به گفت‌وگوی واگذاری پیوند دارد. v5 بنا بر راهنمایش "introduces major improvements to the validation of tokens"، با Validator و گزینه‌هایی مثل WithLeeway، WithAudience و WithIssuer. TOTP در RFC 6238، مهٔ ۲۰۱۱، بر HOTP (RFC 4226) بنا شد. RFC 9700 در ژانویهٔ ۲۰۲۵ برای public OAuth client، refresh token rotation یا sender-constraining را الزامی کرد.

در کتابخانهٔ استاندارد، Go 1.22 الگوهای method و wildcard را به ServeMux افزود؛ به همین دلیل Authorization هر route می‌تواند r.PathValue("id") را بخواند. Go 1.24، crypto/rand.Read را "guaranteed not to fail" کرد و rand.Text را برای "cryptographically secure random text strings" افزود. Go 1.25 نوع http.CrossOriginProtection را آورد که به‌گفتهٔ release notes، "implements protections against Cross-Site Request Forgery (CSRF) by rejecting non-safe cross-origin browser requests". NIST SP 800-63B-4، بازنگری ۲۰۲۵ راهنماهای هویت دیجیتال، نام "memorized secrets" را به passwords تغییر داد؛ حداقل طول تک‌عامل را 15 کاراکتر تعیین کرد و ممنوعیت composition rule و تغییر اجباری دوره‌ای را نگه داشت.

Go ​

قبل ​

این login در روز آرام کار می‌کند: sha256(password) بدون salt، مقایسه با !=، افشای وجود ایمیل، حفظ ID ارسالی مرورگر یا تولید ID ترتیبی، cookie بدون flag و logout صرفاً با حذف cookie. حفظ ID معلوم مهاجم همان تثبیت نشست (Session fixation) است.

go
// Package before is a login that works on a quiet day and fails every audit:
// fast unsalted hash, == comparison, messages that reveal which accounts
// exist, a guessable session ID, a cookie without flags, no rotation, no
// throttling, and a logout that only deletes the cookie in the browser.
package before

import (
	"crypto/sha256"
	"encoding/hex"
	"net/http"
	"strconv"
	"sync"
)

type Server struct {
	mu       sync.Mutex
	users    map[string]string // email -> hex(sha256(password))
	sessions map[string]string // session id -> email
	next     int
}

func New() *Server {
	return &Server{users: map[string]string{}, sessions: map[string]string{}, next: 1000}
}

// Register stores sha256(password): no salt, no cost. Equal passwords give
// equal hashes, and a GPU tries billions of guesses per second.
func (s *Server) Register(email, pw string) string {
	sum := sha256.Sum256([]byte(pw))
	h := hex.EncodeToString(sum[:])
	s.mu.Lock()
	s.users[email] = h
	s.mu.Unlock()
	return h
}

func (s *Server) Login(w http.ResponseWriter, r *http.Request) {
	email, pw := r.PostFormValue("email"), r.PostFormValue("password")
	s.mu.Lock()
	stored, ok := s.users[email]
	s.mu.Unlock()
	if !ok {
		http.Error(w, "no account with that email", http.StatusNotFound) // enumeration
		return
	}
	sum := sha256.Sum256([]byte(pw))
	if hex.EncodeToString(sum[:]) != stored { // early-exit comparison
		http.Error(w, "wrong password", http.StatusUnauthorized)
		return
	}
	// Keep any session id the client already had (fixation), or mint a
	// sequential one (guessable).
	id := ""
	if c, err := r.Cookie("sid"); err == nil {
		id = c.Value
	} else {
		s.mu.Lock()
		s.next++
		id = strconv.Itoa(s.next)
		s.mu.Unlock()
	}
	s.mu.Lock()
	s.sessions[id] = email
	s.mu.Unlock()
	http.SetCookie(w, &http.Cookie{Name: "sid", Value: id}) // no HttpOnly, Secure, SameSite
	w.Write([]byte("welcome"))
}

// Logout clears the cookie; the server-side session stays valid forever.
func (s *Server) Logout(w http.ResponseWriter, r *http.Request) {
	http.SetCookie(w, &http.Cookie{Name: "sid", Value: "", MaxAge: -1})
}

func (s *Server) Me(w http.ResponseWriter, r *http.Request) {
	c, err := r.Cookie("sid")
	s.mu.Lock()
	email, ok := "", false
	if err == nil {
		email, ok = s.sessions[c.Value]
	}
	s.mu.Unlock()
	if !ok {
		http.Error(w, "unauthenticated", http.StatusUnauthorized)
		return
	}
	w.Write([]byte(email))
}

هر assertion تست یک ضعف را ثابت می‌کند؛ تست فهرست یافته‌های امنیتی است.

go
package before

import (
	"net/http"
	"net/http/httptest"
	"net/url"
	"strconv"
	"strings"
	"testing"
)

func login(s *Server, email, pw string, cookie *http.Cookie) *httptest.ResponseRecorder {
	form := url.Values{"email": {email}, "password": {pw}}
	req := httptest.NewRequest("POST", "/login", strings.NewReader(form.Encode()))
	req.Header.Set("Content-Type", "application/x-www-form-urlencoded")
	if cookie != nil {
		req.AddCookie(cookie)
	}
	rec := httptest.NewRecorder()
	s.Login(rec, req)
	return rec
}

// Each assertion documents a weakness; package after fixes every one.
func TestBeforeWeaknesses(t *testing.T) {
	s := New()
	a := s.Register("alice@example.test", "summer2026")
	b := s.Register("bob@example.test", "summer2026")
	if a != b {
		t.Fatal("expected identical hashes for identical passwords (no salt)")
	}

	unknown := login(s, "nobody@example.test", "x", nil)
	wrong := login(s, "alice@example.test", "x", nil)
	if unknown.Code == wrong.Code || unknown.Body.String() == wrong.Body.String() {
		t.Fatal("expected distinguishable answers (user enumeration)")
	}

	ok := login(s, "alice@example.test", "summer2026", nil)
	c := ok.Result().Cookies()[0]
	if raw := ok.Header().Get("Set-Cookie"); raw != "sid="+c.Value {
		t.Fatalf("expected a cookie without flags, got %q", raw)
	}
	n, err := strconv.Atoi(c.Value)
	if err != nil {
		t.Fatal("expected a numeric session id")
	}
	if next := strconv.Itoa(n + 1); next != "1002" {
		t.Fatalf("expected the next id to be guessable, got %s", next)
	}

	// Session fixation: the attacker's planted id becomes an authenticated one.
	planted := &http.Cookie{Name: "sid", Value: "attacker-chosen"}
	login(s, "bob@example.test", "summer2026", planted)
	req := httptest.NewRequest("GET", "/me", nil)
	req.AddCookie(planted)
	rec := httptest.NewRecorder()
	s.Me(rec, req)
	if rec.Body.String() != "bob@example.test" {
		t.Fatal("expected the planted session id to be logged in as bob")
	}

	// Logout does not end the server-side session.
	s.Logout(httptest.NewRecorder(), req)
	rec = httptest.NewRecorder()
	s.Me(rec, req)
	if rec.Code != 200 {
		t.Fatal("expected the session to survive logout")
	}
}

بعد ​

همان سه endpoint با ترکیب بسته‌های این فصل ساخته می‌شوند: Argon2id در قالب PHC، یک پاسخ عمومی شکست که برای کاربران ناشناخته هم با همان هزینه محاسبه می‌شود، throttling جداگانهٔ حساب و IP با 429 و Retry-After، rotation نشست هنگام login، و cookie به نام __Host-sid با HttpOnly; Secure; SameSite=Lax. وقتی policy مربوط به cost تغییر کند، hash ذخیره‌شده ارتقا می‌یابد؛ logout هم session سمت سرور را حذف می‌کند. Routes عمداً هیچ لایهٔ CSRF نصب نمی‌کند تا تست‌ها دربارهٔ Authentication بمانند. Secure در آزمایش 6، همان سرور با لایهٔ CSRF و endpoint دریافت token است، مطابق pipeline.

go
// Package after is the same login done right, composed from this module's
// packages: Argon2id in PHC format, constant-time compare, a dummy hash for
// unknown users, one generic error, per-account and per-IP throttling,
// session rotation on login, a __Host- cookie with all flags, rehash on
// login, and a logout that ends the session on the server.
package after

import (
	"net/http"
	"strconv"
	"strings"
	"sync"
	"sync/atomic"

	"academy/authentication-in-go/lockout"
	"academy/authentication-in-go/password"
	"academy/authentication-in-go/session"
)

type User struct {
	ID    int64
	Email string
	Hash  string // $argon2id$v=19$...
}

type Server struct {
	Params   password.Params
	Sessions *session.Store
	Guard    *lockout.Guard

	mu      sync.Mutex
	byEmail map[string]*User
	dummy   string       // hash of a random password, same params as real ones
	Hashes  atomic.Int64 // number of Argon2id computations, for the test
}

func New(p password.Params, s *session.Store, g *lockout.Guard) *Server {
	dummy, _ := password.Hash(session.NewID(), p)
	return &Server{Params: p, Sessions: s, Guard: g, byEmail: map[string]*User{}, dummy: dummy}
}

func normEmail(e string) string { return strings.ToLower(strings.TrimSpace(e)) }

func (s *Server) Register(id int64, email, plain string) error {
	h, err := password.Hash(plain, s.Params)
	if err != nil {
		return err
	}
	s.mu.Lock()
	s.byEmail[normEmail(email)] = &User{ID: id, Email: normEmail(email), Hash: h}
	s.mu.Unlock()
	return nil
}

// generic is the single failure message, for unknown e-mail and wrong password.
const generic = "invalid email or password"

func clientIP(r *http.Request) string {
	host := r.RemoteAddr // behind a proxy, use the trusted real-IP middleware's value
	if i := strings.LastIndexByte(host, ':'); i > 0 {
		host = host[:i]
	}
	return host
}

func (s *Server) Login(w http.ResponseWriter, r *http.Request) {
	email := normEmail(r.PostFormValue("email"))
	plain := r.PostFormValue("password")
	if len(plain) > 1024 { // bound the hashing work an attacker can request
		http.Error(w, generic, http.StatusUnauthorized)
		return
	}
	if wait := s.Guard.Allow(email, clientIP(r)); wait > 0 {
		w.Header().Set("Retry-After", strconv.Itoa(int(wait.Seconds()+0.999)))
		http.Error(w, "too many attempts, try again later", http.StatusTooManyRequests)
		return
	}

	// Copy what we need under the lock: a concurrent login may be rewriting
	// u.Hash (rehash on login) at the same moment.
	s.mu.Lock()
	u := s.byEmail[email]
	encoded, userID := s.dummy, int64(0)
	if u != nil {
		encoded, userID = u.Hash, u.ID
	}
	s.mu.Unlock()
	ok, rehash, err := password.Verify(plain, encoded, s.Params) // same cost either way
	s.Hashes.Add(1)
	if err != nil || !ok || u == nil {
		s.Guard.Fail(email)
		http.Error(w, generic, http.StatusUnauthorized)
		return
	}
	s.Guard.Succeed(email)
	if rehash { // parameters were raised since this hash was made
		if h, err := password.Hash(plain, s.Params); err == nil {
			s.mu.Lock()
			if u.Hash == encoded { // nobody upgraded it meanwhile
				u.Hash = h
			}
			s.mu.Unlock()
		}
	}

	// Rotation on login: whatever ID the browser had is dropped.
	old := ""
	if c, err := r.Cookie(session.CookieName); err == nil {
		old = c.Value
	}
	id := s.Sessions.Rotate(old, userID)
	http.SetCookie(w, session.Cookie(id))
	w.Header().Set("Cache-Control", "no-store")
	w.WriteHeader(http.StatusNoContent)
}

// Logout deletes the server-side session and the cookie. It is POST only;
// in a real stack it sits behind csrf.Protector (and CrossOriginProtection)
// so another site cannot log the user out. Routes leaves CSRF out to keep
// these tests about authentication; the csrf package tests that layer.
func (s *Server) Logout(w http.ResponseWriter, r *http.Request) {
	if c, err := r.Cookie(session.CookieName); err == nil {
		s.Sessions.Destroy(c.Value)
	}
	http.SetCookie(w, session.ClearCookie())
	w.Header().Set("Clear-Site-Data", `"cache", "cookies", "storage"`)
	w.WriteHeader(http.StatusNoContent)
}

func (s *Server) Me(w http.ResponseWriter, r *http.Request) {
	sess, ok := session.From(r.Context())
	if !ok || sess.UserID == 0 {
		http.Error(w, "authentication required", http.StatusUnauthorized)
		return
	}
	w.Write([]byte(strconv.FormatInt(sess.UserID, 10)))
}

// Routes wires the handlers; session.Load runs on every request.
func (s *Server) Routes() http.Handler {
	mux := http.NewServeMux()
	mux.HandleFunc("POST /login", s.Login)
	mux.HandleFunc("POST /logout", s.Logout)
	mux.HandleFunc("GET /me", s.Me)
	return s.Sessions.Load(mux)
}

تست، ویژگی‌های امنیتی را assert می‌کند، نه فقط مسیر موفق را: پاسخ‌های کاملاً یکسان و تعداد محاسبات hash یکسان برای «چنین کاربری نیست» و «password غلط است»؛ session ID کاشته‌شده پیش از login که پس از آن دیگر کار نمی‌کند؛ ویژگی‌های دقیق cookie؛ rehash هنگام login؛ و throttling.

go
package after

import (
	"net/http"
	"net/http/httptest"
	"net/url"
	"strings"
	"testing"
	"time"

	"academy/authentication-in-go/lockout"
	"academy/authentication-in-go/password"
	"academy/authentication-in-go/session"
)

var fast = password.Params{Memory: 1024, Time: 1, Threads: 1, SaltLen: 16, KeyLen: 32}

func newServer(t *testing.T) (*Server, http.Handler) {
	t.Helper()
	s := New(fast, session.NewStore(30*time.Minute, 12*time.Hour), lockout.New())
	if err := s.Register(7, "alice@example.test", "correct horse battery staple"); err != nil {
		t.Fatal(err)
	}
	return s, s.Routes()
}

func post(h http.Handler, path, email, pw, ip string, c *http.Cookie) *httptest.ResponseRecorder {
	form := url.Values{"email": {email}, "password": {pw}}
	req := httptest.NewRequest("POST", path, strings.NewReader(form.Encode()))
	req.Header.Set("Content-Type", "application/x-www-form-urlencoded")
	req.RemoteAddr = ip + ":51000"
	if c != nil {
		req.AddCookie(c)
	}
	rec := httptest.NewRecorder()
	h.ServeHTTP(rec, req)
	return rec
}

func me(h http.Handler, c *http.Cookie) int {
	req := httptest.NewRequest("GET", "/me", nil)
	if c != nil {
		req.AddCookie(&http.Cookie{Name: c.Name, Value: c.Value})
	}
	rec := httptest.NewRecorder()
	h.ServeHTTP(rec, req)
	return rec.Code
}

func TestUnknownUserAndWrongPasswordLookTheSame(t *testing.T) {
	s, h := newServer(t)
	a := post(h, "/login", "nobody@example.test", "whatever", "192.0.2.1", nil)
	b := post(h, "/login", "alice@example.test", "wrong password", "192.0.2.1", nil)
	if a.Code != b.Code || a.Body.String() != b.Body.String() {
		t.Fatalf("distinguishable: %d %q vs %d %q", a.Code, a.Body, b.Code, b.Body)
	}
	if a.Code != http.StatusUnauthorized {
		t.Fatalf("code %d", a.Code)
	}
	if got := s.Hashes.Load(); got != 2 {
		t.Fatalf("%d hash computations, want 2 (dummy hash for the unknown user)", got)
	}
}

func TestLoginRotatesAndSetsFlags(t *testing.T) {
	s, h := newServer(t)
	planted := &http.Cookie{Name: session.CookieName, Value: s.Sessions.Create(0)}
	rec := post(h, "/login", "Alice@Example.test", "correct horse battery staple", "192.0.2.1", planted)
	if rec.Code != http.StatusNoContent {
		t.Fatalf("login %d %s", rec.Code, rec.Body)
	}
	raw := rec.Header().Get("Set-Cookie")
	if !strings.HasPrefix(raw, "__Host-sid=") || !strings.HasSuffix(raw, "; Path=/; HttpOnly; Secure; SameSite=Lax") {
		t.Fatalf("Set-Cookie %q", raw)
	}
	c := rec.Result().Cookies()[0]
	if c.Value == planted.Value {
		t.Fatal("session id not rotated")
	}
	if me(h, planted) != http.StatusUnauthorized {
		t.Fatal("planted pre-login id still works: fixation")
	}
	if me(h, c) != http.StatusOK {
		t.Fatal("new session rejected")
	}

	out := post(h, "/logout", "", "", "192.0.2.1", c)
	if !strings.Contains(out.Header().Get("Set-Cookie"), "Max-Age=0") {
		t.Fatalf("logout cookie %q", out.Header().Get("Set-Cookie"))
	}
	if me(h, c) != http.StatusUnauthorized {
		t.Fatal("session alive on the server after logout")
	}
}

func TestRehashOnLogin(t *testing.T) {
	s, h := newServer(t)
	before := s.byEmail["alice@example.test"].Hash
	s.Params.Time = 2 // policy raised the cost
	post(h, "/login", "alice@example.test", "correct horse battery staple", "192.0.2.1", nil)
	after := s.byEmail["alice@example.test"].Hash
	if after == before || !strings.Contains(after, ",t=2,") {
		t.Fatalf("hash not upgraded: %s", after)
	}
}

func TestThrottleReturns429(t *testing.T) {
	_, h := newServer(t)
	for range 6 {
		post(h, "/login", "alice@example.test", "guess", "192.0.2.1", nil)
	}
	rec := post(h, "/login", "alice@example.test", "correct horse battery staple", "198.51.100.9", nil)
	if rec.Code != http.StatusTooManyRequests || rec.Header().Get("Retry-After") == "" {
		t.Fatalf("code %d Retry-After %q", rec.Code, rec.Header().Get("Retry-After"))
	}
}

در حالی که loginهای دیگر hash ذخیره‌شده را می‌خوانند، یک login می‌تواند آن را ارتقا دهد. بنابراین handler، u.Hash و u.ID را زیر lock کپی می‌کند و فقط وقتی hash جدید را می‌نویسد که در این فاصله هیچ login دیگری آن را ارتقا نداده باشد. تست هم‌زمانی، 20 دور از 8 login هم‌زمان را زیر -race اجرا می‌کند.

go
package after

import (
	"fmt"
	"net/http"
	"sync"
	"testing"

	"academy/authentication-in-go/password"
)

// Concurrent successful logins while the stored hash is below policy: one
// of them rehashes and writes User.Hash while the others read it. Each
// round resets the hash to the old parameters. Run with -race.
func TestConcurrentLoginsDuringRehash(t *testing.T) {
	s, h := newServer(t)
	old, _ := password.Hash("correct horse battery staple", fast)
	s.Params.Time = 2
	for round := range 20 {
		s.mu.Lock()
		s.byEmail["alice@example.test"].Hash = old
		s.mu.Unlock()
		var wg sync.WaitGroup
		for i := range 8 {
			wg.Add(1)
			go func() {
				defer wg.Done()
				ip := fmt.Sprintf("198.51.%d.%d", round, i)
				if rec := post(h, "/login", "alice@example.test", "correct horse battery staple", ip, nil); rec.Code != http.StatusNoContent {
					t.Errorf("round %d login %d: %d", round, i, rec.Code)
				}
			}()
		}
		wg.Wait()
	}
}

نگاه Go ​

Go ابزارهای پایه را می‌دهد و ساخت framework را به شما می‌سپارد. کتابخانهٔ استاندارد همهٔ قطعه‌های مسیر session را دارد: crypto/rand، crypto/sha256، crypto/subtle، crypto/hmac، cookieهای net/http، context، html/template و از Go 1.25، http.CrossOriginProtection. Password hashing در golang.org/x/crypto است؛ تیم Go آن را نگه می‌دارد ولی جداگانه نسخه‌گذاری می‌شود. بقیه هرکدام بسته‌ای کوچک و متمرکزند: alexedwards/scs/v2 و gorilla/sessions برای session، golang-jwt/jwt/v5 برای JWT، MicahParks/keyfunc برای JWKS، golang.org/x/oauth2 و coreos/go-oidc/v3 برای OAuth و OpenID Connect، pquerna/otp برای TOTP، go-webauthn/webauthn برای passkey، و microcosm-cc/bluemonday برای HTML sanitizing. در Go معادلی از starter kitهای Laravel که این قطعه‌ها را به هم وصل کند وجود ندارد. این هم هزینه دارد (خودتان flow ورود را می‌نویسید) و هم فایده (می‌توانید هر خط را بخوانید و تست کنید، همان‌طور که این ماژول انجام می‌دهد).

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

هش گذرواژه: کند، با salt و در صورت نیاز pepper حیاتی ​

به زبان ساده: هش گذرواژه (Password hashing) یعنی خود password را نگه ندارید. خروجی تابعی را ذخیره کنید که یک بار اجرای آن هنگام login ارزان باشد، اما میلیاردها بار اجرای آن گران تمام شود. نمک تصادفی (Salt) باعث می‌شود password یکسان دو کاربر، خروجی متفاوت بدهد و جدول آماده بی‌فایده شود.

بدفهمی رایج: «رمزگذاری بهتر است چون password را پس می‌گیریم.» هر چیزی که شما با کلید decrypt کنید، مهاجم دارای آن کلید هم decrypt می‌کند. OWASP می‌گوید "should be securely hashed using modern, adaptive hashing algorithms (e.g., Argon2id, bcrypt, or PBKDF2), rather than encrypted or stored in plaintext." salt هم secret نیست؛ کنار hash ذخیره می‌شود تا یکتایی بدهد. بخش محرمانه pepper است.

تعریف: تابع Password hashing، password و salt و cost می‌گیرد و hash می‌دهد. NIST SP 800-63B-4 می‌گوید "Passwords SHALL be salted and hashed using a suitable password hashing scheme" و "The salt SHALL be at least 32 bits in length and chosen to minimize salt value collisions among stored hashes". ترتیب OWASP: ابتدا Argon2id، در نبود آن scrypt، و bcrypt "only ... in legacy systems where Argon2 and scrypt are not available"؛ برای الزام FIPS-140، PBKDF2 با 600,000 دور HMAC-SHA-256. Salts برای هر password تصادفی‌اند و در رشتهٔ hash می‌مانند. Peppers یک secret مشترک بیرون database هستند ("in 'secrets vaults' or HSMs")؛ پیش از hash اعمال می‌شوند (pre-hashing pepper) یا به‌صورت HMAC روی hash (post-hashing pepper). pepper در نشت صرفاً database مثل SQL injection یا backup دزدیده‌شده کمک می‌کند؛ هزینه‌اش این است که "changing a pepper will require forcing all users whose passwords were protected by the previous pepper to reset their passwords".

attacker with a stolen users table, one RTX-class GPU (orders of magnitude, not a benchmark)
1  sha256(pw), no salt     one hash per candidate covers ALL users; rainbow tables work
2  sha256(salt || pw)      one hash per candidate PER user; still ~10^9 guesses/s
3  bcrypt cost 12          ~175 ms per guess on one CPU core here: ~6 guesses/s/core
4  argon2id m=19MiB t=2    ~15 ms and 19 MiB per guess: memory, not cores, is the limit
5  + pepper in a vault     table alone is useless: the attacker also needs the vault

سناریوی واقعی: dump جدول users با SQL injection؛ backup در bucket عمومی؛ خط log که body درخواست حاوی password=... را چاپ کرده است (hash این‌جا کمکی نمی‌کند: هرگز فرم را log نکنید)؛ مهاجرت از schema قدیمی MD5؛ و دو کارمند با Summer2026! که نباید یکسان بودن passwordشان از hash آشکار شود.

روشبستهٔ Goحافظه‌بر (Memory-hard)سقف ورودیجایگاه در OWASP
Argon2idgolang.org/x/crypto/argon2 (IDKey)بلهعملاً نداردانتخاب اول
scryptgolang.org/x/crypto/scryptبلهندارددر نبود Argon2id
bcryptgolang.org/x/crypto/bcryptخیر؛ state در Blowfish شامل p [18]uint32 و چهار S-box از نوع [256]uint32، حدود 4 KiB72 بایتlegacy
PBKDF2crypto/pbkdf2 در Go 1.24 / x/crypto/pbkdf2خیرنداردFIPS-140، حداقل 600,000 دور
SHA-256، MD5، SHA-1crypto/sha256 و مشابهخیرنداردهرگز برای password

راه‌حل / کاربرد: برای سیستم تازه Argon2id، salt تصادفی 16 بایتی و پارامترهای ذخیره‌شده در رشته انتخاب کنید. pepper فقط وقتی ارزش دارد که واقعاً بیرون database نگهش دارید و بتوانید بچرخانیدش. APIهای SHA-2 و HMAC و crypto/rand در Hashing & Crypto آمده‌اند.

Argon2id با x/crypto/argon2 و قالب PHC حیاتی ​

به زبان ساده: Argon2id حافظه را با دادهٔ شبه‌تصادفی حاصل از password و salt پر می‌کند و سپس با ترتیبی وابسته به password می‌خواند. نیاز به حافظه (Memory hardness) مزیت GPU با هسته‌های فراوان و حافظهٔ کم برای هر هسته را محدود می‌کند.

بدفهمی رایج: «افزایش thread یا p یعنی شکستن سخت‌تر.» OWASP دربارهٔ parallelism می‌گوید "controls the number of lanes over which the memory is divided; increasing p does not multiply the total memory or act as an iteration count." بدفهمی دیگر: «مثال 2 GiB را از RFC کپی کنیم.» گزینهٔ FIRST RECOMMENDED در RFC 9106 با t=1، p=4 و m=2 GiB برای ماشینی اندازه‌گذاری شده که کار چندانی جز این ندارد؛ در سرور با 50 login هم‌زمان، 100 GiB حافظه لازم دارد. m را با توجه به concurrency انتخاب کنید.

تعریف: امضای API، argon2.IDKey(password, salt []byte, time, memory uint32, threads uint8, keyLen uint32) []byte است (memory بر حسب KiB). RFC 9106 بخش 4: "If much less memory is available, a uniformly safe option is Argon2id with t=3 iterations, p=4 lanes, m=2^(16) (64 MiB of RAM), 128-bit salt, and 256-bit tag size. This is the SECOND RECOMMENDED option." حداقل‌های OWASP حافظه و تعداد گذرها را با قدرت برابر مبادله می‌کنند: m=47104 t=1، m=19456 t=2، m=12288 t=3، m=9216 t=4 و m=7168 t=5، همگی با p=1. خروجی در قالب رشتهٔ PHC (PHC string format) ذخیره می‌شود که C2SP آن را $<id>[$v=<version>][$<param>=<value>(,<param>=<value>)*][$<salt>[$<hash>]] تعریف می‌کند؛ salt و hash در base64 استاندارد بدون padding هستند. comment مستند x/crypto میان نسخه‌ها تغییر کرده است: v0.48.0 که این‌جا pin شده به "RFC 9106 Section 7.3" ارجاع می‌دهد و time=1 و memory=64*1024 را "a sensible number" می‌نامد؛ master فعلی به دو پیشنهاد بخش 4 اشاره می‌کند. خانوادهٔ پارامترها یکی است؛ ماژول با v0.48.0 کامپایل می‌شود.

Hash("correct horse battery staple", OWASP)   (real output of this module)
1  salt   = 16 bytes from crypto/rand
2  key    = argon2.IDKey(pw, salt, t=2, m=19456, p=1, 32)
3  store  $argon2id$v=19$m=19456,t=2,p=1$P+oy00nASCUPp2mqAQNbNA$Cnca6pEujpk8B7AfAh9cB1VfEaQ0sJzEJhGJS++iYzA
Verify(pw, stored, OWASP)
4  parse  v=19 (argon2.Version = 0x13), m, t, p, salt, key
5  other  = argon2.IDKey(pw, salt, t, m, p, len(key))     parameters from the STRING, not from config
6  subtle.ConstantTimeCompare(key, other) == 1 ?
7  stored params != OWASP ? -> needsRehash = true
One stored string carries everything needed to verify it$argon2id$v=19$m=19456,t=2,p=1$P+oy00nASCUPp2mq…$Cnca6pEujpk8B7Af…algorithmversion 0x13KiB, passes, lanes16-byte salt, base6432-byte tag, base64POST /loginthrottle check first (429)look up user by emailmissing: use the dummy hashargon2.IDKey(pw, salt, t, m, p)same cost on both pathssubtle.ConstantTimeCompareand the user really existsno401 "invalid email or password"count a failure for this emailyesstored params != current?rehash now, while plaintext is knownrotate session IDSet-Cookie: __Host-sid=…No pepper or secret appears in the string: a pepper lives in a secret store and is applied before hashing.Params in the string let old and new hashes coexist; Verify reads them, needsRehash compares them with policy.

سناریوی واقعی: API ورود یک SaaS با ظرفیت 200 login در ثانیه برای هر instance؛ backend موبایلی که containerهایش 512 MiB حافظه دارند (m=19 MiB و t=2 در این حافظه جا می‌شود؛ 64 MiB با 50 login هم‌زمان جا نمی‌شود)؛ مهاجرتی که t را از 2 به 3 می‌رساند و با login کاربران hash را ارتقا می‌دهد؛ و KDF برای export رمزگذاری‌شده (مشتق‌سازی کلید با همان IDKey، ولی salt مخصوص خودش و بدون رشتهٔ PHC).

پروفایلmtpزمان hash در این اجراحافظهٔ hash
حداقل OWASP (password.OWASP)19456 KiB2115.5 ms19.9 MB
گزینهٔ دوم RFC 9106 (password.RFC9106Second)65536 KiB3426.9 ms67.1 MB
گزینهٔ اول RFC 91062097152 KiB14اجرا نشده؛ 2 GiB2 GiB
نمونهٔ مستند driver argon2id در Laravelmemory 1024time 2threads 2PHP؛ اندازه‌گیری نشدهمطابق گزینه‌های Hash::make

راه‌حل / کاربرد: بستهٔ password، hash و verify می‌کند، needsRehash برمی‌گرداند و رشتهٔ خراب یا نسخهٔ نامعتبر را رد می‌کند. تست‌ها برای سرعت -race از 1 MiB استفاده می‌کنند، همراه یک تست با پارامتر واقعی OWASP.

go
// Package password stores and verifies passwords: Argon2id in the PHC string
// format, a bcrypt fallback, an optional pepper, and a NIST SP 800-63B-4
// style policy.
package password

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

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

// Params are the Argon2id cost parameters. Memory is in KiB.
type Params struct {
	Memory  uint32 // m, KiB
	Time    uint32 // t, passes over memory
	Threads uint8  // p, lanes
	SaltLen uint32 // bytes
	KeyLen  uint32 // bytes (the "tag")
}

// OWASP is the OWASP Password Storage Cheat Sheet minimum m=19456 (19 MiB),
// t=2, p=1, with a 128-bit salt and a 256-bit tag as in RFC 9106.
var OWASP = Params{Memory: 19 * 1024, Time: 2, Threads: 1, SaltLen: 16, KeyLen: 32}

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

var (
	ErrInvalidHash         = errors.New("password: hash is not in the expected PHC format")
	ErrIncompatibleVersion = errors.New("password: incompatible argon2 version")
)

// Hash returns a PHC string such as
// $argon2id$v=19$m=19456,t=2,p=1$<salt>$<hash> (unpadded standard base64).
func Hash(plain string, p Params) (string, error) {
	salt := make([]byte, p.SaltLen)
	if _, err := rand.Read(salt); err != nil { // never fails since Go 1.24
		return "", err
	}
	key := argon2.IDKey([]byte(plain), 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 recomputes the hash with the parameters stored in encoded and
// compares in constant time. needsRehash is true when the stored parameters
// are weaker than (or just different from) want, so the caller can upgrade
// the hash right after a successful login, while it still has the plaintext.
func Verify(plain, encoded string, want Params) (ok, needsRehash bool, err error) {
	p, salt, key, err := decode(encoded)
	if err != nil {
		return false, false, err
	}
	other := argon2.IDKey([]byte(plain), salt, p.Time, p.Memory, p.Threads, uint32(len(key)))
	if subtle.ConstantTimeCompare(key, other) != 1 {
		return false, false, nil
	}
	needsRehash = p.Memory != want.Memory || p.Time != want.Time ||
		p.Threads != want.Threads || uint32(len(key)) != want.KeyLen ||
		uint32(len(salt)) != want.SaltLen
	return true, needsRehash, nil
}

func decode(encoded string) (p Params, salt, key []byte, err error) {
	// "", "argon2id", "v=19", "m=..,t=..,p=..", salt, hash
	parts := strings.Split(encoded, "$")
	if len(parts) != 6 || parts[0] != "" || parts[1] != "argon2id" {
		return p, nil, nil, ErrInvalidHash
	}
	var version int
	if _, err := fmt.Sscanf(parts[2], "v=%d", &version); err != nil {
		return p, nil, nil, ErrInvalidHash
	}
	if version != argon2.Version {
		return p, nil, nil, ErrIncompatibleVersion
	}
	if _, err := fmt.Sscanf(parts[3], "m=%d,t=%d,p=%d", &p.Memory, &p.Time, &p.Threads); err != nil {
		return p, nil, nil, ErrInvalidHash
	}
	b64 := base64.RawStdEncoding
	if salt, err = b64.DecodeString(parts[4]); err != nil {
		return p, nil, nil, ErrInvalidHash
	}
	if key, err = b64.DecodeString(parts[5]); err != nil {
		return p, nil, nil, ErrInvalidHash
	}
	if p.Memory == 0 || p.Time == 0 || p.Threads == 0 || len(key) < 16 {
		return p, nil, nil, ErrInvalidHash
	}
	p.SaltLen, p.KeyLen = uint32(len(salt)), uint32(len(key))
	return p, salt, key, nil
}

bcrypt با x/crypto/bcrypt: cost و سقف 72 بایت حیاتی ​

به زبان ساده: bcrypt یک hash تطبیقی (Adaptive hash) قدیمی‌تر است. هزینه (Cost) تعداد دورهای آماده‌سازی گران کلید را تعیین می‌کند و هر واحد افزایشش زمان را دوبرابر می‌کند. برای سیستم موجود قابل استفاده است، اما memory-hard نیست.

بدفهمی رایج: «bcrypt کل password را hash می‌کند.» پیاده‌سازی‌های کلاسیک بی‌صدا فقط 72 بایت اول را می‌گرفتند؛ پس دو passphrase بلند با 72 بایت نخست یکسان، تطبیق پیدا می‌کردند. x/crypto/bcrypt به‌جایش رد می‌کند: "GenerateFromPassword does not accept passwords longer than 72 bytes"، با خطای bcrypt: password length exceeds 72 bytes (bcrypt.ErrPasswordTooLong). بایت مهم است نه کاراکتر: 25 emoji برابر 100 بایت است. بدفهمی دیگر: «cost برابر 4 برای production کافی است چون تست پاس می‌شود.» bcrypt.MinCost برابر 4 برای تست وجود دارد.

تعریف: bcrypt.GenerateFromPassword(password []byte, cost int)؛ "If the cost given is less than MinCost, the cost will be set to DefaultCost" (10). MaxCost برابر 31 است؛ cost خارج محدوده، crypto/bcrypt: cost %d is outside allowed inclusive range 4..31 می‌دهد. CompareHashAndPassword مقدار nil یا bcrypt.ErrMismatchedHashAndPassword برمی‌گرداند؛ bcrypt.Cost(hash) هزینهٔ ذخیره‌شده را برای تصمیم rehash می‌خواند. رشته به‌شکل $2a$12$<22 chars salt><31 chars hash> و با الفبای base64 مخصوص bcrypt است، نه PHC. OWASP: "The work factor should be as large as verification server performance will allow, with a minimum of 10." اگر باید ورودی بلندتر بپذیرید، pre-hash امن پیشنهادی OWASP برابر bcrypt(base64(hmac-sha384(data:$password, key:$pepper)), $salt, $cost) است؛ digest خام می‌تواند NUL داشته باشد و pre-hash بدون کلید راه "password shucking" را باز می‌کند.

cost   rounds 2^cost   time per hash on this machine
10     1024            ~44 ms   (DefaultCost; extrapolated: cost 12 / 4)
12     4096            176 ms   (measured, BenchmarkBcryptCost12)
14     16384           ~0.7 s   (too slow for an interactive login)

سناریوی واقعی: مهاجرت Laravel با hashهای $2y$12$... به Go که x/crypto آن‌ها را می‌خواند؛ دریافت ErrPasswordTooLong برای passphrase صدکاراکتری؛ افزایش cost از 10 به 12 و rehash هنگام login؛ الزام FIPS که PBKDF2 می‌خواهد.

وضعیتاقدام
سیستم تازهArgon2id
hashهای bcrypt موجودverify را نگه دارید؛ پس از login موفق به Argon2id ارتقا دهید
password بلندتر از 72 بایترد طبق policy یا pre-hash با pepper + HMAC-SHA-384 + base64
cost پایین‌تر از policybcrypt.Cost کمتر از هدف: rehash بعد از login موفق
تست کندفقط در تست bcrypt.MinCost

راه‌حل / کاربرد: wrapper، ورودی بلند را رد می‌کند و needsRehash می‌دهد. Peppered همان pre-hash OWASP با 64 کاراکتر base64 است و در سقف bcrypt جا می‌شود.

go
package password

import (
	"errors"

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

// BcryptCost is above bcrypt.DefaultCost (10), the OWASP minimum, and equal
// to the rounds value used in Laravel's hashing docs.
const BcryptCost = 12

// HashBcrypt refuses passwords longer than 72 bytes instead of silently
// truncating them; x/crypto returns bcrypt.ErrPasswordTooLong for those.
func HashBcrypt(plain string) (string, error) {
	h, err := bcrypt.GenerateFromPassword([]byte(plain), BcryptCost)
	if err != nil {
		return "", err
	}
	return string(h), nil
}

// VerifyBcrypt reports a match and whether the stored cost is below the
// current one. A mismatch is not an error.
func VerifyBcrypt(plain, hashed string) (ok, needsRehash bool, err error) {
	err = bcrypt.CompareHashAndPassword([]byte(hashed), []byte(plain))
	if errors.Is(err, bcrypt.ErrMismatchedHashAndPassword) {
		return false, false, nil
	}
	if err != nil {
		return false, false, err
	}
	cost, err := bcrypt.Cost([]byte(hashed))
	if err != nil {
		return false, false, err
	}
	return true, cost < BcryptCost, nil
}
go
package password

import (
	"crypto/hmac"
	"crypto/sha512"
	"encoding/base64"
)

// Peppered returns base64(HMAC-SHA-384(pepper, plain)), the pre-hash OWASP
// gives for bcrypt: base64 avoids NUL bytes, and 64 base64 characters fit in
// bcrypt's 72-byte limit. The pepper lives in a secret store, never in the
// database next to the hashes. Feed the result to Hash or HashBcrypt.
func Peppered(plain string, pepper []byte) string {
	m := hmac.New(sha512.New384, pepper)
	m.Write([]byte(plain))
	return base64.StdEncoding.EncodeToString(m.Sum(nil))
}

مقایسهٔ زمان‌ثابت و حمله‌های زمانی حیاتی ​

به زبان ساده: اگر هرچه حدس غلط‌تر باشد پاسخ سریع‌تر بیاید، مهاجم با ساعت اطلاعات می‌گیرد. مقایسهٔ زمان‌ثابت (Constant-time compare) به محل نخستین اختلاف وابسته نیست. مسیر «کاربر نیست» هم باید به‌اندازهٔ «password غلط» هزینه داشته باشد.

بدفهمی رایج: «مقایسهٔ hashها با == امن است چون مهاجم hash را کنترل نمی‌کند.» برای password hash عمدتاً درست است، چون مهاجم نمی‌تواند خروجی Argon2 را بایت‌به‌بایت هدایت کند؛ اما همین کد برای مقایسهٔ API key، امضای HMAC، CSRF token و reset token کپی می‌شود و آن‌جا دیگر درست نیست. نشت زمانی بزرگ‌تر و عملی‌تر، خروج سریع (Quick exit) است: وقتی کاربر وجود ندارد، پیش از hash برمی‌گردید. مثال دقیق OWASP: "if the user doesn't exist, the application will directly throw an error. Otherwise, when the user exists and the password doesn't, it is apparent that there will be more processing".

تعریف: مستند subtle.ConstantTimeCompare(x, y []byte) int می‌گوید: "returns 1 if the two slices, x and y, have equal contents and 0 otherwise. The time taken is a function of the length of the slices and is independent of the contents. If the lengths of x and y do not match it returns 0 immediately." یعنی محتوا زمان را تغییر نمی‌دهد، ولی طول متفاوت فوراً 0 می‌دهد. hmac.Equal همین تابع را برای MAC می‌پوشاند. حملهٔ زمانی (Timing attack) با اندازه‌گیری زمان پاسخ درخواست‌های فراوان، secret یا واقعیتی مثل وجود حساب را کشف می‌کند. برای نشت lookup کاربر، یک hash ساختگی (Dummy hash) ثابت داشته باشید: در نبود کاربر هم همان Argon2id را با همان پارامترها در برابر آن محاسبه کنید و با همان پیام شکست بدهید.

     quick exit (before)                      dummy hash (after)
1    lookup alice: found  -> hash ~15 ms      lookup alice: found  -> hash ~15 ms
2    lookup nobody: missing -> 404 in 0.1 ms  lookup nobody: missing -> hash dummy ~15 ms
3    attacker: 0.1 ms means "no account"      attacker: same time, same 401, same body
4    enumerates the customer list             learns nothing; throttling limits the rest

سناریوی واقعی: برنامهٔ B2B که فهمیدن وجود حساب cfo@victim.example اولین قدم یک کارزار phishing است؛ بررسی API key با if key == cfg.Key؛ بررسی امضای webhook با bytes.Equal؛ endpoint بازیابی که «ایمیل ارسال شد» را در 900 ms به‌خاطر SMTP ولی «ناشناس» را در 5 ms پاسخ می‌دهد.

مقایسهزمان‌ثابت؟کاربرد
a == b روی string، bytes.Equalخیر؛ توقف در اولین اختلافدادهٔ غیرمحرمانه
subtle.ConstantTimeCompareبرای طول برابر بله؛ طول نشت می‌کندtoken، key، خروجی hash
hmac.Equalبله، همان تابعMAC، signed cookie، CSRF token
bcrypt.CompareHashAndPasswordداخلش subtle داردhash bcrypt
جست‌وجوی sha256(token) در map یا indexکلید lookup، hash secret است نه خود آنreset، refresh، session token

راه‌حل / کاربرد: password.Verify با subtle.ConstantTimeCompare تمام می‌شود؛ after.Login برای ناشناس dummy را hash می‌کند و تست دقیقاً دو محاسبهٔ hash برای دو login شکست‌خورده را assert می‌کند. API عمومی HMAC و مقایسهٔ زمان‌ثابت در Hashing & Crypto آمده است.

سیاست گذرواژه: NIST SP 800-63B-4 مهم ​

به زبان ساده: طول بر پیچیدگی می‌چربد. در سیاست گذرواژه (Password policy)، طول را الزامی و password را با فهرست رایج و افشاشده مقایسه کنید؛ هر کاراکتر قابل چاپ، از جمله فاصله و emoji، را بپذیرید. کاربران را مجبور نکنید هر 90 روز password را عوض کنند.

بدفهمی رایج: «یک حرف بزرگ، یک عدد و یک نماد password را قوی می‌کند.» NIST می‌گوید "Verifiers and CSPs SHALL NOT impose other composition rules (e.g., requiring mixtures of different character types) for passwords"، چون کاربر در جواب، password را Password1! می‌کند. بدفهمی دوم: «سقف 16 کاراکتر معقول است.» متن NIST: "Verifiers and CSPs SHOULD permit a maximum password length of at least 64 characters." سقف را بالا بگذارید؛ هدف سقف فقط محدود کردن کار hashing است.

تعریف: NIST SP 800-63B-4 بخش 3.1.1.2 در ۲۰۲۵: "Verifiers and CSPs SHALL require passwords that are used as a single-factor authentication mechanism to be a minimum of 15 characters in length. Verifiers and CSPs MAY allow passwords that are only used as part of multi-factor authentication processes to be shorter but SHALL require them to be a minimum of eight characters in length." بنابراین حداقل تک‌عامل 15 و حداقل passwordی که فقط همراه MFA مصرف می‌شود 8 است. password پیشنهادی باید مقایسه شود "against a blocklist that contains known commonly used, expected, or compromised passwords". دربارهٔ تغییر دوره‌ای: "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." طول بر حسب کاراکتر است: "Each Unicode code point SHALL be counted as a single character when evaluating password length". همچنین verifier باید طبق توصیهٔ SHOULD پیش از hash، NFC normalization اعمال کند؛ در Go به golang.org/x/text/unicode/norm نیاز دارد (در این ماژول استفاده نشده است).

Policy{MinRunes: 15, MaxRunes: 128, Blocklist: {...}}.Check(...)   (package password tests)
1  "Tr0ub4dor&3"                     -> too short (11): symbols do not help
2  "correct horse battery staple"    -> ok: long, lowercase, spaces
3  "PasswordPassword"                -> blocklisted (case-insensitive)
4  15 x "ŝ" (30 bytes)                -> ok: counts runes, not bytes
5  129 x "a"                          -> too long: bounds hashing work

سناریوی واقعی: فرم ثبت‌نامی که passphrase دارای فاصله را رد می‌کرد؛ کنسول admin با تعویض اجباری هر 90 روز که Winter2026! و Spring2026! تولید می‌کرد؛ بررسی password افشاشده در برابر فهرست 100,000 مورد نخست، هم هنگام ثبت‌نام و هم هر تغییر password؛ حداقل 15 کاراکتر برای برنامهٔ مشتری بدون MFA و 8 برای کارکنانی که باید TOTP داشته باشند.

قانونNIST SP 800-63B-4قاعدهٔ legacy رایج
حداقل طول15 تک‌عامل، 8 همراه MFA8
حداکثر طولپذیرش دست‌کم 6416 یا 20
ترکیب حرف بزرگ/عدد/نمادنباید تحمیل شوداجباری
تعویض دوره‌اینباید؛ فقط در compromise اجباریهر 90 روز
blocklist رایج/افشاشدهباید بررسی شودکم‌یاب
راهنما و سؤال امنیتیknowledge-based authentication نباید درخواست شودرایج
محدودسازی (Throttling)حداکثر 100 شکست متوالی برای حساباغلب ندارد

راه‌حل / کاربرد: Policy در بستهٔ password حدود ده خط است، چون قواعد ساده‌اند. نگه‌داری blocklist کار مستمر می‌خواهد.

go
package password

import (
	"errors"
	"strings"
	"unicode/utf8"
)

var (
	ErrTooShort    = errors.New("password: too short")
	ErrTooLong     = errors.New("password: too long")
	ErrBlocklisted = errors.New("password: appears in a list of common or breached passwords")
)

// Policy follows NIST SP 800-63B-4 section 3.1.1.2: a length minimum (15 for
// single-factor, 8 when the password is only one factor of MFA), at least 64
// characters allowed, a blocklist, and no composition rules or forced
// periodic changes.
type Policy struct {
	MinRunes  int                 // 15, or 8 when MFA is enforced
	MaxRunes  int                 // >= 64; caps hashing work per request
	Blocklist map[string]struct{} // lower-cased common/breached passwords
}

// Check counts Unicode characters, not bytes, and deliberately has no
// "one digit, one symbol" rule.
func (p Policy) Check(plain string) error {
	n := utf8.RuneCountInString(plain)
	switch {
	case n < p.MinRunes:
		return ErrTooShort
	case n > p.MaxRunes:
		return ErrTooLong
	}
	if _, bad := p.Blocklist[strings.ToLower(plain)]; bad {
		return ErrBlocklisted
	}
	return nil
}
go
package password

import (
	"errors"
	"strings"
	"testing"

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

// fast keeps -race runs quick; one test below uses the real OWASP params.
var fast = Params{Memory: 1024, Time: 1, Threads: 1, SaltLen: 16, KeyLen: 32}

func TestHashVerifyRoundTrip(t *testing.T) {
	h, err := Hash("correct horse battery staple", fast)
	if err != nil {
		t.Fatal(err)
	}
	if !strings.HasPrefix(h, "$argon2id$v=19$m=1024,t=1,p=1$") {
		t.Fatalf("not a PHC string: %s", h)
	}
	ok, rehash, err := Verify("correct horse battery staple", h, fast)
	if err != nil || !ok || rehash {
		t.Fatalf("ok=%v rehash=%v err=%v", ok, rehash, err)
	}
	ok, _, err = Verify("Correct horse battery staple", h, fast)
	if err != nil || ok {
		t.Fatalf("wrong password accepted: ok=%v err=%v", ok, err)
	}
}

func TestSaltMakesEqualPasswordsDiffer(t *testing.T) {
	a, _ := Hash("same password for two users", fast)
	b, _ := Hash("same password for two users", fast)
	if a == b {
		t.Fatal("two hashes of the same password are equal: salt missing")
	}
}

func TestNeedsRehashWhenParamsChange(t *testing.T) {
	h, _ := Hash("upgrade me on next login", fast)
	stronger := fast
	stronger.Time = 2
	ok, rehash, err := Verify("upgrade me on next login", h, stronger)
	if err != nil || !ok || !rehash {
		t.Fatalf("ok=%v rehash=%v err=%v", ok, rehash, err)
	}
}

func TestOWASPParams(t *testing.T) {
	h, err := Hash("production parameters once", OWASP)
	if err != nil {
		t.Fatal(err)
	}
	if !strings.Contains(h, "$m=19456,t=2,p=1$") {
		t.Fatalf("unexpected params in %s", h)
	}
	if ok, _, _ := Verify("production parameters once", h, OWASP); !ok {
		t.Fatal("verify failed")
	}
}

func TestDecodeRejectsGarbage(t *testing.T) {
	for _, s := range []string{
		"",
		"plaintext",
		"$argon2i$v=19$m=1024,t=1,p=1$c2FsdA$aGFzaA",
		"$argon2id$v=16$m=1024,t=1,p=1$c2FsdHNhbHRzYWx0$aGFzaGhhc2hoYXNoaGFzaA",
		"$argon2id$v=19$m=0,t=1,p=1$c2FsdHNhbHRzYWx0$aGFzaGhhc2hoYXNoaGFzaA",
	} {
		if _, _, err := Verify("x", s, fast); err == nil {
			t.Errorf("accepted %q", s)
		}
	}
}

func TestBcryptLimitAndCost(t *testing.T) {
	if _, err := HashBcrypt(strings.Repeat("a", 73)); !errors.Is(err, bcrypt.ErrPasswordTooLong) {
		t.Fatalf("73 bytes: err = %v, want ErrPasswordTooLong", err)
	}
	old, _ := bcrypt.GenerateFromPassword([]byte("legacy password"), bcrypt.MinCost)
	ok, rehash, err := VerifyBcrypt("legacy password", string(old))
	if err != nil || !ok || !rehash {
		t.Fatalf("ok=%v rehash=%v err=%v", ok, rehash, err)
	}
	ok, _, err = VerifyBcrypt("wrong", string(old))
	if err != nil || ok {
		t.Fatalf("mismatch: ok=%v err=%v", ok, err)
	}
}

func TestPepperFitsBcrypt(t *testing.T) {
	long := strings.Repeat("päss", 40) // 200 bytes
	p := Peppered(long, []byte("pepper-from-a-secret-store-32-by"))
	if len(p) != 64 {
		t.Fatalf("len = %d, want 64", len(p))
	}
	if _, err := HashBcrypt(p); err != nil {
		t.Fatal(err)
	}
	if Peppered(long, []byte("another pepper")) == p {
		t.Fatal("pepper has no effect")
	}
}

func TestPolicy(t *testing.T) {
	p := Policy{MinRunes: 15, MaxRunes: 128, Blocklist: map[string]struct{}{"passwordpassword": {}}}
	cases := map[string]error{
		"Tr0ub4dor&3":                  ErrTooShort, // 11 chars, composition does not help
		"correct horse battery staple": nil,         // long, no digits or symbols: fine
		"PasswordPassword":             ErrBlocklisted,
		"ŝŝŝŝŝŝŝŝŝŝŝŝŝŝŝ":              nil, // 15 runes, 30 bytes
		strings.Repeat("a", 129):       ErrTooLong,
	}
	for in, want := range cases {
		if got := p.Check(in); !errors.Is(got, want) {
			t.Errorf("Check(%q) = %v, want %v", in, got, want)
		}
	}
}

func BenchmarkArgon2idOWASP(b *testing.B) {
	for b.Loop() {
		_, _ = Hash("benchmark password", OWASP)
	}
}

func BenchmarkBcryptCost12(b *testing.B) {
	for b.Loop() {
		_, _ = HashBcrypt("benchmark password")
	}
}

func BenchmarkArgon2idRFC9106Second(b *testing.B) {
	for b.Loop() {
		_, _ = Hash("benchmark password", RFC9106Second)
	}
}

Session: ذخیرهٔ سرور، entropy، cookie flags، rotation و timeout حیاتی ​

به زبان ساده: پس از login موفق، سرور رکوردی برای نشست (Session) می‌سازد: «این کاربر 7 است، در 09:00 وارد شده و آخرین بار 09:12 دیده شده». سپس شمارهٔ بلند و تصادفیِ اشاره‌کننده به آن رکورد را به مرورگر می‌دهد. هر درخواست آن شماره را در cookie پس می‌فرستد و سرور lookup می‌کند. شماره کلید حساب است؛ باید غیرقابل حدس، از دید JavaScript پنهان، فقط قابل ارسال روی HTTPS، هنگام login جایگزین‌شونده و پس از بی‌فعالیتی فراموش‌شونده باشد.

بدفهمی رایج: «حفظ همان session ID از سبد ناشناس تا حالت واردشده راحت است.» این تثبیت نشست (Session fixation) است: مهاجمی که یک ID در مرورگر قربانی کاشته (با لینک، زیردامنهٔ همسایه یا kiosk مشترک)، همان لحظهٔ login قربانی با هویت او وارد است. OWASP: "The session ID must be renewed or regenerated by the web application after any privilege level change". بدفهمی دوم: «ID تصادفی است، پس نگه‌داشتنش به‌عنوان primary key مشکلی ندارد.» هرکس store را بخواند، از replica یا backup یا debug dump، می‌تواند sessionهای زنده را دوباره مصرف کند؛ به‌جای ID خام، hash آن را نگه دارید.

تعریف: مخزن سمت سرور (Server-side store) دادهٔ session را نگه می‌دارد؛ Redis، جدول SQL یا حافظه برای یک instance. کلاینت فقط شناسه دارد. OWASP: "Session identifiers must have at least 64 bits of entropy" و "A strong CSPRNG (Cryptographically Secure Pseudorandom Number Generator) must be used". این ماژول 32 بایت از crypto/rand، یعنی 256 بیت، را با base64url کد می‌کند. ویژگی‌های cookie (Cookie flags): HttpOnly طبق مستند "Forbids JavaScript from accessing the cookie"؛ Secure ارسال را به https: محدود می‌کند (جز localhost). SameSite=Lax cookie را در ناوبری سطح بالا با method امن می‌فرستد ولی در POST و fetch و subresource میان‌سایتی نه؛ SameSite=Strict هرگز cross-site نمی‌فرستد؛ None به Secure نیاز دارد. پیشوند __Host- مرورگر را وادار می‌کند cookie فاقد Secure، Path=/ یا دارای Domain را رد کند؛ پس زیردامنه نمی‌تواند آن را overwrite کند (توصیهٔ OWASP: "Recommended for session IDs"). چرخش هنگام ورود (Rotation on login) ID تازه صادر و رکورد قبلی را حذف می‌کند. دو timeout روی سرور اعمال می‌شوند: idle برای بی‌فعالیتی و absolute برای کل عمر. OWASP: "Common idle timeouts ranges are 2-5 minutes for high-value applications and 15-30 minutes for low risk applications"؛ برای روز کامل اداری، absolute برابر "between 4 and 8 hours". در NIST SP 800-63B-4، AAL2 برای reauthentication کلی "no more than 24 hours" و بی‌فعالیتی "no more than 1 hour" دارد؛ در AAL3 این دو 12 ساعت و 15 دقیقه‌اند.

     browser                          Go server                          store (key = sha256(id))
1    GET /cart (no cookie)  ───────▶  Create(0): id=Ab3..(256 bit) ───▶  9f2c..: {user 0, created 09:00}
2    ◀── Set-Cookie: __Host-sid=Ab3..; Path=/; HttpOnly; Secure; SameSite=Lax
3    POST /login (cookie Ab3..) ───▶  password ok; Rotate(Ab3.., 7) ──▶  delete 9f2c..; 51d0..: {user 7}
4    ◀── Set-Cookie: __Host-sid=Qz8..  (Ab3.. is now worthless: no fixation)
5    GET /orders (Qz8..) 09:40 ─────▶ Get: idle 28 min < 30, age 40 min < 12 h ─▶ LastSeen = 09:40
6    GET /orders (Qz8..) 10:15 ─────▶ Get: idle 35 min > 30 ─▶ delete; 401, redirect to /login
Session: state on the server. JWT: state in the token.Server-side sessionBrowserCookie: __Host-sidGo serversha256(id), timeoutsSession storeRedis / SQL rowuser 7roles, timestamps+ logout, password reset, ban: delete the row, effective on the next request- one store lookup per request; the store must be shared by every instance; CSRF defence neededJWT access tokenClient / SPA / serviceAuthorization: BearerAPI (resource server)alg allow-list, exp/iss/audJWKS cachepublic key by kidAuth serversigns, rotates keysGET /.well-known/jwks.jsonA valid signature stays valid until exp: logout cannot reach a token already handed out+ no lookup per request; any service with the public key can verify; no cookie, so no CSRF for bearer calls- revocation means a 5-15 min access TTL, a jti denylist, and refresh token rotation at the auth server

سناریوی واقعی: بانک آنلاین با idle برابر 5 دقیقه و absolute برابر 4 ساعت؛ رایانهٔ مشترک کتابخانه که نفر بعد یک ساعت بعد مرورگر را باز می‌کند؛ سبد فروشگاه که در checkout به سبد واردشده تبدیل می‌شود (ID را rotate کنید ولی دادهٔ سبد را کپی کنید)؛ adminی که وسط session یک role تازه می‌گیرد (rotation لازم است)؛ failover در Redis که sessionها را از دست می‌دهد (کاربر دوباره login می‌کند، ولی چیزی نشت نمی‌کند).

ویژگیقاعدهاین ماژولپیش‌فرض alexedwards/scs/v2
entropy شناسهحداقل 64 بیت CSPRNG256 بیت، crypto/rand256 بیت؛ 32 بایت rand.Read و base64url
محتوای storeverifier، نه ID خامsha256(id)token خام مگر HashTokenInStore = true
HttpOnlyهمیشهبلهtrue
Secureهمیشه، HTTPSبلهfalse؛ تنظیم کنید
SameSiteLax یا StrictLaxLax
نامپیشوند __Host-__Host-sidsession
rotationlogin، logout، تغییر دسترسیStore.RotateRenewToken(ctx)
idle timeout15-30 min؛ حساس 2-5Store.IdleIdleTimeout؛ 0 یعنی ندارد
absolute timeout4-12 hStore.AbsoluteLifetime، 24 h
logoutحذف رکورد سرورStore.DestroyDestroy(ctx)
همهٔ sessionهای کاربرreset و خروج همه‌جاStore.DestroyUserپیمایش store با Iterate

راه‌حل / کاربرد: بستهٔ session این الگو را با حدود 150 خط stdlib پیاده می‌کند. Load، middleware اتصال session به context است.

go
// Package session is a server-side session store written with the standard
// library only: 256-bit random IDs from crypto/rand, only a SHA-256 of the
// ID kept in the store, idle and absolute timeouts, rotation on login and
// privilege change, and a __Host- cookie with HttpOnly, Secure and SameSite.
package session

import (
	"context"
	"crypto/rand"
	"crypto/sha256"
	"encoding/base64"
	"encoding/hex"
	"errors"
	"net/http"
	"sync"
	"time"
)

// CookieName uses the __Host- prefix: the browser only accepts it with
// Secure, Path=/ and no Domain, so a sibling subdomain cannot plant it.
const CookieName = "__Host-sid"

var ErrNotFound = errors.New("session: not found or expired")

// Session is the server-side record. The raw ID never appears in it.
type Session struct {
	UserID    int64
	CreatedAt time.Time // start of the absolute timeout
	LastSeen  time.Time // start of the idle timeout
}

// Store is a stand-in for Redis or a SQL table keyed by sha256(ID).
type Store struct {
	mu       sync.Mutex
	byKey    map[string]Session
	Idle     time.Duration // e.g. 30 * time.Minute
	Absolute time.Duration // e.g. 12 * time.Hour
	Now      func() time.Time
}

func NewStore(idle, absolute time.Duration) *Store {
	return &Store{byKey: map[string]Session{}, Idle: idle, Absolute: absolute, Now: time.Now}
}

// NewID returns 32 random bytes as unpadded base64url: 256 bits, four times
// the OWASP minimum of 64 bits of entropy.
func NewID() string {
	b := make([]byte, 32)
	rand.Read(b) // documented never to return an error since Go 1.24
	return base64.RawURLEncoding.EncodeToString(b)
}

// key is what the store sees: a read-only leak of the store (a backup, a
// replica, a debug dump) does not hand out live session IDs.
func key(id string) string {
	sum := sha256.Sum256([]byte(id))
	return hex.EncodeToString(sum[:])
}

// Create starts a session for userID and returns the raw ID for the cookie.
func (s *Store) Create(userID int64) string {
	id := NewID()
	now := s.Now()
	s.mu.Lock()
	s.byKey[key(id)] = Session{UserID: userID, CreatedAt: now, LastSeen: now}
	s.mu.Unlock()
	return id
}

// Get enforces both timeouts and slides the idle one.
func (s *Store) Get(id string) (Session, error) {
	now := s.Now()
	s.mu.Lock()
	defer s.mu.Unlock()
	k := key(id)
	sess, ok := s.byKey[k]
	if !ok {
		return Session{}, ErrNotFound
	}
	if now.Sub(sess.LastSeen) > s.Idle || now.Sub(sess.CreatedAt) > s.Absolute {
		delete(s.byKey, k)
		return Session{}, ErrNotFound
	}
	sess.LastSeen = now
	s.byKey[k] = sess
	return sess, nil
}

// Rotate issues a new ID for the same session data and deletes the old one.
// Call it on login (session fixation), on logout-to-anonymous, on password
// change and on any privilege change.
func (s *Store) Rotate(oldID string, userID int64) string {
	s.mu.Lock()
	delete(s.byKey, key(oldID))
	s.mu.Unlock()
	return s.Create(userID)
}

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

// DestroyUser removes every session of a user (password reset, "log out
// everywhere", account disabled). Returns how many were removed.
func (s *Store) DestroyUser(userID int64) int {
	s.mu.Lock()
	defer s.mu.Unlock()
	n := 0
	for k, v := range s.byKey {
		if v.UserID == userID {
			delete(s.byKey, k)
			n++
		}
	}
	return n
}

// Cookie builds the session cookie. No Expires/MaxAge: a browser-session
// cookie; the server-side timeouts are the real limit.
func Cookie(id string) *http.Cookie {
	return &http.Cookie{
		Name:     CookieName,
		Value:    id,
		Path:     "/",
		HttpOnly: true,                 // no document.cookie access
		Secure:   true,                 // HTTPS only; required by __Host-
		SameSite: http.SameSiteLaxMode, // not sent on cross-site POST
	}
}

// ClearCookie tells the browser to delete the cookie (MaxAge < 0 is
// serialised as Max-Age=0).
func ClearCookie() *http.Cookie {
	c := Cookie("")
	c.MaxAge = -1
	return c
}

type ctxKey struct{}

// Load is middleware: it attaches the session (if any) to the request context.
// It never rejects; RequireUser in package authmw does that.
func (s *Store) Load(next http.Handler) http.Handler {
	return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
		if c, err := r.Cookie(CookieName); err == nil {
			if sess, err := s.Get(c.Value); err == nil {
				r = r.WithContext(context.WithValue(r.Context(), ctxKey{}, sess))
			}
		}
		next.ServeHTTP(w, r)
	})
}

// From returns the session loaded by Load.
func From(ctx context.Context) (Session, bool) {
	sess, ok := ctx.Value(ctxKey{}).(Session)
	return sess, ok
}
go
package session

import (
	"encoding/base64"
	"errors"
	"net/http"
	"net/http/httptest"
	"strings"
	"testing"
	"time"
)

type clock struct{ t time.Time }

func (c *clock) now() time.Time      { return c.t }
func (c *clock) add(d time.Duration) { c.t = c.t.Add(d) }
func newTestStore() (*Store, *clock) {
	c := &clock{t: time.Date(2026, 11, 28, 9, 0, 0, 0, time.UTC)}
	s := NewStore(30*time.Minute, 12*time.Hour)
	s.Now = c.now
	return s, c
}

func TestIDEntropyAndUniqueness(t *testing.T) {
	seen := map[string]bool{}
	for range 1000 {
		id := NewID()
		raw, err := base64.RawURLEncoding.DecodeString(id)
		if err != nil || len(raw) != 32 {
			t.Fatalf("id %q: %d bytes, err %v", id, len(raw), err)
		}
		if seen[id] {
			t.Fatal("duplicate id")
		}
		seen[id] = true
	}
}

func TestStoreKeepsOnlyHash(t *testing.T) {
	s, _ := newTestStore()
	id := s.Create(7)
	for k := range s.byKey {
		if strings.Contains(k, id) {
			t.Fatal("raw id stored")
		}
	}
}

func TestIdleTimeout(t *testing.T) {
	s, c := newTestStore()
	id := s.Create(7)
	c.add(29 * time.Minute)
	if _, err := s.Get(id); err != nil {
		t.Fatalf("active session rejected: %v", err)
	}
	c.add(31 * time.Minute) // 31 min since last activity
	if _, err := s.Get(id); !errors.Is(err, ErrNotFound) {
		t.Fatalf("idle session accepted: %v", err)
	}
}

func TestAbsoluteTimeout(t *testing.T) {
	s, c := newTestStore()
	id := s.Create(7)
	for range 25 { // active every 29 minutes for ~12 hours
		c.add(29 * time.Minute)
		if _, err := s.Get(id); err != nil {
			if c.t.Sub(time.Date(2026, 11, 28, 9, 0, 0, 0, time.UTC)) <= 12*time.Hour {
				t.Fatalf("rejected before absolute timeout: %v", err)
			}
			return
		}
	}
	t.Fatal("session survived the absolute timeout")
}

func TestRotateInvalidatesOldID(t *testing.T) {
	s, _ := newTestStore()
	anon := s.Create(0)
	authed := s.Rotate(anon, 7)
	if anon == authed {
		t.Fatal("rotation kept the id")
	}
	if _, err := s.Get(anon); !errors.Is(err, ErrNotFound) {
		t.Fatal("pre-login id still valid: session fixation possible")
	}
	if sess, err := s.Get(authed); err != nil || sess.UserID != 7 {
		t.Fatalf("new id: %+v %v", sess, err)
	}
}

func TestDestroyUser(t *testing.T) {
	s, _ := newTestStore()
	a, b := s.Create(7), s.Create(7)
	other := s.Create(8)
	if n := s.DestroyUser(7); n != 2 {
		t.Fatalf("removed %d", n)
	}
	for _, id := range []string{a, b} {
		if _, err := s.Get(id); err == nil {
			t.Fatal("session survived DestroyUser")
		}
	}
	if _, err := s.Get(other); err != nil {
		t.Fatal("other user's session removed")
	}
}

func TestCookieFlags(t *testing.T) {
	rec := httptest.NewRecorder()
	http.SetCookie(rec, Cookie("abc"))
	got := rec.Header().Get("Set-Cookie")
	want := "__Host-sid=abc; Path=/; HttpOnly; Secure; SameSite=Lax"
	if got != want {
		t.Fatalf("Set-Cookie = %q\nwant         %q", got, want)
	}
	rec = httptest.NewRecorder()
	http.SetCookie(rec, ClearCookie())
	if got := rec.Header().Get("Set-Cookie"); !strings.Contains(got, "Max-Age=0") {
		t.Fatalf("clear cookie = %q", got)
	}
}

func TestLoadMiddleware(t *testing.T) {
	s, _ := newTestStore()
	id := s.Create(42)
	h := s.Load(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
		sess, ok := From(r.Context())
		if !ok {
			http.Error(w, "anonymous", http.StatusUnauthorized)
			return
		}
		w.Write([]byte{byte(sess.UserID)})
	}))
	req := httptest.NewRequest("GET", "/", nil)
	req.AddCookie(&http.Cookie{Name: CookieName, Value: id})
	rec := httptest.NewRecorder()
	h.ServeHTTP(rec, req)
	if rec.Code != 200 || rec.Body.Bytes()[0] != 42 {
		t.Fatalf("code %d", rec.Code)
	}
	req = httptest.NewRequest("GET", "/", nil)
	req.AddCookie(&http.Cookie{Name: CookieName, Value: "forged"})
	rec = httptest.NewRecorder()
	h.ServeHTTP(rec, req)
	if rec.Code != http.StatusUnauthorized {
		t.Fatalf("forged id: code %d", rec.Code)
	}
}

alexedwards/scs و gorilla/sessions مهم ​

به زبان ساده: معمولاً مخزن نشست (Session store) را از صفر نمی‌نویسید. alexedwards/scs مدیریت server-side با store قابل تعویض است؛ gorilla/sessions بیشتر برای cookie session امضاشده و در صورت نیاز رمزگذاری‌شده به کار می‌رود، یعنی داده داخل cookie است.

بدفهمی رایج: «signed cookie همان session سمت سرور است.» امضا تغییرنکردن داده را ثابت می‌کند، اما چیزی روی سرور برای حذف و ابطال ندارد. کپی cookie پس از logout تا expiry معتبر می‌ماند. پیش‌فرض scs هم آمادهٔ production نیست: Cookie.Secure=false و IdleTimeout=0 را تغییر دهید.

تعریف: scs.New() در v2 یک *SessionManager می‌دهد با Lifetime پیش‌فرض 24 h، IdleTimeout، ساختار Cookie دارای Name، Domain، HttpOnly، Path، Persist، SameSite، Secure، Partitioned، و گزینهٔ HashTokenInStore. storeها شامل memstore پیش‌فرض، postgresstore و redisstore هستند. داده روی سرور و token تصادفی یکتا در session cookie است. LoadAndSave middleware، RenewToken(ctx) چرخش پس از تغییر privilege و Destroy(ctx) حذف داده را انجام می‌دهند. gorilla/sessions، cookie و filesystem و زیرساخت backend سفارشی دارد؛ cookie امضاشده و اختیاری AES-encrypted و rotation کلید با securecookie.CodecsFromPairs. نسخهٔ v1.4.0 به‌دلیل ویژگی partitioned به Go 1.23 نیاز دارد.

scs request cycle (LoadAndSave)
1  read cookie "__Host-session" -> token
2  store.Find(sha256(token))    -> session data (or new empty session)
3  handler: sm.RenewToken(ctx); sm.Put(ctx, "userID", 7)
4  after handler: store.Commit(sha256(newToken), data, expiry); store.Delete(old)
5  Set-Cookie: __Host-session=<new token>; Path=/; HttpOnly; Secure; SameSite=Lax

سناریوی واقعی: برنامهٔ server-rendered با PostgreSQL و postgresstore؛ چند سرور پشت load balancer با redisstore؛ ابزار داخلی کوچک بدون database با gorilla CookieStore؛ و گزینهٔ «مرا به خاطر بسپار» با RememberMe در scs.

بستهمحل دادهابطال‌پذیرrotationstoreها
دست‌نویس، session این فصلسروربلهRotateآنچه پیاده کنید
alexedwards/scs/v2 v2.9.0سروربلهRenewTokenmemstore، Redis، PostgreSQL، MySQL، SQLite، BoltDB و غیره
gorilla/sessions CookieStorecookie امضاشده، اختیاری AESتا expiry خیرکلیدها با CodecsFromPairsندارد
gorilla/sessions FilesystemStoreدیسک سروربلهدستیفایل محلی

راه‌حل / کاربرد:

go
// Package scsdemo shows the same session rules with github.com/alexedwards/scs/v2:
// server-side data, RenewToken on login and logout, idle and absolute timeouts.
package scsdemo

import (
	"net/http"
	"time"

	"github.com/alexedwards/scs/v2"
)

// NewManager configures scs v2.9.0. The in-memory store is the default;
// production uses postgresstore, redisstore, etc.
func NewManager() *scs.SessionManager {
	sm := scs.New()
	sm.Lifetime = 12 * time.Hour      // absolute timeout
	sm.IdleTimeout = 30 * time.Minute // idle timeout (0 = none by default)
	sm.Cookie.Name = "__Host-session"
	sm.Cookie.HttpOnly = true // default true
	sm.Cookie.Secure = true   // default false: always set it
	sm.Cookie.SameSite = http.SameSiteLaxMode
	sm.Cookie.Persist = false // browser-session cookie
	sm.HashTokenInStore = true
	return sm
}

// Routes wires login, logout and a page that needs the user id. Credential
// checking is out of scope here (see package after).
func Routes(sm *scs.SessionManager) http.Handler {
	mux := http.NewServeMux()
	mux.HandleFunc("POST /login", func(w http.ResponseWriter, r *http.Request) {
		// ... verify credentials first ...
		if err := sm.RenewToken(r.Context()); err != nil { // new token: no fixation
			http.Error(w, "internal error", http.StatusInternalServerError)
			return
		}
		sm.Put(r.Context(), "userID", int64(7))
		w.WriteHeader(http.StatusNoContent)
	})
	mux.HandleFunc("POST /logout", func(w http.ResponseWriter, r *http.Request) {
		if err := sm.Destroy(r.Context()); err != nil { // deletes server-side data
			http.Error(w, "internal error", http.StatusInternalServerError)
			return
		}
		w.WriteHeader(http.StatusNoContent)
	})
	mux.HandleFunc("GET /me", func(w http.ResponseWriter, r *http.Request) {
		id := sm.GetInt64(r.Context(), "userID")
		if id == 0 {
			http.Error(w, "unauthenticated", http.StatusUnauthorized)
			return
		}
		w.Write([]byte("user 7"))
	})
	return sm.LoadAndSave(mux)
}
go
package scsdemo

import (
	"net/http"
	"net/http/httptest"
	"strings"
	"testing"
)

func cookieFrom(t *testing.T, rec *httptest.ResponseRecorder) *http.Cookie {
	t.Helper()
	for _, c := range rec.Result().Cookies() {
		if c.Name == "__Host-session" {
			return c
		}
	}
	return nil
}

func do(h http.Handler, method, path string, c *http.Cookie) *httptest.ResponseRecorder {
	req := httptest.NewRequest(method, path, nil)
	if c != nil {
		req.AddCookie(&http.Cookie{Name: c.Name, Value: c.Value})
	}
	rec := httptest.NewRecorder()
	h.ServeHTTP(rec, req)
	return rec
}

func TestLoginRenewsTokenAndLogoutDestroys(t *testing.T) {
	sm := NewManager()
	h := Routes(sm)

	pre := do(h, "GET", "/me", nil)
	if pre.Code != http.StatusUnauthorized {
		t.Fatalf("anonymous /me = %d", pre.Code)
	}

	login := do(h, "POST", "/login", nil)
	c := cookieFrom(t, login)
	if c == nil {
		t.Fatal("no session cookie after login")
	}
	raw := login.Header().Get("Set-Cookie")
	for _, flag := range []string{"HttpOnly", "Secure", "SameSite=Lax", "Path=/"} {
		if !strings.Contains(raw, flag) {
			t.Errorf("Set-Cookie %q lacks %s", raw, flag)
		}
	}
	if strings.Contains(raw, "Expires") {
		t.Errorf("Persist=false should give a browser-session cookie: %q", raw)
	}
	if got := do(h, "GET", "/me", c); got.Code != 200 {
		t.Fatalf("/me with session = %d", got.Code)
	}

	// A second login renews the token: the old one stops working.
	again := do(h, "POST", "/login", c)
	c2 := cookieFrom(t, again)
	if c2 == nil || c2.Value == c.Value {
		t.Fatal("RenewToken did not change the token")
	}
	if got := do(h, "GET", "/me", c); got.Code != http.StatusUnauthorized {
		t.Fatalf("old token still valid after renew: %d", got.Code)
	}

	if got := do(h, "POST", "/logout", c2); got.Code != http.StatusNoContent {
		t.Fatalf("logout = %d", got.Code)
	}
	if got := do(h, "GET", "/me", c2); got.Code != http.StatusUnauthorized {
		t.Fatalf("token valid after logout: %d", got.Code)
	}
}

JWT با golang-jwt/jwt v5: الگوریتم‌ها و بررسی claims حیاتی ​

به زبان ساده: JWT یک سند JSON کوچک از ادعاها (Claims) با امضاست. دارندهٔ کلید مناسب بدون تماس با صادرکننده می‌فهمد سند را او نوشته و هنوز منقضی نشده است. حذف lookup مزیت است؛ نبود پس‌گرفتن فوری هزینهٔ آن.

بدفهمی رایج: «payload رمزگذاری شده است.» JWS فقط base64url است و همه می‌خوانند؛ secret یا دادهٔ شخصی بیش از نیاز API نگذارید. امضای درست هم کافی نیست: صادرکننده (Issuer)، مخاطب (Audience) و expiry باید درست باشند. v5، exp و nbf موجود را بررسی می‌کند؛ iat به WithIssuedAt و iss و aud به WithIssuer و WithAudience نیاز دارند.

تعریف: claims ثبت‌شدهٔ RFC 7519 عبارت‌اند از iss صادرکننده، sub موضوع، aud مخاطب، exp انقضا، nbf شروع اعتبار، iat زمان صدور و jti شناسه. در exp زمان جاری باید پیش از انقضا باشد. HS256 از HMAC-SHA-256 با secret مشترک حداقل 256 بیت استفاده می‌کند؛ هر verifier می‌تواند صادرکننده هم باشد و password انسانی نباید کلید شود. RS256 همان RSA PKCS#1 v1.5 با SHA-256 و کلید حداقل 2048 بیت، ES256 همان ECDSA P-256 و EdDSA همان Ed25519 با امضای قطعی 64 بایتی و jwt.SigningMethodEdDSA است. الگوریتم نامتقارن اجازه می‌دهد سرویس‌ها public key داشته باشند و فقط issuer، private key. API v5 شامل jwt.NewParser(opts...)، WithValidMethods، WithIssuer، WithAudience برای هرکدام از مخاطب‌ها، WithAllAudiences، WithSubject، WithExpirationRequired، WithNotBeforeRequired، WithIssuedAt، WithLeeway، WithTimeFunc و ParseWithClaims(raw, &claims, keyFunc) است.

real token from this module (header and payload decoded, 357 bytes total)
1  header  {"alg":"EdDSA","kid":"2026-11","typ":"at+jwt"}
2  payload {"roles":["admin"],"iss":"https://auth.example.test","sub":"user:7","aud":["orders-api"],
           "exp":1795869332,"nbf":1795868732,"iat":1795868732,"jti":"01JDQ7"}
3  verify  alg in allow-list {EdDSA}? kid in key ring? typ == at+jwt?
4          Ed25519 signature ok? exp > now-30s? nbf, iat <= now+30s? iss == ...? "orders-api" in aud?
5  any "no"  -> 401; errors.Is(err, jwt.ErrTokenExpired) etc. for logs

سناریوی واقعی: API سفارش با auth مرکزی؛ access token موبایل در Authorization: Bearer؛ billing که باید token مخصوص orders را با aud رد کند؛ gateway که هویت را در header داخلی می‌فرستد و باید همان header را از ترافیک بیرونی حذف کند.

الگوریتمکلیدچه کسی صادر می‌کنداندازهٔ امضاGo SigningMethodکاربرد
HS256secret مشترک حداقل 256 بیتهمهٔ verifierها32 BSigningMethodHS256یک سرویس که خودش صادر و بررسی می‌کند
RS256RSA حداقل 2048 بیتدارندهٔ private key256 B در 2048 بیتSigningMethodRS256بیشترین سازگاری با IdPها
PS256RSA-PSSدارندهٔ private key256 BSigningMethodPS256وقتی PSS لازم است
ES256ECDSA P-256دارندهٔ private key64 BSigningMethodES256فشرده، مناسب FIPS
EdDSAEd25519دارندهٔ private key64 BSigningMethodEdDSAفشرده، سریع، بدون دام nonce
noneنداردهرکس0SigningMethodNoneهرگز؛ v5 نیازمند UnsafeAllowNoneSignatureType است
Claimپیش‌فرض v5گزینهٔ الزامخطا
expاگر باشد بررسی می‌شودWithExpirationRequired()token is expired (ErrTokenExpired)
nbfاگر باشد بررسی می‌شودWithNotBeforeRequired()token is not valid yet
iatبررسی نمی‌شودWithIssuedAt()token used before issued
audبررسی نمی‌شودWithAudience(...)، WithAllAudiences(...)token has invalid audience
issبررسی نمی‌شودWithIssuer(...)token has invalid issuer
subبررسی نمی‌شودWithSubject(...)token has invalid subject
اختلاف ساعت (Clock skew)0WithLeeway(d)بر exp و nbf و iat اعمال می‌شود

راه‌حل / کاربرد: jwtauth با EdDSA و kid و typ: at+jwt صادر می‌کند و parser الگوریتم را pin و exp و iss و aud را الزامی می‌کند.

go
// Package jwtauth issues and verifies short-lived access tokens with
// github.com/golang-jwt/jwt/v5: EdDSA (Ed25519) signatures, a kid header for
// key rotation, a fixed algorithm allow-list, and required exp/iss/aud.
package jwtauth

import (
	"crypto/ed25519"
	"errors"
	"fmt"
	"sync"
	"time"

	"github.com/golang-jwt/jwt/v5"
)

// Claims are the registered claims plus what the API needs for authorization.
type Claims struct {
	Roles []string `json:"roles,omitempty"`
	jwt.RegisteredClaims
}

// KeyRing holds the current signing key and every public key still accepted.
// Rotation: add a new key, start signing with it, keep the old public key
// until the longest-lived token signed with it has expired, then remove it.
type KeyRing struct {
	mu      sync.RWMutex
	current string
	private map[string]ed25519.PrivateKey
	public  map[string]ed25519.PublicKey
}

func NewKeyRing() *KeyRing {
	return &KeyRing{private: map[string]ed25519.PrivateKey{}, public: map[string]ed25519.PublicKey{}}
}

// Add stores a key pair under kid and makes it the signing key.
func (k *KeyRing) Add(kid string, priv ed25519.PrivateKey) {
	k.mu.Lock()
	defer k.mu.Unlock()
	k.private[kid] = priv
	k.public[kid] = priv.Public().(ed25519.PublicKey)
	k.current = kid
}

// Retire stops accepting tokens signed with kid.
func (k *KeyRing) Retire(kid string) {
	k.mu.Lock()
	defer k.mu.Unlock()
	delete(k.private, kid)
	delete(k.public, kid)
}

// Public returns a copy of the accepted public keys (for a JWKS endpoint).
func (k *KeyRing) Public() map[string]ed25519.PublicKey {
	k.mu.RLock()
	defer k.mu.RUnlock()
	out := make(map[string]ed25519.PublicKey, len(k.public))
	for kid, pub := range k.public {
		out[kid] = pub
	}
	return out
}

// Issuer signs and verifies access tokens.
type Issuer struct {
	Keys     *KeyRing
	Issuer   string        // iss, e.g. "https://auth.example.test"
	Audience string        // aud, e.g. "orders-api"
	TTL      time.Duration // 5 to 15 minutes for access tokens
	Now      func() time.Time
}

// Issue returns a compact JWS: header.payload.signature.
func (is *Issuer) Issue(subject, jti string, roles []string) (string, error) {
	is.Keys.mu.RLock()
	kid, priv := is.Keys.current, is.Keys.private[is.Keys.current]
	is.Keys.mu.RUnlock()
	if priv == nil {
		return "", errors.New("jwtauth: no signing key")
	}
	now := is.Now()
	c := Claims{
		Roles: roles,
		RegisteredClaims: jwt.RegisteredClaims{
			Issuer:    is.Issuer,
			Subject:   subject,
			Audience:  jwt.ClaimStrings{is.Audience},
			ExpiresAt: jwt.NewNumericDate(now.Add(is.TTL)),
			NotBefore: jwt.NewNumericDate(now),
			IssuedAt:  jwt.NewNumericDate(now),
			ID:        jti, // lets a denylist revoke this one token
		},
	}
	t := jwt.NewWithClaims(jwt.SigningMethodEdDSA, c)
	t.Header["kid"] = kid
	t.Header["typ"] = "at+jwt" // explicit typing (RFC 8725 section 3.11, RFC 9068)
	return t.SignedString(priv)
}

// Verify parses and validates. The algorithm comes from our allow-list, the
// key from our ring by kid, never from anything else in the token.
func (is *Issuer) Verify(raw string) (*Claims, error) {
	p := jwt.NewParser(
		jwt.WithValidMethods([]string{jwt.SigningMethodEdDSA.Alg()}), // blocks alg confusion and "none"
		jwt.WithIssuer(is.Issuer),
		jwt.WithAudience(is.Audience),
		jwt.WithExpirationRequired(),
		jwt.WithIssuedAt(),
		jwt.WithLeeway(30*time.Second), // clock skew between hosts
		jwt.WithTimeFunc(is.Now),
	)
	var c Claims
	_, err := p.ParseWithClaims(raw, &c, func(t *jwt.Token) (any, error) {
		if typ, _ := t.Header["typ"].(string); typ != "at+jwt" {
			return nil, fmt.Errorf("unexpected typ %q", typ)
		}
		kid, _ := t.Header["kid"].(string)
		is.Keys.mu.RLock()
		pub, ok := is.Keys.public[kid] // map lookup: kid is never used in SQL or a path
		is.Keys.mu.RUnlock()
		if !ok {
			return nil, fmt.Errorf("unknown kid %q", kid)
		}
		return pub, nil
	})
	if err != nil {
		return nil, err
	}
	return &c, nil
}

Alg confusion و چرخش کلید با kid حیاتی ​

به زبان ساده: token ادعا می‌کند با چه الگوریتمی ساخته شده است؛ باور کردنش انتخاب الگوریتم را به مهاجم می‌دهد. الگوریتم را برای هر کلید خودتان تعیین کنید و kid فقط یکی از کلیدهای خودتان را انتخاب کند.

بدفهمی رایج: «golang-jwt نوع کلید را بررسی می‌کند، پس بدون WithValidMethods امنم.» README می‌گوید: "This library attempts to make it easy to do the right thing by requiring key types to match the expected alg, but you should take the extra step to verify it in your usage." اگر keyfunc در یک مسیر، مثلاً برای کلاینت legacy با HS256، []byte بدهد، رخنه برای همهٔ tokenها دوباره باز می‌شود. kid هم ورودی تحت کنترل مهاجم است؛ RFC 8725 هشدار می‌دهد نباید "create SQL or LDAP injection vulnerabilities". دنبال‌کردن URL در headerهای jku یا x5u نیز "could result in server-side request forgery (SSRF) attacks".

تعریف: سردرگمی الگوریتم (Alg confusion) در بخش 2.1 از RFC 8725: "The algorithm can be changed to 'none' by an attacker"، یا "An 'RS256' ... parameter value can be changed into 'HS256' ... and some libraries would try to validate the signature using HMAC-SHA256 and using the RSA public key as the HMAC shared secret". یعنی public key مربوط به RSA به‌اشتباه secret مشترک HMAC می‌شود. دفاع بخش 3.1: "Libraries MUST enable the caller to specify a supported set of algorithms and MUST NOT use any other algorithms when performing cryptographic operations... each key MUST be used with exactly one algorithm". در چرخش کلید (Key rotation) با kid، issuer با جدیدترین کلید امضا و ID آن را در header مربوط به kid می‌گذارد؛ verifierها مجموعهٔ public keyهای پذیرفته را نگه می‌دارند. کلید قدیمی فقط پس از انقضای بلندعمرترین token امضاشده با همان کلید بازنشسته می‌شود. نوع‌دهی صریح (typ، بخش 3.11) مانع پذیرش ID token یا refresh token به‌جای access token می‌شود؛ RFC 9068 مقدار at+jwt را برای OAuth access token تعریف می‌کند.

attacker has: the public key (it is public) and one valid token
1  header {"alg":"HS256","kid":"2026-11","typ":"at+jwt"}  payload {"sub":"attacker","roles":["admin"],...}
2  sig = HMAC-SHA256(key = bytes of the Ed25519 public key, header.payload)
3  naive verifier: alg says HS256 -> HMAC with "the key" -> match -> admin
4  this module:  WithValidMethods(["EdDSA"]) -> "token signature is invalid: signing method HS256 is invalid"
5  "alg":"none" -> rejected the same way (and v5 refuses none without UnsafeAllowNoneSignatureType)
rotation:  ring {2026-11}  ->  Add 2026-12 (signs now)  ->  both verify  ->  Retire 2026-11 after max TTL

سناریوی واقعی: ارتقای کتابخانه که پیش‌فرض keyfunc را تغییر داده؛ API چندمستأجری که کلید tenant را با kid از database پیدا می‌کند (query پارامتری کنید یا بهتر، map به کار ببرید)؛ چرخش فصلی کلید در identity provider؛ پاسخ به رخنه که signing key افشاشده را فوراً کنار می‌گذارد و خروج اجباری کاربران را می‌پذیرد.

خطرفیلد headerدفاع
nonealgallow-list؛ v5 نیازمند UnsafeAllowNoneSignatureType
RS256/ES256/EdDSA به HS256algWithValidMethods برای یک خانواده؛ keyfunc فقط کلید نامتقارن
تزریق در lookupkidmap یا query پارامتری؛ بررسی طول و charset
SSRF در URL کلیدjku، x5uنادیده بگیرید؛ URL مربوط به JWKS از config
جایگزینی نوع tokentyp، audالزام نوع و audience مناسب هر token
signing key افشاشدهkidبازنشسته کردن kid و رد فوری tokenهایش

راه‌حل / کاربرد: تست، token جعلی HS256 با بایت‌های public key و token نوع none می‌سازد، رد هر دو را می‌سنجد و rotation کامل را اجرا می‌کند.

go
package jwtauth

import (
	"crypto/ed25519"
	"crypto/rand"
	"errors"
	"strings"
	"testing"
	"time"

	"github.com/golang-jwt/jwt/v5"
)

func newIssuer(t *testing.T, now *time.Time) *Issuer {
	t.Helper()
	_, priv, err := ed25519.GenerateKey(rand.Reader)
	if err != nil {
		t.Fatal(err)
	}
	ring := NewKeyRing()
	ring.Add("2026-11", priv)
	return &Issuer{Keys: ring, Issuer: "https://auth.example.test", Audience: "orders-api",
		TTL: 10 * time.Minute, Now: func() time.Time { return *now }}
}

func TestIssueVerify(t *testing.T) {
	now := time.Date(2026, 11, 28, 9, 0, 0, 0, time.UTC)
	is := newIssuer(t, &now)
	tok, err := is.Issue("user:7", "jti-1", []string{"admin"})
	if err != nil {
		t.Fatal(err)
	}
	if strings.Count(tok, ".") != 2 {
		t.Fatalf("not a compact JWS: %s", tok)
	}
	c, err := is.Verify(tok)
	if err != nil {
		t.Fatal(err)
	}
	if c.Subject != "user:7" || c.Roles[0] != "admin" || c.ID != "jti-1" {
		t.Fatalf("claims %+v", c)
	}
}

func TestExpiredAndWrongAudience(t *testing.T) {
	now := time.Date(2026, 11, 28, 9, 0, 0, 0, time.UTC)
	is := newIssuer(t, &now)
	tok, _ := is.Issue("user:7", "jti-2", nil)

	now = now.Add(10*time.Minute + 29*time.Second) // inside the 30 s leeway
	if _, err := is.Verify(tok); err != nil {
		t.Fatalf("leeway: %v", err)
	}
	now = now.Add(2 * time.Second)
	if _, err := is.Verify(tok); !errors.Is(err, jwt.ErrTokenExpired) {
		t.Fatalf("err = %v, want ErrTokenExpired", err)
	}

	now = time.Date(2026, 11, 28, 9, 0, 0, 0, time.UTC)
	other := *is
	other.Audience = "billing-api"
	if _, err := other.Verify(tok); !errors.Is(err, jwt.ErrTokenInvalidAudience) {
		t.Fatalf("err = %v, want ErrTokenInvalidAudience", err)
	}
}

// The classic alg confusion: re-sign the token with HS256 using the public
// key bytes as the HMAC secret. A parser that trusted "alg" would accept it.
func TestAlgConfusionRejected(t *testing.T) {
	now := time.Date(2026, 11, 28, 9, 0, 0, 0, time.UTC)
	is := newIssuer(t, &now)
	pub := is.Keys.Public()["2026-11"]

	forged := jwt.NewWithClaims(jwt.SigningMethodHS256, Claims{
		Roles: []string{"admin"},
		RegisteredClaims: jwt.RegisteredClaims{
			Issuer: is.Issuer, Subject: "attacker", Audience: jwt.ClaimStrings{is.Audience},
			ExpiresAt: jwt.NewNumericDate(now.Add(time.Hour)), IssuedAt: jwt.NewNumericDate(now),
		},
	})
	forged.Header["kid"] = "2026-11"
	forged.Header["typ"] = "at+jwt"
	raw, err := forged.SignedString([]byte(pub))
	if err != nil {
		t.Fatal(err)
	}
	if _, err := is.Verify(raw); !errors.Is(err, jwt.ErrTokenSignatureInvalid) {
		t.Fatalf("HS256 forgery: err = %v, want ErrTokenSignatureInvalid", err)
	}

	none := jwt.NewWithClaims(jwt.SigningMethodNone, forged.Claims)
	none.Header["kid"] = "2026-11"
	none.Header["typ"] = "at+jwt"
	rawNone, _ := none.SignedString(jwt.UnsafeAllowNoneSignatureType)
	if _, err := is.Verify(rawNone); err == nil {
		t.Fatal(`"alg":"none" accepted`)
	}
}

func TestKeyRotation(t *testing.T) {
	now := time.Date(2026, 11, 28, 9, 0, 0, 0, time.UTC)
	is := newIssuer(t, &now)
	old, _ := is.Issue("user:7", "a", nil)

	_, next, _ := ed25519.GenerateKey(rand.Reader)
	is.Keys.Add("2026-12", next)
	fresh, _ := is.Issue("user:7", "b", nil)

	for _, tok := range []string{old, fresh} {
		if _, err := is.Verify(tok); err != nil {
			t.Fatalf("during overlap: %v", err)
		}
	}
	is.Keys.Retire("2026-11")
	if _, err := is.Verify(old); err == nil {
		t.Fatal("token signed with a retired key accepted")
	}
	if _, err := is.Verify(fresh); err != nil {
		t.Fatal(err)
	}
}

func TestTamperedPayload(t *testing.T) {
	now := time.Date(2026, 11, 28, 9, 0, 0, 0, time.UTC)
	is := newIssuer(t, &now)
	tok, _ := is.Issue("user:7", "c", nil)
	parts := strings.Split(tok, ".")
	parts[1] = parts[1][:len(parts[1])-2] + "xx"
	if _, err := is.Verify(strings.Join(parts, ".")); err == nil {
		t.Fatal("tampered payload accepted")
	}
}

Access کوتاه‌عمر، refresh token و ابطال حیاتی ​

به زبان ساده: چون JWT را نمی‌توان بی‌حالت پس گرفت، اعتبارش را چند دقیقه کنید و token دومِ بلندعمر و opaque بدهید که با آن access تازه بگیرند. token دوم هر بار در database بررسی می‌شود؛ logout و reset و تشخیص سرقت همین‌جا اثر می‌گذارند.

بدفهمی رایج: «Refresh token فقط JWT بلندعمرتر است.» آن را رشتهٔ تصادفی opaque بسازید و hash آن را سمت سرور نگه دارید. استفاده‌اش کم است، پس هزینهٔ lookup ناچیز است؛ دقیقاً همان lookup ابطال‌پذیری را می‌دهد. بدفهمی دوم: «rotation کافی است.» بدون تشخیص استفادهٔ مجدد (Reuse detection)، rotation فقط پنجرهٔ سوءاستفاده را کوتاه می‌کند. RFC 9700 این دو را به هم وصل می‌کند: "If a refresh token is compromised and subsequently used by both the attacker and the legitimate client, one of them will present an invalidated refresh token, which will inform the authorization server of the breach."

تعریف: ترکیب short-lived access + refresh tokens یعنی TTL مربوط به access برابر 5-15 دقیقه و refresh از چند روز تا چند هفته است؛ هر دو به client و audience متصل‌اند. چرخش refresh (Refresh token rotation)، 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، "it will revoke the active refresh token". برای public clientها، یعنی SPA و موبایل، refresh tokenها "MUST be sender-constrained or use refresh token rotation". ابطال (Revocation) access پیش از exp به state نیاز دارد: denylist از jti که هر entry تا exp خود token می‌ماند (کلید Redis با TTL)، timestamp مخصوص هر کاربر با معنای «token صادرشده پیش از T نامعتبر است»، یا token status listهای راهنمای OWASP JWT.

t=0      login                      -> A1 (10 min), R1 (30 days, family F)        store sha256(R1)
t=10m    POST /token R1             -> A2, R2; R1 marked used
t=12m    attacker POST /token R1    -> R1 used: reuse! revoke family F            ErrReused
t=13m    client POST /token R2      -> family revoked: 401, log in again           ErrInvalid
t=14m    A2 still verifies at the API until t=20m unless its jti is on the denylist
Refresh token rotation: a used token presented twice kills the familyClientAuth server (family F)Attackert=0 login (password + MFA)A1 (JWT, 10 min) + R1 (opaque, 30 days)store sha256(R1): family F, unusedR1 leaks (XSS, log, backup)t=10 min: A1 expired, POST /token R1A2 + R2R1 marked used, R2 stored in Freplays R1R1 already used: reuse detected, revoke family Fserver cannot tell thief from owner, so both loselater: POST /token R2401 invalid_grant: log in againIf the thief had rotated first, the owner's replayof R1 triggers the same revocation.

سناریوی واقعی: برنامهٔ موبایل که یک ماه وارد می‌ماند اما access آن هر 10 دقیقه منقضی می‌شود؛ refresh دزدیده‌شده از SPA دارای XSS که در refresh بعدیِ کلاینت واقعی آشکار می‌شود؛ «خروج از همهٔ دستگاه‌ها» پس از تغییر password؛ adminی که حساب را غیرفعال می‌کند در حالی که access کاربر هنوز 8 دقیقه عمر دارد (یا jti را denylist کنید یا این پنجره را بپذیرید).

روشچه چیزی باطل می‌شودstate لازمزمان اثر
TTL کوتاه accessدر نهایت همههیچتا TTL؛ این‌جا 10 min
حذف refreshaccessهای آیندهجدول refreshتا یک TTL از access
rotation و reuse detectionخانوادهٔ refresh سرقت‌شدهused flag و family idrefresh بعدی هر طرف
denylist از jtiیک accessکلید هر token تا expفوری؛ بررسی هر درخواست
not-before کاربرهمهٔ tokenهای پیش از Tیک timestamp برای هر کاربرفوری؛ یک lookup در درخواست
بازنشستگی kidهمهٔ tokenهای کلیدkey ringفوری برای همهٔ آن کلید

راه‌حل / کاربرد: بستهٔ refresh فقط hashها را ذخیره می‌کند، rotation را زیر lock انجام می‌دهد (در SQL: یک transaction با SELECT ... FOR UPDATE)، خانواده را هنگام reuse باطل می‌کند و denylist مربوط به jti دارد که entryهایش را در exp خودکار پاک می‌کند. تست هم‌زمانی ثابت می‌کند 20 refresh هم‌زمان با یک token دقیقاً یک برنده دارند.

go
// Package refresh implements opaque refresh tokens with rotation and reuse
// detection (RFC 9700 section 4.14.2), plus a jti denylist for revoking an
// access token before it expires.
package refresh

import (
	"crypto/rand"
	"crypto/sha256"
	"encoding/hex"
	"errors"
	"sync"
	"time"
)

var (
	ErrInvalid = errors.New("refresh: invalid or expired token")
	ErrReused  = errors.New("refresh: token reuse detected, family revoked")
)

type record struct {
	userID  int64
	family  string // one login = one family
	expires time.Time
	used    bool // rotated away; presenting it again means theft
}

// Store keeps only SHA-256(token): a stolen table is not a list of tokens.
// In SQL the Rotate critical section is one transaction with SELECT ... FOR
// UPDATE on the row (see the page's schema).
type Store struct {
	mu      sync.Mutex
	byHash  map[string]*record
	revoked map[string]bool // revoked families
	TTL     time.Duration   // e.g. 30 days, sliding with each rotation
	Now     func() time.Time
}

func NewStore(ttl time.Duration) *Store {
	return &Store{byHash: map[string]*record{}, revoked: map[string]bool{}, TTL: ttl, Now: time.Now}
}

func newToken() string {
	b := make([]byte, 32)
	rand.Read(b)
	return hex.EncodeToString(b)
}

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

// Issue starts a new family at login.
func (s *Store) Issue(userID int64) string {
	s.mu.Lock()
	defer s.mu.Unlock()
	return s.issueLocked(userID, newToken())
}

func (s *Store) issueLocked(userID int64, family string) string {
	tok := newToken()
	s.byHash[digest(tok)] = &record{userID: userID, family: family, expires: s.Now().Add(s.TTL)}
	return tok
}

// Rotate consumes tok and returns its successor. Exactly one concurrent
// caller can win; a second presentation of a used token revokes the family.
func (s *Store) Rotate(tok string) (userID int64, next string, err error) {
	s.mu.Lock()
	defer s.mu.Unlock()
	rec, ok := s.byHash[digest(tok)]
	if !ok || s.revoked[rec.family] || s.Now().After(rec.expires) {
		return 0, "", ErrInvalid
	}
	if rec.used {
		s.revoked[rec.family] = true // attacker and victim both lose; victim logs in again
		return 0, "", ErrReused
	}
	rec.used = true
	return rec.userID, s.issueLocked(rec.userID, rec.family), nil
}

// RevokeUser ends every family of a user (logout everywhere, password reset).
func (s *Store) RevokeUser(userID int64) {
	s.mu.Lock()
	defer s.mu.Unlock()
	for _, r := range s.byHash {
		if r.userID == userID {
			s.revoked[r.family] = true
		}
	}
}

// Denylist revokes individual access tokens by jti until their exp. Entries
// expire with the token, so the list stays as small as the access TTL allows.
type Denylist struct {
	mu  sync.Mutex
	ids map[string]time.Time // jti -> token exp
	Now func() time.Time
}

func NewDenylist() *Denylist { return &Denylist{ids: map[string]time.Time{}, Now: time.Now} }

func (d *Denylist) Revoke(jti string, exp time.Time) {
	d.mu.Lock()
	d.ids[jti] = exp
	d.mu.Unlock()
}

// Revoked is checked by the API after signature and claims validation.
func (d *Denylist) Revoked(jti string) bool {
	d.mu.Lock()
	defer d.mu.Unlock()
	now := d.Now()
	for id, exp := range d.ids { // a Redis key with TTL does this for free
		if now.After(exp) {
			delete(d.ids, id)
		}
	}
	_, ok := d.ids[jti]
	return ok
}
go
package refresh

import (
	"errors"
	"sync"
	"testing"
	"time"
)

func TestRotateChain(t *testing.T) {
	s := NewStore(30 * 24 * time.Hour)
	t1 := s.Issue(7)
	uid, t2, err := s.Rotate(t1)
	if err != nil || uid != 7 || t2 == t1 {
		t.Fatalf("uid=%d err=%v", uid, err)
	}
	if _, _, err := s.Rotate(t2); err != nil {
		t.Fatal(err)
	}
}

func TestReuseRevokesFamily(t *testing.T) {
	s := NewStore(time.Hour)
	stolen := s.Issue(7)
	_, legit, _ := s.Rotate(stolen) // the real client rotates first
	if _, _, err := s.Rotate(stolen); !errors.Is(err, ErrReused) {
		t.Fatalf("replay: err = %v, want ErrReused", err)
	}
	if _, _, err := s.Rotate(legit); !errors.Is(err, ErrInvalid) {
		t.Fatalf("family should be revoked: err = %v", err)
	}
	other := s.Issue(7) // a new login is a new family
	if _, _, err := s.Rotate(other); err != nil {
		t.Fatal(err)
	}
}

func TestConcurrentRotateHasOneWinner(t *testing.T) {
	s := NewStore(time.Hour)
	tok := s.Issue(7)
	var wg sync.WaitGroup
	var mu sync.Mutex
	wins := 0
	for range 20 {
		wg.Add(1)
		go func() {
			defer wg.Done()
			if _, _, err := s.Rotate(tok); err == nil {
				mu.Lock()
				wins++
				mu.Unlock()
			}
		}()
	}
	wg.Wait()
	if wins != 1 {
		t.Fatalf("%d winners, want 1", wins)
	}
}

func TestExpiryAndRevokeUser(t *testing.T) {
	now := time.Date(2026, 11, 28, 9, 0, 0, 0, time.UTC)
	s := NewStore(time.Hour)
	s.Now = func() time.Time { return now }
	tok := s.Issue(7)
	now = now.Add(61 * time.Minute)
	if _, _, err := s.Rotate(tok); !errors.Is(err, ErrInvalid) {
		t.Fatalf("expired: %v", err)
	}
	now = now.Add(time.Minute)
	tok = s.Issue(7)
	s.RevokeUser(7)
	if _, _, err := s.Rotate(tok); !errors.Is(err, ErrInvalid) {
		t.Fatalf("after RevokeUser: %v", err)
	}
}

func TestDenylist(t *testing.T) {
	now := time.Date(2026, 11, 28, 9, 0, 0, 0, time.UTC)
	d := NewDenylist()
	d.Now = func() time.Time { return now }
	d.Revoke("jti-1", now.Add(10*time.Minute))
	if !d.Revoked("jti-1") || d.Revoked("jti-2") {
		t.Fatal("denylist lookup wrong")
	}
	now = now.Add(11 * time.Minute) // the token itself has expired by now
	if d.Revoked("jti-1") || len(d.ids) != 0 {
		t.Fatal("entry not pruned after exp")
	}
}

دریافت JWKS مهم ​

به زبان ساده: مجموعهٔ کلیدها (JWK Set) فهرست JSON از public keyها در URL شناخته‌شده است. verifier آن را دریافت و cache می‌کند و با kid کلید را می‌یابد. پس از rotation، kid ناشناخته دریافت دوباره را راه می‌اندازد.

بدفهمی رایج: «JWKS را در هر درخواست fetch کن» هم کند است و هم issuer را به یک نقطهٔ شکست واحد تبدیل می‌کند. «فقط یک بار هنگام startup بگیر» نیز با اولین rotation، همهٔ verifierها را از کار می‌اندازد. مجموعه را cache کنید و هنگام kid ناشناخته refresh کنید، اما همین refresh را rate-limit کنید؛ وگرنه جریان tokenهای دارای kid تصادفی، API شما را ابزار denial-of-service علیه issuer می‌کند.

تعریف: RFC 7517 می‌گوید JWK Set دارای "a 'keys' member, which is an array of JWKs" است و "The 'kid' (key ID) parameter is used to match a specific key." کلید Ed25519 طبق RFC 8037 به‌شکل {"kty":"OKP","crv":"Ed25519","x":"<base64url>","kid":"...","alg":"EdDSA","use":"sig"} است. OpenID providerها URL را در jwks_uri از سند discovery منتشر می‌کنند. MicahParks/keyfunc قابلیت "An automatic refresh of remote HTTP resources when an unknown key ID (kid) is encountered" را دارد و یک jwt.Keyfunc برمی‌گرداند؛ README مربوط به golang-jwt آن را افزونهٔ JWKS معرفی می‌کند.

1  verify(token kid=k2)   cache {k1}            -> unknown kid
2  last attempt 2 min ago < MinRefresh 5 min    -> reject (no fetch: kid spraying is cheap for attackers)
3  6 min later            >= MinRefresh          -> GET https://auth.example.test/.well-known/jwks.json
4                         cache {k1, k2}         -> verify with k2
5  token kid=nope         just attempted         -> reject without another fetch
6  issuer removes k1; 6 min later, token kid=k1 -> attempt is due: refetch -> {k2} -> k1 rejected
7  issuer returns 500     attempt recorded       -> next attempt only after MinRefresh; last good set kept

سناریوی واقعی: تک‌تک سرویس‌های یک fleet که tokenهای Auth0، Keycloak، Cognito یا issuer داخلی را verify می‌کنند؛ قطعی issuer که در آن کلیدهای cacheشده APIها را فعال نگه می‌دارند؛ rotation کلید در IdP در یک بعدازظهر سه‌شنبه که هیچ‌کس متوجهش نمی‌شود، چون verifierها با دیدن kid ناشناخته refresh می‌کنند.

دغدغهاین پیاده‌سازیkeyfunc
منبع URLفقط config؛ jku نادیدهconfig
kid ناشناختهحداکثر یک refresh در MinRefreshrefresh محدودشده
kid حذف‌شدهپس از MinRefresh، هر lookup مجموعه را دوباره می‌گیرد و کلید حذف‌شده کنار می‌رودrefresh پس‌زمینه مجموعه را جایگزین می‌کند
issuer قطعتلاش شکست‌خورده هم زمان انتظار را شروع می‌کند؛ آخرین مجموعهٔ خوب می‌ماندخطای refresh با کتابخانه
الگوریتم هر کلیدفقط OKP/Ed25519/EdDSA نگه داشته می‌شوندalg مخصوص هر JWK
اندازهٔ پاسخMaxBytesReader با 1 MiBمحدودیت کتابخانه
HTTPCache-Control: public, max-age=300 روی سرورفاصلهٔ refresh پس‌زمینه

راه‌حل / کاربرد:

go
// Package jwks publishes Ed25519 public keys as a JWK Set (RFC 7517, OKP
// keys per RFC 8037) and fetches them on the verifying side with a cache
// that refreshes on an unknown kid, at most once per MinRefresh.
// In production, github.com/MicahParks/keyfunc does the client half.
package jwks

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

	"github.com/golang-jwt/jwt/v5"
)

type jwk struct {
	Kty string `json:"kty"` // "OKP"
	Crv string `json:"crv"` // "Ed25519"
	X   string `json:"x"`   // base64url public key
	Kid string `json:"kid"`
	Use string `json:"use"` // "sig"
	Alg string `json:"alg"` // "EdDSA"
}

type set struct {
	Keys []jwk `json:"keys"`
}

// Handler serves GET /.well-known/jwks.json from a key source.
func Handler(keys func() map[string]ed25519.PublicKey) http.Handler {
	return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
		var s set
		for kid, pub := range keys() {
			s.Keys = append(s.Keys, jwk{Kty: "OKP", Crv: "Ed25519", Kid: kid, Use: "sig", Alg: "EdDSA",
				X: base64.RawURLEncoding.EncodeToString(pub)})
		}
		w.Header().Set("Content-Type", "application/jwk-set+json")
		w.Header().Set("Cache-Control", "public, max-age=300")
		json.NewEncoder(w).Encode(s)
	})
}

// Cache is the verifier side.
type Cache struct {
	URL        string // fixed in config: never taken from a jku header
	Client     *http.Client
	MinRefresh time.Duration // e.g. 5 * time.Minute; stops kid-spraying from DoS-ing the issuer
	Now        func() time.Time

	mu        sync.Mutex
	keys      map[string]ed25519.PublicKey
	attempted time.Time // last fetch attempt, successful or not
	Fetches   int       // successful fetches, for the test
}

func (c *Cache) refresh(ctx context.Context) error {
	req, err := http.NewRequestWithContext(ctx, http.MethodGet, c.URL, nil)
	if err != nil {
		return err
	}
	resp, err := c.Client.Do(req)
	if err != nil {
		return err
	}
	defer resp.Body.Close()
	if resp.StatusCode != http.StatusOK {
		return fmt.Errorf("jwks: status %d", resp.StatusCode)
	}
	var s set
	if err := json.NewDecoder(http.MaxBytesReader(nil, resp.Body, 1<<20)).Decode(&s); err != nil {
		return err
	}
	keys := map[string]ed25519.PublicKey{}
	for _, k := range s.Keys {
		if k.Kty != "OKP" || k.Crv != "Ed25519" || k.Alg != "EdDSA" {
			continue // only the one algorithm we accept
		}
		raw, err := base64.RawURLEncoding.DecodeString(k.X)
		if err != nil || len(raw) != ed25519.PublicKeySize {
			continue
		}
		keys[k.Kid] = ed25519.PublicKey(raw)
	}
	c.keys, c.Fetches = keys, c.Fetches+1
	return nil
}

// Key returns the key for kid. At most once per MinRefresh (counting failed
// attempts too) it re-fetches the set: that picks up new kids and drops kids
// the issuer no longer publishes, so a retired or compromised key stops
// verifying within MinRefresh. If the issuer is down, the last good set is
// kept, and the next attempt waits for MinRefresh again.
func (c *Cache) Key(ctx context.Context, kid string) (ed25519.PublicKey, error) {
	c.mu.Lock()
	defer c.mu.Unlock()
	now := c.Now()
	if c.attempted.IsZero() || now.Sub(c.attempted) >= c.MinRefresh {
		c.attempted = now
		if err := c.refresh(ctx); err != nil && c.keys == nil {
			return nil, err
		}
	}
	if k, ok := c.keys[kid]; ok {
		return k, nil
	}
	return nil, fmt.Errorf("jwks: unknown kid %q", kid)
}

// Keyfunc adapts the cache to golang-jwt. Pair it with
// jwt.WithValidMethods([]string{"EdDSA"}).
func (c *Cache) Keyfunc(ctx context.Context) jwt.Keyfunc {
	return func(t *jwt.Token) (any, error) {
		kid, ok := t.Header["kid"].(string)
		if !ok {
			return nil, errors.New("jwks: token has no kid")
		}
		return c.Key(ctx, kid)
	}
}
go
package jwks

import (
	"crypto/ed25519"
	"crypto/rand"
	"net/http/httptest"
	"sync"
	"testing"
	"time"

	"github.com/golang-jwt/jwt/v5"
)

func TestFetchVerifyAndRotate(t *testing.T) {
	var mu sync.Mutex
	pubs := map[string]ed25519.PublicKey{}
	privs := map[string]ed25519.PrivateKey{}
	add := func(kid string) {
		pub, priv, _ := ed25519.GenerateKey(rand.Reader)
		mu.Lock()
		pubs[kid], privs[kid] = pub, priv
		mu.Unlock()
	}
	add("k1")
	srv := httptest.NewTLSServer(Handler(func() map[string]ed25519.PublicKey {
		mu.Lock()
		defer mu.Unlock()
		out := map[string]ed25519.PublicKey{}
		for k, v := range pubs {
			out[k] = v
		}
		return out
	}))
	defer srv.Close()

	now := time.Date(2026, 11, 28, 9, 0, 0, 0, time.UTC)
	c := &Cache{URL: srv.URL, Client: srv.Client(), MinRefresh: 5 * time.Minute,
		Now: func() time.Time { return now }}

	sign := func(kid string) string {
		tok := jwt.NewWithClaims(jwt.SigningMethodEdDSA, jwt.MapClaims{"sub": "user:7"})
		tok.Header["kid"] = kid
		mu.Lock()
		priv, ok := privs[kid]
		mu.Unlock()
		if !ok {
			priv = privs["k1"] // a token claiming a kid the issuer never published
		}
		s, err := tok.SignedString(priv)
		if err != nil {
			t.Fatal(err)
		}
		return s
	}
	parse := func(raw string) error {
		_, err := jwt.Parse(raw, c.Keyfunc(t.Context()), jwt.WithValidMethods([]string{"EdDSA"}))
		return err
	}

	if err := parse(sign("k1")); err != nil {
		t.Fatal(err)
	}
	if err := parse(sign("k1")); err != nil || c.Fetches != 1 {
		t.Fatalf("cached key: err=%v fetches=%d", err, c.Fetches)
	}

	add("k2") // issuer rotates
	if err := parse(sign("k2")); err == nil {
		t.Fatal("unknown kid accepted before MinRefresh elapsed")
	}
	now = now.Add(6 * time.Minute)
	if err := parse(sign("k2")); err != nil || c.Fetches != 2 {
		t.Fatalf("after refresh: err=%v fetches=%d", err, c.Fetches)
	}
	if err := parse(sign("nope")); err == nil || c.Fetches != 2 {
		t.Fatalf("kid spraying triggered a fetch: fetches=%d", c.Fetches)
	}
}

دو تست دیگر رفتار ابطال و قطعی را تثبیت می‌کنند: کلیدی که از مجموعهٔ منتشرشده حذف شده، پس از MinRefresh دیگر verify نمی‌شود؛ و پنج kid ناشناخته هنگام قطعی با پاسخ 500، فقط یک fetch ایجاد می‌کنند، نه پنج fetch.

go
package jwks

import (
	"crypto/ed25519"
	"crypto/rand"
	"net/http"
	"net/http/httptest"
	"sync"
	"sync/atomic"
	"testing"
	"time"
)

// A key removed from the issuer's set must stop verifying once MinRefresh
// has passed: the cache re-validates known kids against the published set.
func TestRemovedKeyStopsVerifying(t *testing.T) {
	var mu sync.Mutex
	pub, _, _ := ed25519.GenerateKey(rand.Reader)
	keys := map[string]ed25519.PublicKey{"k1": pub}
	srv := httptest.NewTLSServer(Handler(func() map[string]ed25519.PublicKey {
		mu.Lock()
		defer mu.Unlock()
		out := map[string]ed25519.PublicKey{}
		for k, v := range keys {
			out[k] = v
		}
		return out
	}))
	defer srv.Close()
	now := time.Date(2026, 11, 28, 9, 0, 0, 0, time.UTC)
	c := &Cache{URL: srv.URL, Client: srv.Client(), MinRefresh: 5 * time.Minute, Now: func() time.Time { return now }}
	if _, err := c.Key(t.Context(), "k1"); err != nil {
		t.Fatal(err)
	}
	mu.Lock()
	delete(keys, "k1") // issuer retires a compromised key
	mu.Unlock()
	now = now.Add(6 * time.Minute)
	if _, err := c.Key(t.Context(), "k1"); err == nil {
		t.Fatal("key removed from the published set still verifies after MinRefresh")
	}
}

// During an issuer outage, unknown kids must not trigger one fetch each.
func TestFailedRefreshIsRateLimited(t *testing.T) {
	var hits atomic.Int64
	srv := httptest.NewTLSServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
		hits.Add(1)
		http.Error(w, "down", http.StatusInternalServerError)
	}))
	defer srv.Close()
	now := time.Date(2026, 11, 28, 9, 0, 0, 0, time.UTC)
	c := &Cache{URL: srv.URL, Client: srv.Client(), MinRefresh: 5 * time.Minute, Now: func() time.Time { return now }}
	for _, kid := range []string{"a", "b", "c", "d", "e"} {
		if _, err := c.Key(t.Context(), kid); err == nil {
			t.Fatal("unknown kid accepted")
		}
	}
	if n := hits.Load(); n != 1 {
		t.Fatalf("%d fetches during the outage, want 1", n)
	}
	now = now.Add(6 * time.Minute)
	c.Key(t.Context(), "f")
	if n := hits.Load(); n != 2 {
		t.Fatalf("after MinRefresh: %d fetches, want 2", n)
	}
}

کلاینت OAuth2 و OIDC با x/oauth2 و coreos/go-oidc تکمیلی ​

به زبان ساده: «ورود با Google/Microsoft/Okta» لایهٔ هویت OpenID Connect روی OAuth 2.0 است. برنامه کاربر را به provider می‌فرستد، code یک‌بارمصرف می‌گیرد، آن را با token مبادله و ID token را verify می‌کند. دو بسته بیشتر کار را انجام می‌دهند.

بدفهمی رایج: «Access token سرویس‌دهنده هویت را ثابت می‌کند.» آن token برای APIهای provider است؛ هویت از ID token تأییدشده با iss، aud برابر client ID خودتان، exp و nonce می‌آید. پس از callback هنوز باید session محلی خودتان را بسازید.

تعریف: golang.org/x/oauth2 شامل oauth2.Config{ClientID, ClientSecret, Endpoint, RedirectURL, Scopes}، AuthCodeURL(state, opts...)، Exchange(ctx, code, opts...) و ابزار PKCE یعنی GenerateVerifier()، S256ChallengeOption(verifier) و VerifierOption(verifier) است. در github.com/coreos/go-oidc/v3/oidc، oidc.NewProvider(ctx, issuerURL) discovery را می‌خواند؛ provider.Verifier(&oidc.Config{ClientID: clientID}) و verifier.Verify(ctx, rawIDToken) امضا را با JWKS و سپس issuer و audience و expiry را بررسی می‌کنند. سورس صریح است: "Verify does NOT do nonce validation, which is the caller's responsibility". با oidc.Nonce(n)، nonce بفرستید و idToken.Nonce را با مقدار session پیش از login مقایسه کنید. جزئیات flow و SSO در OAuth2, OIDC & SSO است.

1  GET /login/google   -> state, PKCE verifier into the (pre-login) session
2  302 to provider     AuthCodeURL(state, S256ChallengeOption(verifier)) + scope openid email
3  GET /callback?code&state   -> state matches session? (CSRF on the login itself)
4  Exchange(ctx, code, VerifierOption(verifier)) -> oauth2.Token with "id_token" extra
5  verifier.Verify(ctx, rawIDToken) -> signature, iss, aud, exp; then YOU check idToken.Nonce == session nonce
6  find or create local user by (issuer, sub); Rotate session; Set-Cookie

سناریوی واقعی: SaaS سازمانی با Microsoft؛ ابزار داخلی پشت Okta؛ موبایل با مرورگر سیستم و PKCE؛ API Go که فقط access token Keycloak را بررسی می‌کند و resource server است، پس JWKS می‌خواهد نه flow ورود go-oidc.

نیازبستهفراخوانی‌ها
authorization code و PKCEgolang.org/x/oauth2AuthCodeURL، Exchange، GenerateVerifier، S256ChallengeOption
discovery و بررسی ID tokengithub.com/coreos/go-oidc/v3/oidcNewProvider، Verifier، Verify، IDToken.Claims
بررسی access در APIgolang-jwt/jwt/v5 + JWKS با keyfuncWithValidMethods، WithIssuer، WithAudience
client credentials سرویس‌به‌سرویسgolang.org/x/oauth2/clientcredentialsConfig.Token، Config.Client

راه‌حل / کاربرد: state و PKCE verifier و nonce را در session پیش از login نگه دارید. callback باید state را بسنجد، با VerifierOption مبادله کند، ID token را verify و nonce را خودش مقایسه کند. کاربر محلی را با (iss, sub) پیدا کنید، هرگز فقط ایمیل؛ سپس مثل login گذرواژه Rotate کنید. API فقط دریافت‌کنندهٔ access از JWKS استفاده کند.

Auth middleware، هویت context و کنترل مجوز هر handler حیاتی ​

به زبان ساده: میان‌افزار احراز هویت (Auth middleware) یک بار می‌پرسد «این کیست؟» و پاسخ را زیر کلیدی غیرقابل جعل توسط بستهٔ دیگر در context می‌گذارد. handler پس از بارگیری شیء می‌پرسد «این شخص اجازهٔ این کار روی این شیء را دارد؟».

بدفهمی رایج: «RequireRole("user") روی گروه route کافی است.» user بودن مالکیت فاکتور 1001 را ثابت نمی‌کند؛ همین شکاف، Broken Object Level Authorization در OWASP API1:2023 است. credential نامعتبر را هم نباید با روش ضعیف‌تر یا ناشناس جایگزین کرد؛ شکست را رد کنید تا downgrade ساخته نشود.

تعریف: middleware از نوع func(http.Handler) http.Handler در Middlewares، credential را از cookie با session.Load یا از Authorization: Bearer با jwtauth.Verify می‌خواند. موفقیت به next.ServeHTTP(w, r.WithContext(WithIdentity(ctx, id))) و شکست به 401 همراه WWW-Authenticate می‌رسد. کلید context نوع unexported مانند type ctxKey struct{} دارد؛ context.WithValue(ctx, "identity", ...) از بستهٔ دیگر جای آن نمی‌نشیند؛ قواعد در context. کنترل مجوز (Authorization) هر handler پس از load، مالک و tenant و state را می‌سنجد. 403 Forbidden یعنی هویت معلوم ولی مجوز ناکافی؛ برای شیئی که وجودش هم نباید معلوم باشد 404 بدهید.

     request                          RequireUser(Bearer(verify))         InvoiceHandler
1    GET /invoices/1001, no token  -> 401 + WWW-Authenticate: Bearer realm="api"
2    Bearer forged                 -> verify fails -> 401 (no fallback to another scheme)
3    Bearer alice (user 1)         -> ctx{Identity{1}}  ───────────────▶ load 1001: owner 1 == 1 -> 200
4    Bearer bob (user 2)           -> ctx{Identity{2}}  ───────────────▶ load 1001: owner 1 != 2 -> 404
5    Bearer root (admin)           -> ctx{Identity{9, admin}} ──────────▶ admin -> 200
6    GET /admin/stats as alice     -> RequireRole("admin") -> 403

سناریوی واقعی: خریدار بازارگاه با افزایش ID آدرس دیگران را می‌خواند؛ repository چندمستأجری باید tenant را از identity بگیرد نه body؛ پشتیبانی اجازهٔ خواندن دارد ولی refund نه؛ endpoint موبایل هم cookie وب‌ویو و هم bearer می‌پذیرد.

لایهپرسششکستمحل در Go
Authentication middlewareچه کسی؟401 و WWW-AuthenticateRequireUser
مجوز کلی routeاین role این‌جا مجاز است؟403RequireRole
مجوز شیء در handlerاین کار روی این شیء مجاز است؟404 برای پنهان‌سازی یا 403بعد از Load، مقایسهٔ owner/tenant
محافظ data layerدفاع چندلایهنتیجهٔ خالیWHERE id = $1 AND owner_id = $2
مجوز فیلددیدن این فیلد مجاز است؟حذف فیلدDTO پاسخ متناسب با role

راه‌حل / کاربرد:

go
// Package authmw turns "who is calling" into a typed value in the request
// context (authentication), and leaves "may they do this" to each handler
// (authorization), with a small helper for role checks.
package authmw

import (
	"context"
	"errors"
	"net/http"
	"slices"
	"strings"
)

// Identity is what every handler may rely on after RequireUser.
type Identity struct {
	UserID int64
	Roles  []string
	Method string // "session" or "bearer": some actions demand a session
}

func (id *Identity) Has(role string) bool { return slices.Contains(id.Roles, role) }

type ctxKey struct{} // unexported: no other package can read or forge it

func WithIdentity(ctx context.Context, id *Identity) context.Context {
	return context.WithValue(ctx, ctxKey{}, id)
}

// From returns the caller, or nil for anonymous requests.
func From(ctx context.Context) *Identity {
	id, _ := ctx.Value(ctxKey{}).(*Identity)
	return id
}

// ErrNoCredentials means "nothing presented"; any other error means
// "something presented and it was wrong". Both answer 401.
var ErrNoCredentials = errors.New("authmw: no credentials")

// Authenticator checks one kind of credential (session cookie, bearer JWT).
type Authenticator func(r *http.Request) (*Identity, error)

// Bearer extracts "Authorization: Bearer <token>" and hands it to verify.
func Bearer(verify func(token string) (*Identity, error)) Authenticator {
	return func(r *http.Request) (*Identity, error) {
		h := r.Header.Get("Authorization")
		scheme, tok, ok := strings.Cut(h, " ")
		if !ok || !strings.EqualFold(scheme, "Bearer") || tok == "" {
			return nil, ErrNoCredentials
		}
		id, err := verify(tok)
		if err != nil {
			return nil, err
		}
		id.Method = "bearer"
		return id, nil
	}
}

// RequireUser tries each authenticator in order and rejects with 401 when
// none succeeds. The error detail goes to logs, never to the client.
func RequireUser(auths ...Authenticator) func(http.Handler) http.Handler {
	return func(next http.Handler) http.Handler {
		return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
			for _, a := range auths {
				id, err := a(r)
				if errors.Is(err, ErrNoCredentials) {
					continue
				}
				if err != nil {
					break // a wrong credential: do not fall through to the next scheme
				}
				next.ServeHTTP(w, r.WithContext(WithIdentity(r.Context(), id)))
				return
			}
			w.Header().Set("WWW-Authenticate", `Bearer realm="api"`)
			http.Error(w, "authentication required", http.StatusUnauthorized)
		})
	}
}

// RequireRole is coarse-grained authorization for a whole route group.
func RequireRole(role string) func(http.Handler) http.Handler {
	return func(next http.Handler) http.Handler {
		return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
			id := From(r.Context())
			if id == nil {
				http.Error(w, "authentication required", http.StatusUnauthorized)
				return
			}
			if !id.Has(role) {
				http.Error(w, "forbidden", http.StatusForbidden)
				return
			}
			next.ServeHTTP(w, r)
		})
	}
}
go
package authmw

import (
	"encoding/json"
	"net/http"
	"strconv"
)

type Invoice struct {
	ID      int64 `json:"id"`
	OwnerID int64 `json:"owner_id"`
	Total   int64 `json:"total_cents"`
}

// InvoiceHandler shows the check no middleware can do for you: the object's
// owner is only known after loading it. Skipping it is IDOR / BOLA, the
// first item (API1:2023) of the OWASP API Security Top 10.
type InvoiceHandler struct {
	Load func(id int64) (Invoice, bool)
}

func (h InvoiceHandler) ServeHTTP(w http.ResponseWriter, r *http.Request) {
	me := From(r.Context()) // set by RequireUser
	id, err := strconv.ParseInt(r.PathValue("id"), 10, 64)
	if err != nil {
		http.NotFound(w, r)
		return
	}
	inv, ok := h.Load(id)
	// Same 404 for "does not exist" and "not yours": do not confirm that
	// invoice 1002 exists to someone who may not see it. Admins see all.
	if !ok || (inv.OwnerID != me.UserID && !me.Has("admin")) {
		http.NotFound(w, r)
		return
	}
	w.Header().Set("Content-Type", "application/json")
	json.NewEncoder(w).Encode(inv)
}
go
package authmw

import (
	"context"
	"errors"
	"net/http"
	"net/http/httptest"
	"testing"
)

func routes() http.Handler {
	verify := func(tok string) (*Identity, error) {
		switch tok {
		case "alice":
			return &Identity{UserID: 1}, nil
		case "bob":
			return &Identity{UserID: 2}, nil
		case "root":
			return &Identity{UserID: 9, Roles: []string{"admin"}}, nil
		}
		return nil, errors.New("bad token")
	}
	invoices := map[int64]Invoice{1001: {ID: 1001, OwnerID: 1, Total: 4200}}
	auth := RequireUser(Bearer(verify))

	mux := http.NewServeMux()
	mux.Handle("GET /invoices/{id}", auth(InvoiceHandler{Load: func(id int64) (Invoice, bool) {
		inv, ok := invoices[id]
		return inv, ok
	}}))
	mux.Handle("GET /admin/stats", auth(RequireRole("admin")(http.HandlerFunc(
		func(w http.ResponseWriter, r *http.Request) { w.Write([]byte("ok")) }))))
	return mux
}

func call(h http.Handler, path, token string) *httptest.ResponseRecorder {
	req := httptest.NewRequest("GET", path, nil)
	if token != "" {
		req.Header.Set("Authorization", "Bearer "+token)
	}
	rec := httptest.NewRecorder()
	h.ServeHTTP(rec, req)
	return rec
}

func TestAuthenticationAndAuthorization(t *testing.T) {
	h := routes()
	cases := []struct {
		name, path, token string
		want              int
	}{
		{"no credentials", "/invoices/1001", "", 401},
		{"bad token", "/invoices/1001", "forged", 401},
		{"owner", "/invoices/1001", "alice", 200},
		{"other user: IDOR blocked, same as missing", "/invoices/1001", "bob", 404},
		{"missing invoice", "/invoices/1002", "alice", 404},
		{"admin sees all", "/invoices/1001", "root", 200},
		{"role required", "/admin/stats", "alice", 403},
		{"role present", "/admin/stats", "root", 200},
	}
	for _, c := range cases {
		t.Run(c.name, func(t *testing.T) {
			rec := call(h, c.path, c.token)
			if rec.Code != c.want {
				t.Fatalf("%s %s: %d, want %d", c.token, c.path, rec.Code, c.want)
			}
			if c.want == 401 && rec.Header().Get("WWW-Authenticate") == "" {
				t.Fatal("401 without WWW-Authenticate")
			}
		})
	}
}

func TestContextKeyCannotBeForged(t *testing.T) {
	type ctxKey struct{} // same name in another scope is a different type
	ctx := context.WithValue(t.Context(), ctxKey{}, &Identity{UserID: 1, Roles: []string{"admin"}})
	ctx = context.WithValue(ctx, "identity", &Identity{UserID: 1})
	if From(ctx) != nil {
		t.Fatal("identity forged with a foreign key")
	}
	if id := From(WithIdentity(ctx, &Identity{UserID: 2})); id == nil || id.UserID != 2 {
		t.Fatal("WithIdentity/From round trip failed")
	}
}

adapterها دو credential این فصل را به RequireUser وصل می‌کنند: SessionAuth دادهٔ متصل‌شده با session.Store.Load را می‌خواند و JWTVerifier دور jwtauth.Issuer.Verify است. تست همان route را با cookie، bearer، token جعلی و session ناشناس اجرا می‌کند.

go
package authmw

import (
	"fmt"
	"net/http"
	"strconv"
	"strings"

	"academy/authentication-in-go/jwtauth"
	"academy/authentication-in-go/session"
)

// SessionAuth reads the session that session.Store.Load attached to the
// context. No cookie or an anonymous session means "no credentials", so the
// next authenticator is tried.
func SessionAuth(r *http.Request) (*Identity, error) {
	sess, ok := session.From(r.Context())
	if !ok || sess.UserID == 0 {
		return nil, ErrNoCredentials
	}
	return &Identity{UserID: sess.UserID, Method: "session"}, nil
}

// JWTVerifier turns a verified access token into an Identity. The subject
// is "user:<id>" as issued by jwtauth.Issuer.Issue.
func JWTVerifier(is *jwtauth.Issuer) func(token string) (*Identity, error) {
	return func(token string) (*Identity, error) {
		c, err := is.Verify(token)
		if err != nil {
			return nil, err
		}
		raw, ok := strings.CutPrefix(c.Subject, "user:")
		id, err := strconv.ParseInt(raw, 10, 64)
		if !ok || err != nil {
			return nil, fmt.Errorf("authmw: unexpected subject %q", c.Subject)
		}
		return &Identity{UserID: id, Roles: c.Roles}, nil
	}
}
go
package authmw

import (
	"crypto/ed25519"
	"crypto/rand"
	"net/http"
	"net/http/httptest"
	"strconv"
	"testing"
	"time"

	"academy/authentication-in-go/jwtauth"
	"academy/authentication-in-go/session"
)

// One API, two credential kinds: a browser with a session cookie and a
// mobile client with a bearer JWT, tried in that fixed order. A bad bearer
// token is a 401, never a fall-through to anonymous.
func TestSessionAndBearerOnOneRoute(t *testing.T) {
	store := session.NewStore(30*time.Minute, 12*time.Hour)
	_, priv, _ := ed25519.GenerateKey(rand.Reader)
	ring := jwtauth.NewKeyRing()
	ring.Add("k1", priv)
	is := &jwtauth.Issuer{Keys: ring, Issuer: "https://auth.example.test", Audience: "orders-api",
		TTL: 10 * time.Minute, Now: time.Now}

	me := http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
		id := From(r.Context())
		w.Write([]byte(id.Method + ":" + strconv.FormatInt(id.UserID, 10)))
	})
	h := store.Load(RequireUser(SessionAuth, Bearer(JWTVerifier(is)))(me))

	call := func(cookie, bearer string) *httptest.ResponseRecorder {
		req := httptest.NewRequest("GET", "/me", nil)
		if cookie != "" {
			req.AddCookie(&http.Cookie{Name: session.CookieName, Value: cookie})
		}
		if bearer != "" {
			req.Header.Set("Authorization", "Bearer "+bearer)
		}
		rec := httptest.NewRecorder()
		h.ServeHTTP(rec, req)
		return rec
	}

	sid := store.Create(7)
	if rec := call(sid, ""); rec.Code != 200 || rec.Body.String() != "session:7" {
		t.Fatalf("cookie: %d %q", rec.Code, rec.Body)
	}
	tok, _ := is.Issue("user:8", "j1", nil)
	if rec := call("", tok); rec.Code != 200 || rec.Body.String() != "bearer:8" {
		t.Fatalf("bearer: %d %q", rec.Code, rec.Body)
	}
	if rec := call("", "forged.token.value"); rec.Code != 401 {
		t.Fatalf("forged bearer: %d", rec.Code)
	}
	anon := store.Create(0)
	if rec := call(anon, ""); rec.Code != 401 {
		t.Fatalf("anonymous session: %d", rec.Code)
	}
	if rec := call("", ""); rec.Code != 401 {
		t.Fatalf("nothing: %d", rec.Code)
	}
}

CSRF: double-submit cookie، SameSite، Origin و http.CrossOriginProtection حیاتی ​

به زبان ساده: در session مبتنی بر cookie، مرورگر cookie را به هر درخواست سایت شما ضمیمه می‌کند، حتی درخواستی که یک فرم روی evil.example راه انداخته باشد. دفاع در برابر جعل درخواست میان‌سایتی (CSRF) به سرور امکان می‌دهد «کاربر روی Transfer در صفحهٔ ما کلیک کرد» را از «سایت دیگری مرورگر کاربر را وادار کرد به ما POST بفرستد» تشخیص دهد.

بدفهمی رایج: «cookieهای SameSite=Lax مسئلهٔ CSRF را حل می‌کنند.» بیشتر POSTهای cross-site را می‌بندند، اما درخواست زیردامنهٔ همسایه را نه (site یکسان، origin متفاوت: blog.example.test علیه bank.example.test)؛ GET تغییردهندهٔ state هم می‌ماند. MDN دربارهٔ Lax صرفاً پیش‌فرض مرورگر می‌گوید "cookies are also included in POST requests, as long as they were set no more than two minutes before the request was made". بدفهمی دوم: «double-submit ساده کافی است.» OWASP آن را DISCOURAGED علامت می‌زند، چون "is bypassable by an attacker who can write cookies on the target domain". token را به session متصل کنید.

تعریف: راهنمای OWASP: "Stateful software should use the synchronizer token pattern" و "Stateless software should use double submit cookies". نوع توصیه‌شده، signed double-submit cookie است، "which explicitly ties tokens to the user's authenticated session (e.g., session ID)"؛ این اتصال با HMAC و کلید سمت سرور انجام می‌شود. SameSite تعیین می‌کند مرورگر اصلاً چه وقت cookie را بفرستد. بررسی مبدأ (Origin check)، header نوع Origin در درخواست unsafe را با origin خودتان یا allow-list مقایسه می‌کند. در Fetch metadata، مرورگرها Sec-Fetch-Site: same-origin | same-site | cross-site | none می‌فرستند. http.CrossOriginProtection در Go 1.25 همین را مصرف می‌کند: methodهای امن GET و HEAD و OPTIONS عبور می‌کنند؛ مقدار same-origin یا none در Sec-Fetch-Site هم عبور می‌کند. بقیه با 403 و cross-origin request detected from Sec-Fetch-Site header رد می‌شوند، مگر origin با AddTrustedOrigin یا route با AddInsecureBypassPattern اضافه شده باشد. در نبود Sec-Fetch-Site، مقدار Origin ناسازگار با Host رد می‌شود. OWASP: "Starting from 1.25, Go developers can rely on the built-in CrossOriginProtection type." شرح کامل middleware در Middlewares است.

     evil.example.test page                       bank.example.test (cookie: __Host-sid=Qz8..)
1    <form action=https://bank.../transfer method=POST> auto-submits
2    browser: SameSite=Lax -> cookie NOT sent on cross-site POST          (first wall)
3    cookie without SameSite: no Lax default (older browser), or the default-Lax 2-minute POST window -> cookie sent
4    Sec-Fetch-Site: cross-site -> CrossOriginProtection 403              (second wall)
5    no fetch metadata, Origin: https://evil.example.test != Host -> 403  (third wall)
6    no Origin at all -> token check: csrf_token missing or not HMAC(session) -> 403  (fourth wall)

سناریوی واقعی: پنل admin با render سمت سرور و فرم‌ها؛ blog بازاریابی روی همان site که XSS دارد و می‌تواند درخواست same-site به برنامه بفرستد؛ SPA روی app.example.test که با cookie به api.example.test درخواست می‌دهد (AddTrustedOrigin)؛ webhook پرداخت که چون مرورگر و cookie ندارد باید CSRF را دور بزند (AddInsecureBypassPattern("POST /webhooks/")، با احراز هویت از طریق signature به‌جای آن)؛ و endpoint خروج که آن هم باید CSRF-protected باشد، وگرنه هر کسی می‌تواند کاربران شما را logout کند.

دفاعچه چیزی را می‌بنددچه چیزی می‌ماندGo
SameSite=Lax صریحPOST و fetch و iframe میان‌سایتیمهاجم same-site، GET تغییردهندهhttp.Cookie.SameSite
نبود SameSite و Lax پیش‌فرضهمان موارد بالا، در مرورگرهایی که Lax را پیش‌فرض اعمال می‌کنندPOST تا دو دقیقهٔ اول و مرورگر بدون Lax پیش‌فرضویژگی را صریح تنظیم کنید
SameSite=Strictعلاوه بر موارد بالا، GET ناوبری سطح بالای cross-siteمهاجم same-site؛ لینک ایمیل به صفحهٔ واردشده را هم می‌شکندhttp.SameSiteStrictMode
CrossOriginProtection (1.25)درخواست unsafe میان‌سایتی و same-site با origin متفاوت، در مرورگرهای جدیدمرورگر قدیمی فاقد Sec-Fetch-Site و فاقد Originhttp.NewCrossOriginProtection()
Origin checkOrigin خارجیدرخواست بدون Originr.Header.Get("Origin") در برابر r.Host
synchronizer / signed double-submitدرخواست فاقد token همان sessionXSS در origin خودتان که token را می‌خواندHMAC در form/header
bearer در AuthorizationCSRF؛ مرورگر خودکار attach نمی‌کندXSS که token storage را می‌دزددauthmw.Bearer

راه‌حل / کاربرد: csrf دارای token نوع HMAC متصل به session و Origin check است؛ فایل با قید //go:build go1.25، CrossOriginProtection را جلوی آن می‌گذارد.

go
// Package csrf protects cookie-authenticated, state-changing requests with a
// session-bound HMAC token (OWASP "signed double-submit cookie" / synchronizer
// token) plus an Origin check. Go 1.25+ code can add
// http.CrossOriginProtection in front (crossorigin.go).
package csrf

import (
	"crypto/hmac"
	"crypto/rand"
	"crypto/sha256"
	"encoding/base64"
	"net/http"
	"net/url"
	"strings"
)

// Protector issues and checks tokens. Secret is 32 random bytes from a
// secret store; SessionID returns the current session's ID (or "" if none).
type Protector struct {
	Secret         []byte
	SessionID      func(r *http.Request) string
	TrustedOrigins map[string]bool // e.g. "https://app.example.test"
}

// Token returns nonce.mac where mac = HMAC-SHA256(secret, sessionID "!" nonce).
// Render it in a hidden form field or a meta tag for fetch().
func (p *Protector) Token(sessionID string) string {
	nonce := make([]byte, 16)
	rand.Read(nonce)
	n := base64.RawURLEncoding.EncodeToString(nonce)
	return n + "." + p.mac(sessionID, n)
}

func (p *Protector) mac(sessionID, nonce string) string {
	m := hmac.New(sha256.New, p.Secret)
	m.Write([]byte(sessionID + "!" + nonce))
	return base64.RawURLEncoding.EncodeToString(m.Sum(nil))
}

func (p *Protector) valid(sessionID, tok string) bool {
	nonce, mac, ok := strings.Cut(tok, ".")
	if !ok || sessionID == "" {
		return false
	}
	return hmac.Equal([]byte(mac), []byte(p.mac(sessionID, nonce))) // constant time
}

// originOK implements the OWASP "verify origin with standard headers" check:
// if Origin is present it must be our own host or a trusted origin.
func (p *Protector) originOK(r *http.Request) bool {
	o := r.Header.Get("Origin")
	if o == "" || o == "null" {
		return o == "" // no Origin: older browser or non-browser; rely on the token
	}
	if p.TrustedOrigins[o] {
		return true
	}
	u, err := url.Parse(o)
	return err == nil && u.Host == r.Host
}

// Middleware rejects unsafe methods without a valid token with 403.
func (p *Protector) Middleware(next http.Handler) http.Handler {
	return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
		switch r.Method {
		case http.MethodGet, http.MethodHead, http.MethodOptions:
			next.ServeHTTP(w, r) // safe methods must not change state
			return
		}
		tok := r.Header.Get("X-CSRF-Token")
		if tok == "" {
			tok = r.PostFormValue("csrf_token")
		}
		if !p.originOK(r) || !p.valid(p.SessionID(r), tok) {
			http.Error(w, "forbidden: CSRF check failed", http.StatusForbidden)
			return
		}
		next.ServeHTTP(w, r)
	})
}
go
//go:build go1.25

package csrf

import "net/http"

// Fetch-metadata layer from the standard library (Go 1.25): rejects non-safe
// requests whose Sec-Fetch-Site is cross-site or same-site, or whose Origin
// does not match Host. It is tokenless; keep the token check for old
// browsers and for same-site-but-cross-origin threats you care about.
func WithCrossOriginProtection(next http.Handler, trusted ...string) (http.Handler, error) {
	cop := http.NewCrossOriginProtection()
	for _, o := range trusted {
		if err := cop.AddTrustedOrigin(o); err != nil {
			return nil, err
		}
	}
	return cop.Handler(next), nil
}
go
package csrf

import (
	"net/http"
	"net/http/httptest"
	"net/url"
	"strings"
	"testing"
)

func setup() (*Protector, http.Handler) {
	p := &Protector{
		Secret:    []byte("0123456789abcdef0123456789abcdef"),
		SessionID: func(r *http.Request) string { return r.Header.Get("X-Test-Session") },
	}
	h := p.Middleware(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
		w.Write([]byte("transferred"))
	}))
	return p, h
}

func post(h http.Handler, session, token, origin string) int {
	form := url.Values{"csrf_token": {token}, "amount": {"100"}}
	req := httptest.NewRequest("POST", "https://bank.example.test/transfer", strings.NewReader(form.Encode()))
	req.Header.Set("Content-Type", "application/x-www-form-urlencoded")
	req.Header.Set("X-Test-Session", session)
	if origin != "" {
		req.Header.Set("Origin", origin)
	}
	rec := httptest.NewRecorder()
	h.ServeHTTP(rec, req)
	return rec.Code
}

func TestTokenBoundToSession(t *testing.T) {
	p, h := setup()
	tok := p.Token("sess-A")
	if c := post(h, "sess-A", tok, "https://bank.example.test"); c != 200 {
		t.Fatalf("own form: %d", c)
	}
	if c := post(h, "sess-A", "", ""); c != 403 {
		t.Fatalf("missing token: %d", c)
	}
	// An attacker's own valid token does not work in the victim's session.
	if c := post(h, "sess-B", tok, ""); c != 403 {
		t.Fatalf("token from another session: %d", c)
	}
	if c := post(h, "sess-A", tok, "https://evil.example.test"); c != 403 {
		t.Fatalf("cross-origin with valid token: %d", c)
	}
}

func TestSafeMethodsPass(t *testing.T) {
	_, h := setup()
	rec := httptest.NewRecorder()
	h.ServeHTTP(rec, httptest.NewRequest("GET", "/transfer", nil))
	if rec.Code != 200 {
		t.Fatalf("GET: %d", rec.Code)
	}
}
go
//go:build go1.25

package csrf

import (
	"net/http"
	"net/http/httptest"
	"testing"
)

func TestCrossOriginProtection(t *testing.T) {
	h, err := WithCrossOriginProtection(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {}),
		"https://admin.example.test")
	if err != nil {
		t.Fatal(err)
	}
	cases := []struct {
		site, origin string
		want         int
	}{
		{"same-origin", "", 200},
		{"cross-site", "https://evil.example.test", 403},
		{"same-site", "https://blog.example.test", 403},
		{"", "https://evil.example.test", 403},            // old browser: Origin vs Host
		{"", "", 200},                                     // curl, server-to-server
		{"cross-site", "https://admin.example.test", 200}, // trusted origin
	}
	for _, c := range cases {
		req := httptest.NewRequest("POST", "https://bank.example.test/transfer", nil)
		if c.site != "" {
			req.Header.Set("Sec-Fetch-Site", c.site)
		}
		if c.origin != "" {
			req.Header.Set("Origin", c.origin)
		}
		rec := httptest.NewRecorder()
		h.ServeHTTP(rec, req)
		if rec.Code != c.want {
			t.Errorf("Sec-Fetch-Site=%q Origin=%q: %d, want %d", c.site, c.origin, rec.Code, c.want)
		}
	}
}

اعتبارسنجی، پاک‌سازی و encoding خروجی حیاتی ​

به زبان ساده: سه کار متفاوت داریم. اعتبارسنجی (Validation) ورودی را در مرز سیستم بررسی و نامتناسب را رد می‌کند («این ایمیل نیست»). پاک‌سازی (Sanitization) HTMLی را تمیز می‌کند که تصمیم گرفته‌اید واقعاً به‌شکل HTML نشان دهید، مثل bio با متن غنی. کدگذاری خروجی (Output encoding) هنگام render، داده را به متن مناسبِ دقیقاً همان context تبدیل می‌کند: بدنهٔ HTML، attribute، URL یا JavaScript. بیشتر باگ‌های XSS از این می‌آیند که یکی را انجام می‌دهیم و فکر می‌کنیم بقیه را هم پوشش داده است.

بدفهمی رایج: «از همهٔ ورودی‌ها < و > را حذف کنیم XSS حل می‌شود.» دادهٔ معتبر مثل a < b را خراب می‌کند؛ حذف quote هم نامی مثل O'Brien را. در ضمن contextهایی را از قلم می‌اندازد که اصلاً angle bracket لازم ندارند: javascript: در href، attribute بدون quote یا رشتهٔ JavaScript. راهنمای XSS در OWASP از output encoding مخصوص هر context شروع می‌کند: "start with your framework's default output encoding protection" و "Each variable used in the user interface should be passed through an output encoding function." بدفهمی دوم: «html/template همه‌چیز را انجام می‌دهد، پس template.HTML(userBio) اشکالی ندارد.» تبدیل به template.HTML به engine می‌گوید «این از قبل امن است»؛ دقیقاً محل همین تبدیل است که sanitization باید انجام شود.

تعریف: Validation یک allow-list برای هر فیلد است (نوع، طول، قالب، بازه) که یک بار در مرز سیستم اعمال می‌شود؛ ابزارهای Go شامل net/mail.ParseAddress، regexp، strconv و utf8.RuneCountInString هستند. Sanitization، HTML را parse می‌کند و فقط element و attribute مجاز را نگه می‌دارد. bluemonday طبق مستندش "takes untrusted user generated content as an input, and will return HTML that has been sanitised against an allowlist of approved HTML elements and attributes". bluemonday.UGCPolicy() نیز "allows a broad selection of HTML elements and attributes that are safe for user generated content"؛ یعنی بدون script و iframe و style. StrictPolicy() همهٔ HTML را حذف می‌کند. دربارهٔ Output encoding در html/template: "HTML templates treat data values as plain text which should be encoded so they can be safely embedded in an HTML document. The escaping is contextual, so actions can appear within JavaScript, CSS, and URI contexts." scheme غیرمجاز URL در attribute به #ZgotmplZ تبدیل می‌شود. text/template اصلاً escaping ندارد. سازوکار template شامل layout و caching و forms در html/template آمده است.

username = "</script><script>alert(1)</script>", website = "javascript:alert(1)", bio = "<b>Go</b><script>..."
1  Validate      username fails ^[a-z0-9_-]{3,32}$ -> 400 at sign-up (in this test we render anyway)
2  SanitizeBio   bluemonday UGC: "<b>Go</b>" kept, <script>, onerror, javascript: removed
3  Render (real output, html/template):
   <h1>&lt;/script&gt;&lt;script&gt;alert(1)&lt;/script&gt;</h1>        HTML text context
   <a href="#ZgotmplZ">site</a>                                         URL attribute: scheme blocked
   <script>const user = "\u003c/script\u003e...";</script>              JS string context

سناریوی واقعی: فیلد comment که روی صفحهٔ عمومی render می‌شود؛ لینک «website» پروفایل؛ search box که عبارت آن در صفحهٔ نتیجه بازنمایی می‌شود؛ داشبورد admin که JSON پایگاه داده را داخل بلوک <script> می‌گذارد؛ template ایمیل ساخته‌شده با text/template (escaping ندارد؛ برای ایمیل HTML از html/template استفاده کنید).

کارزمانابزار Goپیامد حذف
Validation؛ اعتبارسنجیورودی، پیش از ذخیرهnet/mail، regexp، strconv، کنترل طولدادهٔ خراب و فرض ضعیف downstream
Canonicalization؛ همسان‌سازیورودیstrings.ToLower ایمیل، Unicode normalizationحساب تکراری Alice@ و alice@
Sanitization؛ پاک‌سازیفقط فیلدِ قابل render به‌صورت HTMLbluemonday.UGCPolicy().Sanitizestored XSS در متن غنی
Output encoding؛ کدگذاریهر render و هر فیلد در context خودhtml/template با autoescaping وابسته به contextreflected و stored XSS
پارامتر SQLهنگام query$1 در database/sql و pgxSQL injection؛ sanitizer جای این نیست
مقدار headerهنگام بازتاب در headerرد CR/LFheader injection

راه‌حل / کاربرد:

go
// Package sanitize separates three jobs that are often mixed up:
// validation (reject bad input at the edge), sanitization (clean HTML you
// intend to render as HTML), and output encoding (html/template escaping
// everything else at render time).
package sanitize

import (
	"errors"
	"html/template"
	"io"
	"net/mail"
	"regexp"
	"strings"
	"unicode/utf8"

	"github.com/microcosm-cc/bluemonday"
)

var (
	ErrEmail    = errors.New("email: not a valid address")
	ErrUsername = errors.New("username: 3-32 characters, a-z 0-9 _ -")
	ErrBio      = errors.New("bio: at most 2000 characters")
)

var usernameRE = regexp.MustCompile(`^[a-z0-9_-]{3,32}$`)

type Signup struct {
	Email    string
	Username string
	Bio      string // may contain a little HTML (bold, links)
}

// Validate rejects, it does not repair: an allow-list per field.
func (s *Signup) Validate() error {
	addr, err := mail.ParseAddress(s.Email)
	if err != nil || addr.Address != strings.TrimSpace(s.Email) || len(s.Email) > 254 {
		return ErrEmail
	}
	s.Email = strings.ToLower(addr.Address) // canonical form for lookups
	if !usernameRE.MatchString(s.Username) {
		return ErrUsername
	}
	if utf8.RuneCountInString(s.Bio) > 2000 {
		return ErrBio
	}
	return nil
}

// ugc is safe for concurrent use; build it once.
var ugc = bluemonday.UGCPolicy()

// SanitizeBio is only for the field you deliberately render as HTML.
// The result is wrapped in template.HTML so html/template will not escape it
// a second time: that type conversion is the trust decision, so it lives here.
func SanitizeBio(bio string) template.HTML {
	return template.HTML(ugc.Sanitize(bio))
}

var page = template.Must(template.New("profile").Parse(
	`<h1>{{.Username}}</h1><a href="{{.Website}}">site</a><div class="bio">{{.Bio}}</div>
<script>const user = {{.Username}};</script>`))

type Profile struct {
	Username string        // escaped for HTML, and for JS inside <script>
	Website  string        // escaped for a URL attribute; javascript: is neutralised
	Bio      template.HTML // already sanitized
}

func Render(w io.Writer, p Profile) error { return page.Execute(w, p) }
go
package sanitize

import (
	"errors"
	"strings"
	"testing"
)

func TestValidate(t *testing.T) {
	ok := Signup{Email: "Alice@Example.test", Username: "alice_1", Bio: "hi"}
	if err := ok.Validate(); err != nil || ok.Email != "alice@example.test" {
		t.Fatalf("%v %q", err, ok.Email)
	}
	bad := []struct {
		s    Signup
		want error
	}{
		{Signup{Email: "Alice <alice@example.test>", Username: "alice"}, ErrEmail},
		{Signup{Email: "not-an-email", Username: "alice"}, ErrEmail},
		{Signup{Email: "a@example.test", Username: "<script>"}, ErrUsername},
		{Signup{Email: "a@example.test", Username: "al"}, ErrUsername},
		{Signup{Email: "a@example.test", Username: "alice", Bio: strings.Repeat("x", 2001)}, ErrBio},
	}
	for _, c := range bad {
		if err := c.s.Validate(); !errors.Is(err, c.want) {
			t.Errorf("%+v: %v, want %v", c.s, err, c.want)
		}
	}
}

func TestSanitizeBio(t *testing.T) {
	got := string(SanitizeBio(`<b>Go</b> dev <script>alert(1)</script><a href="javascript:alert(1)">x</a><img src=x onerror=alert(1)>`))
	for _, bad := range []string{"<script", "javascript:", "onerror"} {
		if strings.Contains(got, bad) {
			t.Fatalf("sanitized bio still contains %q: %s", bad, got)
		}
	}
	if !strings.Contains(got, "<b>Go</b>") {
		t.Fatalf("allowed markup removed: %s", got)
	}
}

func TestOutputEncodingIsContextual(t *testing.T) {
	var b strings.Builder
	err := Render(&b, Profile{
		Username: `</script><script>alert(1)</script>`,
		Website:  `javascript:alert(1)`,
		Bio:      SanitizeBio(`<i>ok</i>`),
	})
	if err != nil {
		t.Fatal(err)
	}
	out := b.String()
	if strings.Contains(out, "<script>alert(1)") {
		t.Fatalf("username not escaped:\n%s", out)
	}
	if !strings.Contains(out, `href="#ZgotmplZ"`) {
		t.Fatalf("javascript: URL not neutralised:\n%s", out)
	}
	if !strings.Contains(out, "<i>ok</i>") {
		t.Fatalf("sanitized HTML double-escaped:\n%s", out)
	}
	if strings.Contains(out, `const user = "</script>`) || !strings.Contains(out, `u003c/script`) {
		t.Fatalf("JS context not escaped as a JS string:\n%s", out)
	}
}

بازیابی گذرواژه: token یک‌بارمصرف، hash، expiry و پاسخ یکسان حیاتی ​

به زبان ساده: بازیابی گذرواژه (Password reset) یک فرم login دیگر است که password را دور می‌زند؛ همان‌قدر باید محکم باشد. همهٔ ایمیل‌ها یک پاسخ می‌گیرند؛ فقط حساب موجود لینک تصادفی دریافت می‌کند. hash token را ذخیره کنید، اعتبار کوتاه و یک‌بارمصرف بدهید و پس از reset همهٔ sessionها را پایان دهید.

بدفهمی رایج: «لینک reset مستقیم login کند راحت‌تر است.» OWASP: "Don't automatically log the user in, as this introduces additional complexity to the authentication and session handling code". بدفهمی دوم: «token را خام ذخیره کن؛ بالاخره تصادفی است.» آن وقت نشت read-only جدول، مثلاً backup یا replica، به مهاجم اجازه می‌دهد هر حساب دارای درخواست باز را reset کند. بدفهمی سوم: «لینک را از Host درخواست بساز.» OWASP می‌گوید "Don't rely on the Host header while creating the reset URLs to avoid Host Header Injection attacks."

تعریف: راهنمای OWASP Forgot Password می‌گوید "Return a consistent message for both existent and non-existent accounts" و "Ensure that the time taken for the user response message is uniform". tokenها باید "Randomly generated using a cryptographically safe algorithm"، "Sufficiently long to protect against brute-force attacks"، "Stored securely" و "Single use and expire after an appropriate period" باشند. پس از recovery هم باید "invalidate existing sessions and outstanding password reset and recovery links or codes". در این ماژول، هر دو شاخهٔ RequestReset یک token تولید و hash می‌کنند، store را scan می‌کنند و یک job در صف می‌گذارند؛ فقط job، بیرون مسیر درخواست، می‌داند واقعاً باید ایمیل بفرستد یا نه. TestRequestResetSameStepsBothBranches تعداد مراحل هر دو شاخه را می‌شمارد. صفحهٔ reset باید Referrer-Policy: no-referrer بفرستد تا token به resource شخص ثالث نشت نکند. broker پیش‌فرض Laravel از 'expire' => 60 بر حسب دقیقه و 'throttle' => 60 بر حسب ثانیهٔ فاصلهٔ درخواست‌ها استفاده می‌کند.

1  POST /forgot-password email=alice@...      -> 200 "If an account exists for that address, ..."
   POST /forgot-password email=nobody@...     -> 200 "If an account exists for that address, ..." (same)
2  BOTH emails: raw = hex(32 random bytes), sha256(raw), scan the token store, enqueue ONE mail job
   alice only: store sha256(raw), user 1, purpose reset, expires +30 min (older tokens deleted);
   the queued job mails https://app.example.test/reset-password?token=raw, nobody's job sends nothing
3  GET /reset-password?token=raw              -> form (Referrer-Policy: no-referrer)
4  POST new password                          -> consume: look up sha256(raw) AND delete, same critical section
5  expired? -> 400 "invalid or expired link";  ok -> policy check, Argon2id, UPDATE users
6  end all sessions + refresh token families of user 1; send "your password was changed" mail
7  second POST with the same raw              -> 400 (deleted in step 4)
Password reset: same answer for everyone, token usable oncePOST /forgot-passwordemail, rate limited per IP + emailaccount exists?decided silently200 "If an account exists…"identical for both branchesyes (off the response path)token = 32 bytes from crypto/randstore sha256(token), user, purpose, expires = now + 30 mindelete older tokens; link from BaseURL config, never Host headeruser opens /reset-password?token=… (Referrer-Policy: no-referrer)consume: look up + deletein one transaction; thencheck expirypolicy check, Argon2id hashUPDATE users SETpassword_hash = …revoke every sessionand refresh token family;notify by email; no auto-loginEmail verification uses the same table with purpose = email_verification and a longer expiry.

سناریوی واقعی: مهاجمی که فرم forgot-password را با اسکریپت می‌زند تا بفهمد کدام ایمیل حساب دارد؛ token بازیابی که از header نوع Referer به script تحلیل بازدید نشت می‌کند؛ لینکی که در ticket پشتیبانی برای مهاجم forward شده و او پیش از کاربر مصرفش می‌کند؛ کاربری که پس از phishing، reset می‌کند اما مهاجم هنوز session دارد (این session در گام 6 پایان می‌یابد)؛ و دو tab که هم‌زمان همان لینک را submit می‌کنند و دقیقاً یکی برنده می‌شود.

ویژگیقاعدهاین ماژولPassword broker در Laravel 13
پاسخبرای ایمیل موجود و ناشناخته یکسانreset.GenericPassword::sendResetLink status متفاوت می‌دهد؛ برای همه پیام یکسان نمایش دهید
tokenCSPRNG و طول کافی؛ 128+ بیت256 بیتتولید broker
ذخیرهفقط hashsha256(raw)driver نوع database (جدول token از migration پیش‌فرض کاربران) یا driver نوع cache
عمرکوتاه30 minexpire برابر 60 min
مصرف یگانهحذف اتمیک هنگام مصرفconsume زیر lockپس از reset حذف می‌شود
rate limitایمیل و IPlockoutthrottle برابر 60 s
پس از resetپایان session، ابطال token، اطلاع‌رسانیcallback نوع EndSessionرویداد PasswordReset
host لینکconfigBaseURLAPP_URL

راه‌حل / کاربرد:

go
// Package reset implements single-use, expiring, hashed tokens for password
// reset and email verification, with responses that do not reveal whether
// an account exists.
package reset

import (
	"crypto/rand"
	"crypto/sha256"
	"encoding/hex"
	"errors"
	"strings"
	"sync"
	"sync/atomic"
	"time"
)

type Purpose string

const (
	PurposeReset  Purpose = "password_reset"
	PurposeVerify Purpose = "email_verification"
)

// Generic is the only answer the "forgot password" form ever gives.
const Generic = "If an account exists for that address, we have sent a link to reset the password."

var ErrInvalidToken = errors.New("reset: invalid or expired link")

type token struct {
	userID  int64
	purpose Purpose
	email   string // the address the link was sent to (verification binds to it)
	expires time.Time
}

// Users is the slice of the user repository this package needs.
type Users interface {
	IDByEmail(email string) (int64, bool)
	SetPassword(userID int64, plain string) error // hashes with Argon2id
	MarkVerified(userID int64) error
	EmailOf(userID int64) string // current address, to check a verification link still applies
}

type Service struct {
	Users      Users
	Send       func(email, link string) // the actual mail call, run inside a queued job
	Enqueue    func(job func())         // background queue; New runs jobs inline (tests)
	EndSession func(userID int64)       // session.Store.DestroyUser + refresh.RevokeUser
	BaseURL    string                   // from config, never from the Host header
	TTL        time.Duration            // 30 min for reset; 24 h is common for verification
	Now        func() time.Time

	Issued atomic.Int64 // tokens generated, for the uniform-work test

	mu     sync.Mutex
	byHash map[string]token // SHA-256(token) -> record
}

func New(u Users, send func(string, string), end func(int64), baseURL string) *Service {
	return &Service{Users: u, Send: send, EndSession: end, BaseURL: baseURL,
		Enqueue: func(job func()) { job() },
		TTL:     30 * time.Minute, Now: time.Now, byHash: map[string]token{}}
}

func digest(t string) string { s := sha256.Sum256([]byte(t)); return hex.EncodeToString(s[:]) }

// issue generates a token and, for a real user (userID != 0), stores only
// its hash. For an unknown address the same generation, hashing and store
// scan run, and nothing is stored: both branches cost the same.
func (s *Service) issue(userID int64, p Purpose, email string) string {
	b := make([]byte, 32)
	rand.Read(b)
	raw := hex.EncodeToString(b)
	h := digest(raw)
	s.Issued.Add(1)
	s.mu.Lock()
	for k, t := range s.byHash { // one live token per user and purpose
		if t.userID == userID && t.purpose == p {
			delete(s.byHash, k)
		}
	}
	if userID != 0 {
		s.byHash[h] = token{userID: userID, purpose: p, email: email, expires: s.Now().Add(s.TTL)}
	}
	s.mu.Unlock()
	return raw
}

// RequestReset always returns Generic and does the same work on the request
// path for known and unknown addresses: one token generated, one job
// enqueued. Only the job (off the request path) decides whether to mail.
func (s *Service) RequestReset(email string) string {
	email = strings.ToLower(strings.TrimSpace(email))
	id, ok := s.Users.IDByEmail(email)
	raw := s.issue(id, PurposeReset, email) // id is 0 when unknown
	link := s.BaseURL + "/reset-password?token=" + raw
	s.Enqueue(func() {
		if ok {
			s.Send(email, link)
		}
	})
	return Generic
}

// consume deletes the token in the same critical section that checks it, so
// two concurrent submissions cannot both succeed.
func (s *Service) consume(raw string, p Purpose) (token, error) {
	s.mu.Lock()
	defer s.mu.Unlock()
	h := digest(raw)
	t, ok := s.byHash[h]
	if !ok || t.purpose != p {
		return token{}, ErrInvalidToken
	}
	delete(s.byHash, h)
	if s.Now().After(t.expires) {
		return token{}, ErrInvalidToken
	}
	return t, nil
}

// ConfirmReset sets the new password and ends every session and refresh
// token of the user. It does not log the user in.
func (s *Service) ConfirmReset(raw, newPassword string) error {
	t, err := s.consume(raw, PurposeReset)
	if err != nil {
		return err
	}
	if err := s.Users.SetPassword(t.userID, newPassword); err != nil {
		return err
	}
	s.EndSession(t.userID)
	return nil
}

// SendVerification and ConfirmEmail reuse the same mechanism.
func (s *Service) SendVerification(userID int64, email string) {
	email = strings.ToLower(strings.TrimSpace(email))
	raw := s.issue(userID, PurposeVerify, email)
	link := s.BaseURL + "/verify-email?token=" + raw
	s.Enqueue(func() { s.Send(email, link) })
}

// ConfirmEmail verifies the address the link was sent to, and only if it is
// still the user's address: a link sent before an email change is void.
func (s *Service) ConfirmEmail(raw string) error {
	t, err := s.consume(raw, PurposeVerify)
	if err != nil {
		return err
	}
	if !strings.EqualFold(s.Users.EmailOf(t.userID), t.email) {
		return ErrInvalidToken
	}
	return s.Users.MarkVerified(t.userID)
}
go
package reset

import (
	"errors"
	"net/url"
	"strings"
	"sync"
	"testing"
	"time"
)

type fakeUsers struct {
	mu       sync.Mutex
	pw       map[int64]string
	verified map[int64]bool
	email    map[int64]string
}

func (f *fakeUsers) IDByEmail(e string) (int64, bool) {
	if e == "alice@example.test" {
		return 1, true
	}
	return 0, false
}
func (f *fakeUsers) SetPassword(id int64, p string) error {
	f.mu.Lock()
	f.pw[id] = p
	f.mu.Unlock()
	return nil
}
func (f *fakeUsers) MarkVerified(id int64) error { f.verified[id] = true; return nil }
func (f *fakeUsers) EmailOf(id int64) string     { return f.email[id] }

type outbox struct {
	mu    sync.Mutex
	links []string
}

func (o *outbox) send(_, link string) { o.mu.Lock(); o.links = append(o.links, link); o.mu.Unlock() }

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

func newSvc() (*Service, *fakeUsers, *outbox, *[]int64) {
	u := &fakeUsers{pw: map[int64]string{}, verified: map[int64]bool{}, email: map[int64]string{1: "alice@example.test"}}
	o := &outbox{}
	ended := &[]int64{}
	s := New(u, o.send, func(id int64) { *ended = append(*ended, id) }, "https://app.example.test")
	return s, u, o, ended
}

func TestEnumerationSafeResponse(t *testing.T) {
	s, _, o, _ := newSvc()
	a := s.RequestReset("Alice@Example.test ")
	b := s.RequestReset("nobody@example.test")
	if a != b || a != Generic {
		t.Fatalf("responses differ: %q vs %q", a, b)
	}
	if len(o.links) != 1 || !strings.HasPrefix(o.links[0], "https://app.example.test/reset-password?token=") {
		t.Fatalf("links: %v", o.links)
	}
}

func TestSingleUseHashedAndSessionsEnded(t *testing.T) {
	s, u, o, ended := newSvc()
	s.RequestReset("alice@example.test")
	raw := tokenFrom(t, o.links[0])
	for k := range s.byHash {
		if k == raw {
			t.Fatal("raw token stored")
		}
	}
	if err := s.ConfirmReset(raw, "a brand new long passphrase"); err != nil {
		t.Fatal(err)
	}
	if u.pw[1] != "a brand new long passphrase" || len(*ended) != 1 {
		t.Fatalf("password %q, sessions ended %v", u.pw[1], *ended)
	}
	if err := s.ConfirmReset(raw, "second use"); !errors.Is(err, ErrInvalidToken) {
		t.Fatalf("second use: %v", err)
	}
}

func TestExpiryAndNewerTokenWins(t *testing.T) {
	now := time.Date(2026, 11, 28, 9, 0, 0, 0, time.UTC)
	s, _, o, _ := newSvc()
	s.Now = func() time.Time { return now }
	s.RequestReset("alice@example.test")
	s.RequestReset("alice@example.test")
	first, second := tokenFrom(t, o.links[0]), tokenFrom(t, o.links[1])
	if err := s.ConfirmReset(first, "x"); !errors.Is(err, ErrInvalidToken) {
		t.Fatal("older link still valid after a newer one was sent")
	}
	now = now.Add(31 * time.Minute)
	if err := s.ConfirmReset(second, "x"); !errors.Is(err, ErrInvalidToken) {
		t.Fatal("expired link accepted")
	}
}

func TestConcurrentConfirmHasOneWinner(t *testing.T) {
	s, _, o, _ := newSvc()
	s.RequestReset("alice@example.test")
	raw := tokenFrom(t, o.links[0])
	var wg sync.WaitGroup
	var mu sync.Mutex
	wins := 0
	for range 10 {
		wg.Add(1)
		go func() {
			defer wg.Done()
			if s.ConfirmReset(raw, "concurrent passphrase") == nil {
				mu.Lock()
				wins++
				mu.Unlock()
			}
		}()
	}
	wg.Wait()
	if wins != 1 {
		t.Fatalf("%d winners", wins)
	}
}

func TestEmailVerificationPurposeIsSeparate(t *testing.T) {
	s, u, o, _ := newSvc()
	s.SendVerification(1, "alice@example.test")
	raw := tokenFrom(t, o.links[0])
	if err := s.ConfirmReset(raw, "x"); !errors.Is(err, ErrInvalidToken) {
		t.Fatal("verification token accepted as a reset token")
	}
	s.SendVerification(1, "alice@example.test")
	if err := s.ConfirmEmail(tokenFrom(t, o.links[1])); err != nil || !u.verified[1] {
		t.Fatalf("verify: %v", err)
	}
}
go
package reset

import (
	"errors"
	"testing"
)

// The verification link proves control of the address it was sent to. If
// the user changed the address meanwhile, the old link must not verify.
func TestVerificationBoundToAddress(t *testing.T) {
	s, u, o, _ := newSvc()
	u.email = map[int64]string{1: "alice@example.test"}
	s.SendVerification(1, "alice@example.test")
	oldLink := tokenFrom(t, o.links[0])
	u.email[1] = "alice@new.example.test" // address changed after the mail went out
	if err := s.ConfirmEmail(oldLink); !errors.Is(err, ErrInvalidToken) {
		t.Fatalf("old-address token verified the new address: err=%v verified=%v", err, u.verified[1])
	}
	if u.verified[1] {
		t.Fatal("marked verified")
	}
	s.SendVerification(1, "alice@new.example.test")
	if err := s.ConfirmEmail(tokenFrom(t, o.links[1])); err != nil || !u.verified[1] {
		t.Fatalf("new address: %v", err)
	}
}

// Both branches of RequestReset must do the same work on the request path:
// one token generated and one mail job enqueued; only the job decides
// whether a mail is actually sent.
func TestRequestResetSameStepsBothBranches(t *testing.T) {
	s, _, _, _ := newSvc()
	var jobs int
	s.Enqueue = func(job func()) { jobs++; job() }
	s.RequestReset("alice@example.test")
	known, knownJobs := s.Issued.Load(), jobs
	s.RequestReset("nobody@example.test")
	if got := s.Issued.Load() - known; got != known {
		t.Fatalf("tokens generated: known=%d unknown=%d", known, got)
	}
	if jobs-knownJobs != knownJobs {
		t.Fatalf("jobs enqueued: known=%d unknown=%d", knownJobs, jobs-knownJobs)
	}
}

تأیید ایمیل مهم ​

به زبان ساده: تأیید ایمیل (Email verification) نشان می‌دهد ثبت‌نام‌کننده آدرس را کنترل می‌کند؛ پیش از اعتماد برای reset و اعلان یا login ایمیلی لازم است. همان سازوکار token بازیابی است با purpose متفاوت و عمر بیشتر.

بدفهمی رایج: «لینک verification را می‌شود تکرار کرد، فقط flag عوض می‌کند.» اگر آن لینک login هم می‌کند، credential ورود است و همان مراقبت را می‌خواهد. token یک purpose هم نباید در purpose دیگر پذیرفته شود؛ تست، verification token را در reset رد می‌کند.

تعریف: token تصادفی، hash‌شده، متصل به user و purpose و آدرس ایمیل، یک‌بارمصرف و معمولاً چندساعته است. تغییر ایمیل برای آدرس جدید token جدا می‌سازد و به قبلی اطلاع می‌دهد. email_verified در ID tokenهای OIDC همین معنا را دارد.

1  sign-up alice@example.test -> user 1, email_verified = false
2  SendVerification(1, email) -> sha256(raw), purpose email_verification, expires +24 h
3  click link -> ConfirmEmail(raw) -> consume (purpose must match) -> MarkVerified(1)
4  same raw used on /reset-password -> rejected: purpose mismatch

سناریوی واقعی: بازارگاهی که نباید payout را به ایمیل تأییدنشده بفرستد؛ تصاحب حسابی که در آن مهاجم زودتر با آدرس قربانی ثبت‌نام می‌کند (verification مانع قابل‌استفاده شدن آن حساب می‌شود)؛ تغییر ایمیل روی حساب موجود؛ و ورود با «magic link»، یعنی token از جنس verification که session می‌دهد و بنابراین expiry کوتاه، مصرف یک‌باره و rotation نشست می‌خواهد.

نوع tokenpurposeexpiry معمولsession می‌دهد؟
reset گذرواژهpassword_reset30-60 minخیر؛ سپس login
تأیید ایمیلemail_verification24 hخیر
تأیید تغییر ایمیلemail_change1-24 hخیر
magic link ورودlogin10-15 minبله؛ rotation و مراقبت مثل password

راه‌حل / کاربرد: همان سازوکار reset را با purpose مخصوص خودش دوباره استفاده کنید: reset.Service.SendVerification هنگام ثبت‌نام و تغییر ایمیل، و ConfirmEmail هنگام مراجعه به لینک. رکورد token، آدرسی را که لینک به آن ارسال شده ذخیره می‌کند. ConfirmEmail فقط وقتی کاربر را تأیید می‌کند که آدرس هنوز آدرس فعلی او باشد (Users.EmailOf)؛ پس لینک ارسال‌شده پیش از تغییر ایمیل باطل است. TestEmailVerificationPurposeIsSeparate و TestVerificationBoundToAddress در فایل‌های تست reset بالاتر، صریحاً ثابت می‌کنند verification token در endpoint بازیابی و در صورت تغییر آدرس رد می‌شود. اجازهٔ کارهای حساس را به email_verified وابسته کنید، نه صرف وجود حساب.

محدودسازی حساب و نرخ تلاش مهم ​

به زبان ساده: قفل حساب (Account lockout) باید شکست‌های تکراری روی یک حساب را کند کند، مثلاً کسی که password مربوط به alice را حدس می‌زند. محدودسازی نرخ (Rate limiting) هم تلاش‌های مکرر یک مبدأ را کند می‌کند، مثلاً کسی که فهرست password افشاشده را روی حساب‌های متعدد می‌آزماید. این کار نباید به مهاجم امکان بدهد عمداً کاربران واقعی را بیرون نگه دارد.

بدفهمی رایج: «پس از پنج شکست، حساب را 24 ساعت قفل کن.» این برای هر مهاجم یک دکمهٔ قفل‌کردن هر کاربر است. OWASP می‌خواهد مراقب باشیم "to prevent it from being used to cause a denial of service by locking out other users' accounts". تأخیر نمایی که با موفقیت reset می‌شود بهتر است. بدفهمی دوم: «فقط بر اساس IP محدود کن.» OWASP: "The counter of failed logins should be associated with the account itself, rather than the source IP address". botnetها IP عوض می‌کنند؛ از طرف دیگر محدودیت IP همچنان برای credential stuffing که برای هر حساب فقط یک password امتحان می‌کند لازم است. بدفهمی سوم: «فقط حساب‌های واقعی را محدود کن.» آن وقت خود 429 به مهاجم می‌گوید کدام ایمیل موجود است؛ شمارنده را با چیزی که تایپ شده کلیدگذاری کنید.

تعریف: Account lockout این‌جا تأخیر به‌ازای شناسه است: پس از Free شکست، Base صبر کنید و برای هر شکست بعدی آن را دوبرابر کنید تا سقف Max. OWASP توصیف می‌کند "an exponential lockout, where the lockout duration starts as a very short period (e.g., one second), but doubles after each failed login attempt". محدودسازی IP کلاینت یک سطل توکن (Token bucket) است: rate.NewLimiter(rate.Every(2*time.Second), 20) از golang.org/x/time/rate؛ الگوریتم‌ها در Rate Limiting in Go هستند. NIST SP 800-63B-4 سقف شکست متوالی را "to no more than 100" تعیین می‌کند و انتظار افزایشی را پیشنهاد می‌کند: "(e.g., 30 seconds up to an hour)". پاسخ 429 Too Many Requests با Retry-After بدهید.

alice@example.test, attempts from rotating IPs
1-5   fail, fail, fail, fail, fail        no delay (Free = 5)
6     fail                                -> wait 1 s
7,8   fail, fail                          -> wait 2 s, then 4 s
...   30 more failures                    -> capped at 15 min (never permanent)
ok    correct password after the wait     -> counter cleared
one IP, 100 different accounts            -> 20 allowed (burst), then 1 per 2 s

سناریوی واقعی: credential stuffing با combo list دو میلیون‌خطی حاصل از رخنهٔ سایت دیگر؛ حدس هدفمند حساب CEO؛ مشتری که یادش نیست password کاری یا شخصی را استفاده کرده و شش بار شکست می‌خورد؛ NAT سازمانی که 2,000 کارمند یک IP مشترک دارند (burst محدودیت IP را متناسب بگذارید یا از کلید IP + account استفاده کنید).

کنترلکلیدچه چیزی را می‌بنددخطر
تأخیر نماییشناسهٔ normalizeشده، موجود یا ناموجودحدس هدفمندDoS خفیف با سقف Max
قفل سختحسابحدس هدفمندقفل عمدی کاربران
token bucketIP کلاینتstuffing از چند IPتشخیص غلط NAT
بررسی password افشاشدهpasswordاستفادهٔ مجدد secret افشاشدهنگه‌داری blocklist
CAPTCHA پس از N شکستsession/IPbotسرویس حل دارد؛ هزینهٔ UX
MFAحسابتقریباً همهٔ حملات passwordهزینهٔ enrolment و recovery

راه‌حل / کاربرد:

go
// Package lockout throttles login attempts two ways: per account identifier
// (exponential delay after a few failures, keyed on what was typed, whether
// or not the account exists) and per client IP (token bucket from
// golang.org/x/time/rate) against credential stuffing across many accounts.
package lockout

import (
	"strings"
	"sync"
	"time"

	"golang.org/x/time/rate"
)

type entry struct {
	failures int
	until    time.Time
}

type Guard struct {
	Free     int           // failures allowed before delays start, e.g. 5
	Base     time.Duration // first delay, e.g. 1 s; doubles per further failure
	Max      time.Duration // cap, e.g. 15 min: a delay, never a permanent lock
	PerIP    rate.Limit    // e.g. rate.Every(2 * time.Second)
	IPBurst  int           // e.g. 20
	Now      func() time.Time
	mu       sync.Mutex
	accounts map[string]*entry
	ips      map[string]*rate.Limiter
}

func New() *Guard {
	return &Guard{Free: 5, Base: time.Second, Max: 15 * time.Minute,
		PerIP: rate.Every(2 * time.Second), IPBurst: 20, Now: time.Now,
		accounts: map[string]*entry{}, ips: map[string]*rate.Limiter{}}
}

func norm(id string) string { return strings.ToLower(strings.TrimSpace(id)) }

// Allow returns 0 if the attempt may proceed, or how long to wait (for a
// 429 with Retry-After). Call it before verifying the password.
func (g *Guard) Allow(account, ip string) time.Duration {
	g.mu.Lock()
	defer g.mu.Unlock()
	now := g.Now()
	if e := g.accounts[norm(account)]; e != nil && now.Before(e.until) {
		return e.until.Sub(now)
	}
	lim := g.ips[ip]
	if lim == nil {
		lim = rate.NewLimiter(g.PerIP, g.IPBurst)
		g.ips[ip] = lim
	}
	r := lim.ReserveN(now, 1)
	if d := r.DelayFrom(now); d > 0 {
		r.CancelAt(now)
		return d
	}
	return 0
}

// Fail records a failed attempt for the identifier.
func (g *Guard) Fail(account string) {
	g.mu.Lock()
	defer g.mu.Unlock()
	k := norm(account)
	e := g.accounts[k]
	if e == nil {
		e = &entry{}
		g.accounts[k] = e
	}
	e.failures++
	if n := e.failures - g.Free; n > 0 {
		d := g.Base << min(n-1, 20)
		e.until = g.Now().Add(min(d, g.Max))
	}
}

// Succeed clears the account counter.
func (g *Guard) Succeed(account string) {
	g.mu.Lock()
	delete(g.accounts, norm(account))
	g.mu.Unlock()
}
go
package lockout

import (
	"fmt"
	"testing"
	"time"
)

func TestExponentialDelayPerAccount(t *testing.T) {
	now := time.Date(2026, 11, 28, 9, 0, 0, 0, time.UTC)
	g := New()
	g.Now = func() time.Time { return now }
	for i := range 5 {
		if d := g.Allow("alice@example.test", fmt.Sprintf("10.0.0.%d", i)); d != 0 {
			t.Fatalf("attempt %d delayed %v", i, d)
		}
		g.Fail("alice@example.test")
	}
	g.Fail("Alice@Example.test") // 6th failure: 1 s
	if d := g.Allow("alice@example.test", "10.0.1.1"); d != time.Second {
		t.Fatalf("after 6 failures: %v", d)
	}
	now = now.Add(time.Second)
	g.Fail("alice@example.test") // 7th: 2 s
	g.Fail("alice@example.test") // 8th: 4 s
	if d := g.Allow("alice@example.test", "10.0.1.2"); d != 4*time.Second {
		t.Fatalf("after 8 failures: %v", d)
	}
	for range 30 {
		g.Fail("alice@example.test")
	}
	if d := g.Allow("alice@example.test", "10.0.1.3"); d != 15*time.Minute {
		t.Fatalf("cap: %v", d)
	}
	g.Succeed("alice@example.test")
	if d := g.Allow("alice@example.test", "10.0.1.4"); d != 0 {
		t.Fatalf("after success: %v", d)
	}
}

func TestUnknownAccountsAreThrottledToo(t *testing.T) {
	g := New()
	for range 6 {
		g.Fail("nobody@example.test") // the account does not exist
	}
	if d := g.Allow("nobody@example.test", "10.0.0.9"); d == 0 {
		t.Fatal("non-existent account not throttled: that difference leaks existence")
	}
}

func TestPerIPBucketStopsStuffing(t *testing.T) {
	now := time.Date(2026, 11, 28, 9, 0, 0, 0, time.UTC)
	g := New()
	g.Now = func() time.Time { return now }
	allowed := 0
	for i := range 100 { // 100 different accounts from one IP
		if g.Allow(fmt.Sprintf("user%d@example.test", i), "203.0.113.7") == 0 {
			allowed++
		}
	}
	if allowed != 20 {
		t.Fatalf("burst allowed %d, want 20", allowed)
	}
	if g.Allow("x@example.test", "198.51.100.1") != 0 {
		t.Fatal("another IP was throttled")
	}
}

MFA با TOTP: pquerna/otp و RFC 6238 مهم ​

به زبان ساده: در گذرواژهٔ یک‌بارمصرف زمانی (TOTP)، تلفن و سرور secret مشترک دارند و هر 30 ثانیه کد 6 رقمی از آن و زمان می‌سازند. همراه password، سرقت password به‌تنهایی کافی نیست؛ کاربر باید کد عامل دوم (MFA) را هم داشته باشد.

بدفهمی رایج: «totp.Validate کافی است.» این تابع گام فعلی و یک گام طرفین را می‌پذیرد اما state ندارد؛ کد در همان پنجره دوباره معتبر است. RFC 6238 می‌گوید "The verifier MUST NOT accept the second attempt of the OTP after the successful validation has been issued for the first OTP". آخرین گام پذیرفته‌شدهٔ هر کاربر را نگه دارید. TOTP ضد phishing هم نیست؛ proxy زنده کد را در 30 ثانیه منتقل می‌کند. passkey متصل به origin این حمله را می‌بندد.

تعریف: TOTP همان HOTP از RFC 4226 با شمارندهٔ T = floor((now - T0) / X) است؛ RFC 6238 گام X برابر 30 ثانیه و حداکثر یک گام تأخیر شبکه را توصیه می‌کند. pquerna/otp/totp با Generate(GenerateOpts{Issuer, AccountName}) کلیدی می‌دهد با Secret() نوع base32، URL() به‌شکل otpauth://totp/... برای QR و Image(). Validate(passcode, secret) از Period 30 و Skew 1 استفاده می‌کند؛ ValidateCustom و GenerateCodeCustom گزینه‌های ValidateOpts{Period, Skew, Digits, Algorithm} می‌گیرند. enrolment شامل تولید، نمایش، آزمودن کد کاربر، ذخیره و تحویل کد بازیابی (Recovery code) است. این‌جا crypto/rand.Text() از Go 1.24 حداقل 128 بیت randomness می‌دهد؛ SHA-256 برای ذخیرهٔ recovery code کافی است، چون NIST فقط lookup secret کمتر از 112 بیت را نیازمند password hashing می‌داند.

secret S shared at enrolment (QR code: otpauth://totp/Academy:alice@example.test?secret=...&issuer=Academy)
1  09:00:10  phone: HOTP(S, 1795856410/30 = 59861880) = 492039 (illustrative); user types it
2  server    counters 59861880±1 -> match at 59861880 > last(0) -> accept, last = 59861880
3  09:00:15  same 492039 again (phished, replayed) -> match at 59861880 <= last -> reject
4  09:00:45  code from step 59861880 still in skew window, but already used -> reject
5  09:01:00  new step 59861882 -> new code -> accept

سناریوی واقعی: MFA اجباری کارکنان admin که طبق NIST می‌توانند password هشت‌کاراکتری داشته باشند؛ تلفن گم‌شده و recovery code؛ مهاجم passwordدار که پشت TOTP می‌ماند؛ بررسی تقویتی (Step-up) برای تغییر مقصد پرداخت.

عاملمقاوم به phishingsecret مشترک روی سروربستهٔ Go
SMS OTPخیرکد در انتقالSDK ارائه‌دهنده
Email OTPخیرکد در انتقالnet/smtp یا provider
TOTP در RFC 6238خیربله؛ encrypt at restgithub.com/pquerna/otp/totp
recovery codeخیرفقط hashcrypto/rand.Text و SHA-256
Passkeys / WebAuthnبله؛ متصل به originخیر؛ فقط public keygithub.com/go-webauthn/webauthn

راه‌حل / کاربرد:

go
// Package mfa adds TOTP (RFC 6238) as a second factor with
// github.com/pquerna/otp, plus the replay check the RFC requires and
// hashed single-use recovery codes.
package mfa

import (
	"crypto/rand"
	"crypto/sha256"
	"crypto/subtle"
	"encoding/hex"
	"sync"
	"time"

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

// Opts are the RFC 6238 defaults every authenticator app understands:
// 30-second step, 6 digits, HMAC-SHA1, one step of skew either way.
var Opts = totp.ValidateOpts{Period: 30, Skew: 1, Digits: otp.DigitsSix, Algorithm: otp.AlgorithmSHA1}

// Enroll creates a secret and the otpauth:// URL to show as a QR code.
// Store key.Secret() encrypted at rest; activate only after Verify succeeds once.
func Enroll(issuer, account string) (*otp.Key, error) {
	return totp.Generate(totp.GenerateOpts{Issuer: issuer, AccountName: account})
}

// Verifier remembers the last accepted time step per user. totp.Validate
// alone accepts the same code again inside its window; RFC 6238 says the
// verifier "MUST NOT accept the second attempt of the OTP after the
// successful validation has been issued for the first OTP".
type Verifier struct {
	mu   sync.Mutex
	last map[int64]int64 // userID -> last accepted counter
}

func NewVerifier() *Verifier { return &Verifier{last: map[int64]int64{}} }

func (v *Verifier) Verify(userID int64, secret, code string, now time.Time) bool {
	step := int64(Opts.Period)
	counter := now.Unix() / step
	v.mu.Lock()
	defer v.mu.Unlock()
	for off := -int64(Opts.Skew); off <= int64(Opts.Skew); off++ {
		c := counter + off
		want, err := totp.GenerateCodeCustom(secret, time.Unix(c*step, 0), Opts)
		if err != nil {
			return false
		}
		if subtle.ConstantTimeCompare([]byte(want), []byte(code)) == 1 {
			if c <= v.last[userID] {
				return false // replayed or older than the last accepted code
			}
			v.last[userID] = c
			return true
		}
	}
	return false
}

// RecoveryCodes returns n codes for the user to print and their SHA-256
// hashes to store. rand.Text (Go 1.24) gives 26 base32 characters, at least
// 128 bits, so a fast hash is enough; a short code would need a password hash.
func RecoveryCodes(n int) (plain, hashes []string) {
	for range n {
		c := rand.Text()
		plain = append(plain, c)
		hashes = append(hashes, hashCode(c))
	}
	return plain, hashes
}

func hashCode(c string) string { s := sha256.Sum256([]byte(c)); return hex.EncodeToString(s[:]) }

// UseRecoveryCode removes the matching hash (single use) and reports success.
func UseRecoveryCode(stored []string, code string) ([]string, bool) {
	h := hashCode(code)
	for i, s := range stored {
		if subtle.ConstantTimeCompare([]byte(s), []byte(h)) == 1 {
			return append(stored[:i:i], stored[i+1:]...), true
		}
	}
	return stored, false
}
go
package mfa

import (
	"strings"
	"testing"
	"time"

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

func TestEnrollAndVerify(t *testing.T) {
	key, err := Enroll("Academy", "alice@example.test")
	if err != nil {
		t.Fatal(err)
	}
	if !strings.HasPrefix(key.URL(), "otpauth://totp/Academy:alice@example.test?") {
		t.Fatalf("url %s", key.URL())
	}
	now := time.Date(2026, 11, 28, 9, 0, 10, 0, time.UTC)
	code, _ := totp.GenerateCodeCustom(key.Secret(), now, Opts)

	v := NewVerifier()
	if !v.Verify(1, key.Secret(), code, now) {
		t.Fatal("valid code rejected")
	}
	if v.Verify(1, key.Secret(), code, now.Add(5*time.Second)) {
		t.Fatal("same code accepted twice: replay")
	}
	// The library alone would have accepted the replay:
	if ok, _ := totp.ValidateCustom(code, key.Secret(), now.Add(5*time.Second), Opts); !ok {
		t.Fatal("expected pquerna/otp to accept it (no replay state)")
	}
}

func TestSkewWindow(t *testing.T) {
	key, _ := Enroll("Academy", "bob@example.test")
	issued := time.Date(2026, 11, 28, 9, 0, 0, 0, time.UTC)
	code, _ := totp.GenerateCodeCustom(key.Secret(), issued, Opts)
	if !NewVerifier().Verify(2, key.Secret(), code, issued.Add(45*time.Second)) {
		t.Fatal("code from the previous step rejected (skew 1)")
	}
	if NewVerifier().Verify(2, key.Secret(), code, issued.Add(95*time.Second)) {
		t.Fatal("code three steps old accepted")
	}
}

func TestRecoveryCodesSingleUse(t *testing.T) {
	plain, stored := RecoveryCodes(10)
	if len(plain) != 10 || len(plain[0]) != 26 {
		t.Fatalf("codes %v", plain)
	}
	stored, ok := UseRecoveryCode(stored, plain[3])
	if !ok || len(stored) != 9 {
		t.Fatal("valid recovery code rejected")
	}
	if _, ok := UseRecoveryCode(stored, plain[3]); ok {
		t.Fatal("recovery code used twice")
	}
}

Passkey و WebAuthn: راهنمای go-webauthn تکمیلی ​

به زبان ساده: کلید عبور (Passkey) یک جفت‌کلید است که دستگاه برای سایت شما می‌سازد. سرور فقط public key دارد؛ در login، دستگاه پس از اثر انگشت، چهره یا PIN یک challenge را امضا می‌کند. secret مشترکی برای سرقت، reuse یا phishing ندارید.

بدفهمی رایج: «passkey فقط کد 2FA دیگر است.» می‌تواند جای password را بگیرد یا عامل دوم باشد. مرورگر آن را به origin متصل می‌کند؛ دامنهٔ مشابه نمی‌تواند مصرفش کند. کتابخانه هم storage شما را انجام نمی‌دهد: credential شامل ID، public key، sign count و flags باید برای هر کاربر و جدا بر حسب Relying Party ID ذخیره شود؛ README بر partition بر اساس RPID تأکید دارد.

تعریف: در github.com/go-webauthn/webauthn/webauthn، تنظیم webauthn.New(&webauthn.Config{RPID, RPDisplayName, RPOrigins}) دست‌کم RPID و RPOrigins می‌خواهد. دو مراسم (Ceremony) دو مرحله دارند: BeginRegistration(user) / FinishRegistration(user, session, r) و BeginLogin(user) / FinishLogin(user, session, r). برای ورود بدون نام کاربری، BeginDiscoverableLogin / FinishDiscoverableLogin(handler, session, r) است. SessionData برگشتی Begin باید تا Finish روی سرور در pre-login session بماند. استاندارد W3C، Web Authentication Level 3 است.

1  BeginLogin(user)  -> challenge (random), allowed credential ids; SessionData into session
2  browser: navigator.credentials.get(...) -> device asks for fingerprint -> signs challenge for RPID
3  FinishLogin(user, SessionData, r) -> verify signature with stored public key, origin, RPID, sign count
4  ok -> Rotate session (it is a login), update stored sign count and flags

سناریوی واقعی: ورود با passkey کنار فرم password مشتری؛ پنل admin نیازمند hardware security key در محدودهٔ AAL3؛ recovery که هنوز مسیر امن بدون passkey لازم دارد.

نیازفراخوانی
تنظیم relying partywebauthn.New(&webauthn.Config{RPID: "example.test", RPDisplayName: "Academy", RPOrigins: []string{"https://example.test"}})
ثبت passkeyBeginRegistration(user) سپس FinishRegistration(user, session, r)
ورود با usernameBeginLogin(user) سپس FinishLogin(user, session, r)
ورود بی‌نامBeginDiscoverableLogin() سپس FinishDiscoverableLogin(handler, session, r) یا FinishPasskeyLogin
ذخیرهcredential ID، public key، sign count و flags به تفکیک RPID

راه‌حل / کاربرد: SessionData در pre-login session سمت سرور بماند و به Finish متناظر داده شود. credential را ذخیره، sign count را در هر login به‌روز و session را rotate کنید. ابتدا کنار password عرضه کنید؛ recovery حداقل هم‌قدرت نگه دارید و برای admin اجباری کنید.

خروج امن مهم ​

به زبان ساده: خروج امن (Secure logout) باید session سرور را پایان دهد. پاک‌کردن cookie مرورگر فقط پاک‌سازی سمت کاربر است؛ مهاجم با کپی cookie هنوز رکورد سرور را مصرف می‌کند.

بدفهمی رایج: «logout لینک GET است.» هر <img src> در سایت دیگر آن را فعال می‌کند و CSRF-protected نیست. POST پشت CSRF لازم است. logout هم JWT را خودکار باطل نمی‌کند؛ refresh family را حذف کنید و اگر access باید فوراً بمیرد، jti آن را denylist کنید.

تعریف: Store.Destroy رکورد را حذف می‌کند؛ cookie منقضی با MaxAge: -1 به Max-Age=0 serialize می‌شود. اختیاری Clear-Site-Data: "cache", "cookies", "storage" state مرورگر را پاک می‌کند. برای کلاینت token، refresh family را باطل کنید و خروج همه‌جا با DestroyUser و RevokeUser بدهید. OWASP دسترسی به دکمهٔ logout از همهٔ صفحات و منابع را می‌خواهد.

1  POST /logout (cookie Qz8.., csrf_token ok)
2  Store.Destroy(Qz8..)                      server-side record gone
3  Set-Cookie: __Host-sid=; Path=/; Max-Age=0; HttpOnly; Secure; SameSite=Lax
4  Clear-Site-Data: "cache", "cookies", "storage"
5  copied cookie Qz8.. replayed later -> Get: not found -> 401

سناریوی واقعی: رایانهٔ مشترک کتابخانه؛ لپ‌تاپ دزدیده‌شده و خروج همهٔ sessionها؛ قطع همکاری کارمند وسط session؛ تغییر password با حفظ session جاری که باید rotate شود و بقیه حذف شوند.

کلاینتکار logout
مرورگر و server sessionDestroy، انقضای cookie، Clear-Site-Data
SPA با refresh در cookieابطال خانواده و انقضای cookie؛ access تا exp
موبایل tokenدارابطال خانواده؛ حذف tokenها از keychain
ورود OIDCاول خروج محلی؛ اختیاری RP-initiated logout در provider
خروج همه‌جاDestroyUser و RevokeUser؛ اختیاری not-before کاربر برای JWT

راه‌حل / کاربرد: after.Server.Logout رکورد را حذف و ClearCookie() و Clear-Site-Data ارسال می‌کند. TestLoginRotatesAndSetsFlags رد cookie قدیمی را ثابت می‌کند. کلاینت token، refresh.Store.RevokeUser و در صورت نیاز denylist مربوط به jti را صدا می‌زند. logout را POST پشت CSRF بگذارید.

سازوکار (Mechanics) ​

ترتیب pipeline درخواست حیاتی ​

ترتیب مشخص می‌کند هر لایه به چه چیزی می‌تواند اعتماد کند. بسته‌های این فصل ترتیب زیر را از بیرون به داخل فرض می‌کنند؛ قواعد عمومی در Middlewares است.

1  recover, request id, logging              (Middlewares chapter)
2  http.CrossOriginProtection (Go 1.25)      reject cross-origin unsafe requests before any work
3  session.Store.Load                         cookie -> sha256 -> Session in ctx (never rejects)
4  csrf.Protector.Middleware                  unsafe methods need HMAC(session) token + Origin check
5  lockout.Guard (login routes only)          429 + Retry-After before hashing
6  authmw.RequireUser(SessionAuth, Bearer(JWTVerifier(is)))   401 if nobody; Identity in ctx
7  authmw.RequireRole("admin") (route group)  403
8  handler: load object, check owner/tenant  404 / 403, then do the work

Cookieها و headerهای دقیق حیاتی ​

این خطوط واقعی Set-Cookie از تست‌های این فصل با net/http در Go 1.27.4 آمده‌اند:

session.Cookie(id)       __Host-sid=<id>; Path=/; HttpOnly; Secure; SameSite=Lax
session.ClearCookie()    __Host-sid=; Path=/; Max-Age=0; HttpOnly; Secure; SameSite=Lax
before (no flags)        sid=1001
scs v2.9.0 configured    __Host-session=<token>; Path=/; HttpOnly; Secure; SameSite=Lax   (Persist=false: no Expires)
ویژگیاثرفیلد Goاگر نباشد
HttpOnlydocument.cookie نمی‌خواندHttpOnly: trueXSS شناسه را می‌خواند
Secureفقط HTTPSSecure: trueروی http:// به‌صورت روشن ارسال می‌شود
SameSite=Laxروی POST/fetch/iframe میان‌سایتی ارسال نمی‌شودSameSite: http.SameSiteLaxModeدر بعضی مرورگرها Lax پیش‌فرض با استثنای POST دو دقیقهٔ اول؛ Lax صریح این استثنا را ندارد
Path=/کل سایتPath: "/"پیش‌فرض، directory مسیر درخواست
نبود Domaincookie فقط برای همان hostDomain خالیبا دامنهٔ گسترده به زیردامنه‌ها هم می‌رود
پیشوند __Host-مرورگر قیود Secure، Path و Domain را اعمال می‌کندName: "__Host-sid"زیردامنه ممکن است cookie همنام بکارد
Max-Age / Expirescookie پایدار (Persistent cookie)MaxAge، Expiressession cookie؛ حذف طبق تصمیم مرورگر
Partitionedذخیرهٔ بخش‌بندی‌شدهٔ CHIPSPartitioned: true از Go 1.23رفتار در context شخص ثالث متفاوت است

headerهای پاسخ: Cache-Control: no-store روی login و صفحات شخصی؛ WWW-Authenticate: Bearer realm="api" با هر 401؛ Retry-After: <seconds> با 429؛ Referrer-Policy: no-referrer روی reset؛ و Clear-Site-Data: "cache", "cookies", "storage" روی logout.

متن دقیق خطاها حیاتی ​

خروجی‌ها واقعی‌اند، با Go 1.27.4 و نسخه‌های pinشدهٔ ماژول؛ فقط ردیف ErrNoCookie از سورس net/http/request.go خوانده شده است.

متنمنشأ
bcrypt: password length exceeds 72 bytesbcrypt.ErrPasswordTooLong از GenerateFromPassword
crypto/bcrypt: cost 32 is outside allowed inclusive range 4..31bcrypt.InvalidCostError
crypto/bcrypt: hashedPassword is not the hash of the given passwordbcrypt.ErrMismatchedHashAndPassword
password: hash is not in the expected PHC formatpassword.ErrInvalidHash در این ماژول
token has invalid claims: token is expiredv5، errors.Is(err, jwt.ErrTokenExpired)
token has invalid claims: token has invalid audiencejwt.ErrTokenInvalidAudience
token has invalid claims: token has invalid issuerjwt.ErrTokenInvalidIssuer
token signature is invalid: signing method HS256 is invalidرد alg confusion با WithValidMethods؛ jwt.ErrTokenSignatureInvalid
token signature is invalid: signing method none is invalidهمان بررسی برای "alg":"none"
token is malformed: token contains an invalid number of segmentsjwt.ErrTokenMalformed
token is unverifiable: error while executing keyfunc: unknown kid "k1"خطای keyfunc برای کلید بازنشسته، داخل jwt.ErrTokenUnverifiable
cross-origin request detected from Sec-Fetch-Site headerhttp.CrossOriginProtection، 403
cross-origin request detected, and/or browser is out of date: Sec-Fetch-Site is missing, and Origin does not match Hostهمان، مسیر مرورگر قدیمی
http: named cookie not presenthttp.ErrNoCookie از r.Cookie(name)؛ از سورس، نه این اجرا
#ZgotmplZ در خروجیجایگزینی مقدار ناامن URL یا CSS در html/template

مدل داده مهم ​

storeهای حافظه‌ای snippetها به این جدول‌های PostgreSQL نگاشت می‌شوند. هر secret ارائه‌شدهٔ کلاینت، شامل session ID و refresh و reset token، فقط به‌صورت digest از SHA-256 ذخیره می‌شود؛ password فقط به‌شکل PHC.

sql
CREATE TABLE users (
  id               bigint GENERATED ALWAYS AS IDENTITY PRIMARY KEY,
  email            text NOT NULL,
  email_verified   boolean NOT NULL DEFAULT false,
  password_hash    text NOT NULL,              -- $argon2id$v=19$m=19456,t=2,p=1$...
  totp_secret_enc  bytea,                       -- encrypted at rest (envelope key in KMS)
  totp_last_step   bigint NOT NULL DEFAULT 0,   -- replay protection (RFC 6238)
  password_changed timestamptz NOT NULL DEFAULT now()
);
CREATE UNIQUE INDEX users_email_lower ON users (lower(email));

CREATE TABLE sessions (
  id_hash    bytea PRIMARY KEY,                -- sha256(session id); raw id only in the cookie
  user_id    bigint REFERENCES users(id) ON DELETE CASCADE,
  created_at timestamptz NOT NULL DEFAULT now(),   -- absolute timeout
  last_seen  timestamptz NOT NULL DEFAULT now()    -- idle timeout
);
CREATE INDEX sessions_user ON sessions (user_id);

CREATE TABLE refresh_tokens (
  token_hash bytea PRIMARY KEY,
  family_id  uuid NOT NULL,
  user_id    bigint NOT NULL REFERENCES users(id) ON DELETE CASCADE,
  used       boolean NOT NULL DEFAULT false,
  expires_at timestamptz NOT NULL
);
CREATE TABLE revoked_families (family_id uuid PRIMARY KEY, revoked_at timestamptz NOT NULL DEFAULT now());

CREATE TABLE auth_tokens (                     -- password reset + email verification
  token_hash bytea PRIMARY KEY,
  user_id    bigint NOT NULL REFERENCES users(id) ON DELETE CASCADE,
  purpose    text NOT NULL CHECK (purpose IN ('password_reset', 'email_verification')),
  expires_at timestamptz NOT NULL
);

-- refresh rotation: one transaction, the row lock makes concurrent refreshes queue.
-- Same checks, same order as refresh.Store.Rotate: unknown, revoked, expired -> 401;
-- used -> revoke the family, 401; otherwise mark used and insert the successor.
BEGIN;
SELECT t.user_id, t.family_id, t.used,
       (r.family_id IS NOT NULL) AS family_revoked,
       (t.expires_at <= now())   AS expired
  FROM refresh_tokens t
  LEFT JOIN revoked_families r ON r.family_id = t.family_id
 WHERE t.token_hash = $1
   FOR UPDATE OF t;
-- no row OR family_revoked OR expired -> ROLLBACK; answer 401 invalid_grant
-- used = true -> INSERT INTO revoked_families (family_id) VALUES ($family) ON CONFLICT DO NOTHING;
--                COMMIT; answer 401 (reuse detected)
UPDATE refresh_tokens SET used = true WHERE token_hash = $1 AND NOT used;   -- 1 row, or someone won the race
INSERT INTO refresh_tokens (token_hash, family_id, user_id, expires_at)
SELECT $2, $3, $4, now() + interval '30 days'
 WHERE NOT EXISTS (SELECT 1 FROM revoked_families WHERE family_id = $3);   -- 0 rows -> ROLLBACK, 401
COMMIT;

-- single-use reset token: consume and read in one statement
DELETE FROM auth_tokens
 WHERE token_hash = $1 AND purpose = 'password_reset'
RETURNING user_id, expires_at;

-- after a reset: end everything
DELETE FROM sessions WHERE user_id = $1;
INSERT INTO revoked_families SELECT DISTINCT family_id FROM refresh_tokens WHERE user_id = $1 ON CONFLICT DO NOTHING;

-- housekeeping job
DELETE FROM sessions WHERE last_seen < now() - interval '30 minutes' OR created_at < now() - interval '12 hours';
DELETE FROM auth_tokens WHERE expires_at < now();

هزینهٔ Argon2id و هم‌زمانی تکمیلی ​

هر فراخوانی IDKey برای تمام مدت hash، مقدار m KiB حافظه allocate می‌کند؛ benchmark برای هر operation با پارامتر OWASP، مقدار 19.9 MB و با گزینهٔ دوم RFC 9106، مقدار 67.1 MB نشان می‌دهد. پس اوج حافظه m × concurrent logins است: 100 login هم‌زمان با 19 MiB حدود 2 GB می‌خواهد. با semaphore دور Verify (یک channel بافرشده با ظرفیت N)، concurrency را محدود کنید. بررسی throttling پیش از hash باشد تا سیل loginهای غلط نتواند حافظهٔ نامحدود بخرد. OWASP هشدار می‌دهد work factor بیش از حد می‌تواند "used by an attacker to carry out a denial of service attack by exhausting the server's CPU with a large number of login attempts".

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

باگنشانهاصلاحهزینه
password hash سریع یا بدون saltشکستن passwordها در چند ساعت پس از نشتArgon2id PHC و rehash هنگام login15-30 ms CPU و 19-64 MiB هر login
== روی secret و خروج سریع ناشناسشناسایی حساب با زمانsubtle.ConstantTimeCompare و hash ساختگی (Dummy hash)یک hash اضافی در مسیر شکست
پیام متفاوت ناشناس و password غلطenumeration از متنپیام عمومی و status یکسانUX کمی ضعیف‌تر
ID ثابت در loginfixationRotate / RenewTokenندارد
ID قابل حدس یا خام در storehijacking؛ نشت store یعنی session زنده256 بیت crypto/rand و sha256(id)ندارد
cookie بدون flagسرقت با XSS یا HTTP و CSRF__Host-، HttpOnly، Secure، SameSite=Laxندارد
اعتماد به JWT algtoken جعلیWithValidMethods و کلید هر الگوریتمندارد
aud/iss بررسی‌نشدهtoken سرویس A در B پذیرفته می‌شودWithAudience و WithIssuerندارد
JWT بلندعمر بدون ابطالlogout و ban بی‌اثرaccess ده‌دقیقه‌ای، refresh چرخشی، denylist از jtiendpoint و جدول
فقط role checkIDOR / BOLAمالکیت پس از load، 404یک مقایسه در handler
cookie auth بدون CSRFعمل میان‌سایتیCrossOriginProtection و token متصل به sessionانتقال token در فرم
template.HTML(userInput)stored XSSbluemonday پیش از تبدیلsanitizer برای هر فیلد غنی
reset خام، تکرارپذیر، بلندعمرتصاحب حساب با خواندن DBhash، یک‌بارمصرف، 30 min، پایان sessionهاجدول و job
hard lockoutقفل عمدی کاربرتأخیر نمایی سقف‌دارکندی bot
TOTP بدون replay checkreuse کد در پنجرهٔ 90 sذخیرهٔ آخرین گام پذیرفتهیک ستون
logout فقط cookie را حذف کندکپی cookie معتبر می‌ماندDestroy در سرور و ابطال refreshندارد

ارتقای hash قدیمی بدون reset همگانی ​

برای مهاجرت از sha1(salt+pw) یا bcrypt به Argon2id دو مسیر دارید. ارتقای تنبل (Lazy upgrade): پس از login موفق با روش قدیمی، password.Hash(plain, OWASP) ذخیره کنید؛ handler بعد همین کار را برای تغییر پارامتر انجام می‌دهد. پوشاندن hash (Wrapped hash): فوراً همهٔ hashهای قدیمی را با argon2id(sha1hash) بپوشانید، scheme = 'wrapped-sha1' بگذارید و هنگام login، argon2id(sha1(salt+pw)) بسازید. این روش از حساب غیرفعال هم حفاظت می‌کند ولی مسیر کد اضافی دارد. OWASP یادآور می‌شود lazy برای کاربری که برنمی‌گردد هیچ‌وقت ارتقا نمی‌دهد؛ می‌توان آن credentialها را منقضی و reset اجباری کرد.

انتخاب متن پاسخ 401 ​

برای کاربر ناشناخته، password غلط، حساب قفل‌شده (پس از پایان مدت انتظار) و ایمیل تأییدنشده، همان status، همان body و همان زمان پاسخ را برگردانید. جزئیات را با ایمیل به کاربر بگویید، مثلاً «کسی تلاش کرد وارد شود» یا «لطفاً آدرس خود را تأیید کنید». تنها استثنا throttling است: 429 همراه Retry-After قابل قبول است، چون کلید شمارنده شناسهٔ تایپ‌شده است، مستقل از این‌که آن حساب وجود دارد یا ندارد؛ بنابراین هیچ اطلاعاتی از وجود حساب آشکار نمی‌کند.

پذیرش cookie و bearer در یک API ​

وب و موبایل اغلب API مشترک دارند. هر دو را با ترتیب ثابت RequireUser(SessionAuth, Bearer(JWTVerifier(issuer))) بپذیرید؛ تست در Middleware است. CSRF فقط زمانی اعمال شود که credential از cookie آمده؛ bearer خودکار توسط مرورگر ضمیمه نمی‌شود. روش را در Identity.Method ثبت کنید و برای تغییر ایمیل یا حساب پرداخت، session تازه بخواهید، نه token بلندعمر.

انتخاب ​

وضعیتانتخابتکنیک اضافهدلیل
برنامهٔ Go با render سرورserver-side session با scs یا الگوی sessionCrossOriginProtection و CSRF token و html/templateابطال فوری، بدون storage در JS
SPA خودتان روی همان sitesession cookie با SameSite=Laxtoken در header، AddTrustedOrigin برای origin برنامههمان؛ دوری از localStorage
موبایلJWT access کوتاه و refresh چرخشیrefresh در keychain سیستم‌عاملبدون cookie، بررسی آفلاین API
سرویس‌به‌سرویسJWT با EdDSA/ES256 یا mTLSaud هر سرویس، TTL کوتاه، client_credentialsبررسی بدون تماس issuer
APIهای متعدد با یک IdPOIDC در لبه و JWT داخلcache JWKS و refresh روی kid ناشناسrotation بدون deploy
login شخص ثالثx/oauth2 و go-oidcPKCE، state، nonce، سپس session خودتانهویت از ID token
password storage تازهArgon2id با OWASP m=19 MiB t=2 p=1 یا RFC 9106 با 64 MiB t=3 p=4rehash و semaphorememory-hard
bcrypt موجودحفظ با cost حداقل 12مهاجرت در loginبدون reset اجباری
محیط FIPSPBKDF2-HMAC-SHA-256 با 600,000+ دورcrypto/pbkdf2 در Go 1.24الگوریتم تأییدشده
کارکنان / adminpassword و TOTP یا passkeystep-up برای کار حساسpassword فیش‌شده کافی نیست
حساب مشتریعرضهٔ passkey، password حداقل 15 و بررسی افشاشدنverification و rate limitNIST SP 800-63B-4
متن غنی کاربرbluemonday.UGCPolicy سپس template.HTMLCSP لایهٔ اضافهsanitizer مبتنی بر allow-list

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

مونولیت (Monolith): یک فرایند، یک پایگاه داده ​

ساده‌ترین طراحی درست، همین طرح ماژول است: hashهای Argon2id در users، جدول sessions (یا scs با postgresstore)، session cookie با پیشوند __Host-، اجرای session.Load و middleware مربوط به CSRF روی تک‌تک routeها، RequireUser روی گروه احرازشده و بررسی مالکیت در handlerها. اصلاً JWT در کار نیست. مثال مشخص: برنامهٔ صدور فاکتور Go برای چندصد مشتری، با یک PostgreSQL و یک binary. logout، password reset و «غیرفعال‌کردن کاربر» همگی از همان درخواست بعد اثر می‌گذارند، چون سطرهای مربوط را حذف می‌کنند.

مونولیت ماژولار و چند پایگاه داده ​

Authentication به یک ماژول، internal/auth، تبدیل می‌شود که مالک users، sessions، auth_tokens و password hasher است. فقط Authenticate(r) (*Identity, error)، RequireUser و From(ctx) را در اختیار دیگران می‌گذارد. ماژول‌های دیگر هیچ‌وقت جدول users را نمی‌خوانند؛ یک Identity از context می‌گیرند و قواعد شیء مخصوص خود را اعمال می‌کنند (billing مالکیت فاکتور را می‌سنجد؛ catalogue عضویت فروشگاه را). اگر برای سرعت، sessionها به Redis منتقل شوند ولی کاربران در PostgreSQL بمانند، password reset باید از هر دو store حذف کند. این کار در خود ماژول auth انجام شود؛ حذف Redis پس از commit در PostgreSQL و همراه retry، چون عملیات این دو store با هم اتمیک نیست.

میکروسرویس‌ها (Microservices) ​

یک سرویس اختصاصی auth، token صادر می‌کند؛ سرویس‌های دیگر فقط verify می‌کنند. مرورگر همچنان با backend-for-frontend یا BFF از طریق session cookie حرف می‌زند. BFF، access و refresh tokenهای کاربر را سمت سرور نگه می‌دارد و سرویس‌های داخلی را با Authorization: Bearer <access token> صدا می‌زند. هر سرویس با WithValidMethods([]string{"EdDSA"})، WithIssuer("https://auth.internal")، WithAudience("<its own name>") و کلیدهای JWKS سرویس auth بررسی می‌کند. جریان مثال: مرورگر → BFF با __Host-sid → orders با aud: orders و عمر 10 min → payments. در این مرحله orders باید token خودش را exchange کند یا tokenی با aud: payments بخواهد، نه این‌که همان token خودش را forward کند؛ token forwardشده با audience گسترده به هر سرویس compromiseشده اجازه می‌دهد همه‌جا از جانب کاربر عمل کند. سه چیز از مرز سرویس عبور نمی‌کند: session سمت سرور (فقط BFF آن را دارد)، ابطال فوری (هر سرویس token معتبر را تا exp قبول می‌کند مگر denylist مشترک را بررسی کند)، و Authorization سطح شیء (هر سرویس باید خودش انجامش دهد). پروژهٔ میکروسرویس سرویس auth را با همین شکل می‌سازد.

دادهٔ توزیع‌شده: replica، cache و چند منطقه ​

Sessionها در Redis cluster یا جدول replicated، تأخیر replica را وارد Authentication می‌کنند. logout نوشته‌شده روی primary ممکن است هنوز به replicaیی که read بعدی را پاسخ می‌دهد نرسیده باشد؛ پس session «حذف‌شده» چندصد میلی‌ثانیه دیگر کار می‌کند. برای هر چیزی که باید فوری باشد، مثل logout و تغییر password، state نشست را از primary بخوانید (یا از Redis بدون replica read). بررسی JWT ذاتاً مناسب multi-region است، چون فقط public key لازم دارد؛ اما cacheهای JWKS و denylistها باید replicated شوند. اختلاف ساعت‌ها هم باید در محدودهٔ leeway بماند، این‌جا 30 s، چون exp و nbf و iat زمان ساعت دیواری میزبان‌های متفاوت را مقایسه می‌کنند. شمارنده‌های rate limit و lockout جدا در هر region به مهاجم N تلاش در هر region می‌دهند. این موضوع برای credential stuffing اهمیت کمتری نسبت به حملهٔ هدفمند به یک حساب دارد؛ بنابراین شمارنده‌های هر حساب را جهانی نگه دارید (یک Redis مرکزی) و شمارنده‌های IP را محلی.

مسیر مقیاس: 1×، 10×، 100× ​

بارتغییرروش Authentication
1× (یک instance)همه‌چیز در یک فرایند جا می‌شودsession حافظه‌ای یا PostgreSQL، پارامترهای OWASP برای Argon2id، lockout در حافظه
10× (چند instance پشت load balancer)sessionها و شمارنده‌ها باید مشترک شوندsession store در Redis یا PostgreSQL، شمارندهٔ مرکزی lockout، semaphore برای هم‌زمانی hash در هر instance، real-IP قابل اعتماد برای محدودیت‌های هر IP
100× (سرویس‌های فراوان، regionهای فراوان)lookup هر درخواست و hash مربوط به login هزینهٔ غالب می‌شوندبررسی محلی JWT access token با cache از JWKS، refresh در سرویس auth، passkey برای کاهش password hashing و phishing، سرویس اختصاصی login با ظرفیت و rate limit مخصوص خودش

آزمایشگاه (Lab) ​

1. اجرای تست‌ها؛ خروجی واقعی ​

cd docs/snippets/go/authentication-in-go/go
gofmt -l . && go vet ./... && go test -race -count=1 ./...
# ok  academy/authentication-in-go/after     1.612s
# ok  academy/authentication-in-go/authmw    1.440s
# ok  academy/authentication-in-go/before    1.439s
# ok  academy/authentication-in-go/csrf      1.438s
# ok  academy/authentication-in-go/jwks      1.620s
# ok  academy/authentication-in-go/jwtauth   1.530s
# ok  academy/authentication-in-go/lockout   1.407s
# ok  academy/authentication-in-go/mfa       1.412s
# ok  academy/authentication-in-go/password  3.971s
# ok  academy/authentication-in-go/refresh   1.499s
# ok  academy/authentication-in-go/reset     1.412s
# ok  academy/authentication-in-go/sanitize  1.404s
# ok  academy/authentication-in-go/scsdemo   1.491s
# ok  academy/authentication-in-go/session   1.486s

2. اندازه‌گیری hashها؛ خروجی واقعی ​

go test -run '^$' -bench . -benchmem ./password
# cpu: Apple M4 Pro
# BenchmarkArgon2idOWASP-12             76   15467632 ns/op   19927483 B/op   33 allocs/op
# BenchmarkBcryptCost12-12               6  175956194 ns/op       5534 B/op   10 allocs/op
# BenchmarkArgon2idRFC9106Second-12     42   26944114 ns/op   67120044 B/op   91 allocs/op

Argon2id با OWASP حدود 15 ms و 19 MiB هزینه دارد؛ 100 login هم‌زمان حدود 2 GB می‌خواهند. bcrypt با cost 12 حدود 176 ms از یک هسته و تقریباً هیچ حافظه‌ای می‌گیرد؛ همین مصرف کم حافظه علت مناسب‌تر بودنش برای GPU نسبت به Argon2id است.

3. دیدن شکست alg confusion؛ واقعی ​

go test -run 'TestAlgConfusionRejected|TestKeyRotation' -v ./jwtauth
# --- PASS: TestAlgConfusionRejected   HS256-with-public-key and "none" both rejected
# --- PASS: TestKeyRotation            old and new kid accepted during overlap; retired kid rejected

خطای جعل HS256 که برنامهٔ آزمایشی این فصل با همین بسته چاپ کرده: token signature is invalid: signing method HS256 is invalid.

4. اثبات reuse detection و reset یک‌بارمصرف؛ واقعی ​

go test -run 'Reuse|Concurrent|SingleUse' -v ./refresh ./reset
# --- PASS: TestReuseRevokesFamily
# --- PASS: TestConcurrentRotateHasOneWinner     20 goroutines, 1 winner
# --- PASS: TestSingleUseHashedAndSessionsEnded
# --- PASS: TestConcurrentConfirmHasOneWinner    10 goroutines, 1 winner

5. Fixation و enumeration، قبل و بعد؛ واقعی ​

go test -run 'TestBeforeWeaknesses' -v ./before
# --- PASS: TestBeforeWeaknesses   planted "attacker-chosen" id logged in as bob; session survives logout
go test -run 'TestUnknownUserAndWrongPasswordLookTheSame|TestLoginRotatesAndSetsFlags' -v ./after
# --- PASS: TestUnknownUserAndWrongPasswordLookTheSame   same 401 body, 2 hash computations
# --- PASS: TestLoginRotatesAndSetsFlags                 planted id rejected after login

6. مسیر مرورگر با CSRF؛ تست واقعی و curl مورد انتظار ​

after.Server.Secure(p) همان endpointها همراه GET /csrf-token است؛ اگر session نباشد ناشناس می‌سازد و token session جاری را می‌دهد. همه پشت csrf.Protector.Middleware با SessionID: after.SessionIDFromCookie هستند. خود مسیر مرورگر تست واقعی دارد:

go
package after

import (
	"encoding/json"
	"net/http"

	"academy/authentication-in-go/csrf"
	"academy/authentication-in-go/session"
)

// SessionIDFromCookie is what csrf.Protector binds its tokens to.
func SessionIDFromCookie(r *http.Request) string {
	if c, err := r.Cookie(session.CookieName); err == nil {
		return c.Value
	}
	return ""
}

// CSRFToken serves GET /csrf-token: it starts an anonymous session when the
// browser has none (so the login form has something to bind a token to)
// and returns the token for the current session. Call it again after login:
// rotation gives a new session ID, so the old token no longer matches.
func (s *Server) CSRFToken(p *csrf.Protector) http.HandlerFunc {
	return func(w http.ResponseWriter, r *http.Request) {
		id := SessionIDFromCookie(r)
		if _, err := s.Sessions.Get(id); id == "" || err != nil {
			id = s.Sessions.Create(0)
			http.SetCookie(w, session.Cookie(id))
		}
		w.Header().Set("Cache-Control", "no-store")
		w.Header().Set("Content-Type", "application/json")
		json.NewEncoder(w).Encode(map[string]string{"csrf_token": p.Token(id)})
	}
}

// Secure is the production shape of Routes: the same endpoints plus
// GET /csrf-token, with csrf.Protector in front of every unsafe method.
// Put csrf.WithCrossOriginProtection (Go 1.25) outside it.
func (s *Server) Secure(p *csrf.Protector) http.Handler {
	mux := http.NewServeMux()
	mux.HandleFunc("GET /csrf-token", s.CSRFToken(p))
	mux.HandleFunc("POST /login", s.Login)
	mux.HandleFunc("POST /logout", s.Logout)
	mux.HandleFunc("GET /me", s.Me)
	return s.Sessions.Load(p.Middleware(mux))
}
go
package after

import (
	"encoding/json"
	"net/http"
	"net/http/httptest"
	"net/url"
	"strings"
	"testing"

	"academy/authentication-in-go/csrf"
	"academy/authentication-in-go/session"
)

// The lab flow end to end: fetch a token (anonymous session), log in with
// it, fetch a new token for the rotated session, log out with it; a logout
// without a token is refused.
func TestSecureStackBrowserFlow(t *testing.T) {
	s, _ := newServer(t)
	p := &csrf.Protector{Secret: []byte("0123456789abcdef0123456789abcdef"), SessionID: SessionIDFromCookie}
	h := s.Secure(p)

	getToken := func(c *http.Cookie) (string, *http.Cookie) {
		req := httptest.NewRequest("GET", "https://app.example.test/csrf-token", nil)
		if c != nil {
			req.AddCookie(c)
		}
		rec := httptest.NewRecorder()
		h.ServeHTTP(rec, req)
		var body map[string]string
		json.NewDecoder(rec.Body).Decode(&body)
		if cs := rec.Result().Cookies(); len(cs) > 0 {
			c = &http.Cookie{Name: cs[0].Name, Value: cs[0].Value}
		}
		return body["csrf_token"], c
	}
	send := func(path string, form url.Values, c *http.Cookie) *httptest.ResponseRecorder {
		req := httptest.NewRequest("POST", "https://app.example.test"+path, strings.NewReader(form.Encode()))
		req.Header.Set("Content-Type", "application/x-www-form-urlencoded")
		req.Header.Set("Origin", "https://app.example.test")
		req.RemoteAddr = "192.0.2.10:5000"
		if c != nil {
			req.AddCookie(c)
		}
		rec := httptest.NewRecorder()
		h.ServeHTTP(rec, req)
		return rec
	}

	tok, anon := getToken(nil)
	if tok == "" || anon == nil || anon.Name != session.CookieName {
		t.Fatalf("no anonymous session/token: %q %v", tok, anon)
	}
	if rec := send("/login", url.Values{"email": {"alice@example.test"}, "password": {"correct horse battery staple"}}, anon); rec.Code != 403 {
		t.Fatalf("login without token: %d", rec.Code)
	}
	rec := send("/login", url.Values{"email": {"alice@example.test"}, "password": {"correct horse battery staple"}, "csrf_token": {tok}}, anon)
	if rec.Code != http.StatusNoContent {
		t.Fatalf("login with token: %d %s", rec.Code, rec.Body)
	}
	authed := &http.Cookie{Name: session.CookieName, Value: rec.Result().Cookies()[0].Value}
	if rec := send("/logout", url.Values{"csrf_token": {tok}}, authed); rec.Code != 403 {
		t.Fatalf("pre-login token accepted after rotation: %d", rec.Code)
	}
	tok2, _ := getToken(authed)
	if rec := send("/logout", nil, authed); rec.Code != 403 {
		t.Fatalf("logout without token: %d", rec.Code)
	}
	if rec := send("/logout", url.Values{"csrf_token": {tok2}}, authed); rec.Code != http.StatusNoContent {
		t.Fatalf("logout with token: %d", rec.Code)
	}
}
go test -run TestSecureStackBrowserFlow -v ./after      (real)
# --- PASS: TestSecureStackBrowserFlow   GET /csrf-token -> anonymous __Host-sid + token;
#     POST /login without token 403, with token 204 (rotated cookie);
#     old token after rotation 403; fresh token -> POST /logout 204; no token 403

برای سرور در حال اجرا، این فرمان‌ها اجرا نشده‌اند (مورد انتظار): در main با HTTPS روی https://localhost:8443 و certificate خودامضا، s.Secure(p) را با csrf.WithCrossOriginProtection بپوشانید و سپس:

curl -k -c jar -b jar https://localhost:8443/csrf-token
# {"csrf_token":"<nonce>.<mac>"}  and Set-Cookie: __Host-sid=<anonymous id>      (expected)
curl -k -c jar -b jar -X POST https://localhost:8443/login -H 'Origin: https://localhost:8443' \
     --data-urlencode 'email=alice@example.test' --data-urlencode 'password=correct horse battery staple' \
     --data-urlencode 'csrf_token=<nonce>.<mac>'
# HTTP/2 204, Set-Cookie: __Host-sid=<new id>                                       (expected)
curl -k -c jar -b jar https://localhost:8443/csrf-token
# {"csrf_token":"<token for the new session>"}                                      (expected)

سه حالت ردشدن:

curl -k -i -X POST https://localhost:8443/logout -H 'Sec-Fetch-Site: cross-site' -b '__Host-sid=<id>'
# HTTP/2 403   cross-origin request detected from Sec-Fetch-Site header        (expected)
curl -k -i -X POST https://localhost:8443/logout -H 'Origin: https://evil.example.test' -b '__Host-sid=<id>'
# HTTP/2 403   cross-origin request detected, and/or browser is out of date: ...  (expected)
curl -k -i -X POST https://localhost:8443/logout -b '__Host-sid=<id>'
# HTTP/2 403   forbidden: CSRF check failed   (no token; the session-bound token layer)  (expected)

برای توسعه‌دهندگان PHP/Laravel ​

Laravel کل این فصل را به‌شکل configuration می‌دهد؛ Go قطعه‌ها را می‌دهد. Auth::attempt($credentials) با facade نوع Hash بررسی می‌کند (پیش‌فرض bcrypt، driverهای argon و argon2id هم موجودند؛ Hash::needsRehash برای ارتقا). مثال login مستندات سپس $request->session()->regenerate() را صدا می‌زند که معادل session.Rotate این‌جاست. گروه middleware نوع web، session و دفاع CSRF را اضافه می‌کند. در Laravel 13، PreventRequestForgery از "a two-layer approach" استفاده می‌کند: ابتدا header نوع Sec-Fetch-Site ("If the header indicates the request came from the same origin, the request is allowed immediately without any token verification") و سپس token کلاسیک session با @csrf و فیلد _token. این همان لایه‌بندی CrossOriginProtection جلوی csrf.Protector است. starter kitها "rate limiting ... to login attempts" اضافه می‌کنند (یک دقیقه پس از چند شکست)؛ broker نوع Password هم reset را با 'expire' => 60 دقیقه و 'throttle' => 60 ثانیهٔ فاصلهٔ درخواست‌ها انجام می‌دهد.

مقایسهٔ Laravel Breeze/Sanctum. Breeze به‌گفتهٔ مستند Laravel 11، "a minimal, simple implementation of all of Laravel's authentication features, including login, registration, password reset, email verification, and password confirmation" بود. یادداشت انتشار Laravel 12 سپس گفت: "With the introduction of our new application starter kits, Laravel Breeze and Laravel Jetstream will no longer receive additional updates." در Laravel 13، starter kitهای React و Vue و Livewire "use Laravel Fortify to handle authentication"؛ احراز دوعاملی هم یکی از قابلیت‌های Fortify است. این نزدیک‌ترین معادل ترکیب بسته‌های after، reset، lockout و mfa است. Sanctum سمت token را در دو حالت پوشش می‌دهد: API tokenهایی "inspired by GitHub and other applications which issue 'personal access tokens'" که در جدول database ذخیره و "hashed using SHA-256 hashing before being stored" می‌شوند؛ این‌ها tokenهای opaque شبیه refresh tokenهای این فصل‌اند (با حذف سطر باطل می‌شوند)، نه JWT. در حالت SPA authentication، "Sanctum does not use tokens of any kind. Instead, Sanctum uses Laravel's built-in cookie based session authentication services"؛ همان ردیف SPA خودتان در انتخاب.

php
// Laravel 13: login with rotation, generic error, throttling handled by the starter kit
if (Auth::attempt($request->only('email', 'password'))) {
    $request->session()->regenerate();            // = session.Rotate
    return redirect()->intended('/dashboard');
}
return back()->withErrors(['email' => 'The provided credentials do not match our records.']);
// Sanctum API token: opaque, SHA-256 hashed before storage; abilities as the second argument
$token = $user->createToken('mobile', ['orders:read'])->plainTextToken;
Laravel 13Go در این فصل
Hash::make، Hash::check، Hash::needsRehashpassword.Hash، password.Verify با خروجی needsRehash
config/hashing.php، bcrypt.rounds، argon.memory/time/threadspassword.Params، password.BcryptCost
Auth::attempt و session()->regenerate()after.Login و session.Store.Rotate
session()->invalidate() و regenerateToken() در logoutStore.Destroy و ClearCookie
PreventRequestForgery؛ Sec-Fetch-Site سپس @csrf؛ originOnly و allowSameSitehttp.CrossOriginProtection سپس csrf.Protector
RateLimiter / login throttlinglockout.Guard
Password::sendResetLink، Password::resetreset.Service
MustVerifyEmail و URL امضاشدهٔ verificationreset.SendVerification، ConfirmEmail
احراز دوعاملی Fortifymfa با pquerna/otp
API token در Sanctumtoken opaque و hash‌شده با الگوی refresh یا JWT با jwtauth
SPA auth در Sanctumsession cookie و CSRF برای SPA خودتان
Breeze تا Laravel 11 / starter kit روی Fortify در 12 و 13after و reset و lockout و mfa؛ اتصال با شما
echo escaped در Blade، آکولاد دوتاییautoescaping وابسته به context در html/template

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

باورواقعیت
SHA-256 با salt برای password کافی استخیلی سریع است؛ Argon2id یا bcrypt برای legacy
salt باید محرمانه باشدکنار hash می‌ماند؛ pepper محرمانه است
thread بیشتر Argon2 یعنی شکستن سخت‌ترp حافظه را به lane تقسیم می‌کند؛ memory و passes هزینه را می‌سازند
bcrypt کل password را می‌گیردحداکثر 72 بایت؛ x/crypto بلندتر را رد می‌کند
== روی hash بی‌خطر استکپی آن برای token و MAC نشت می‌دهد؛ quick exit هم حساب را لو می‌دهد
complexity rule امنیت می‌دهدNIST SP 800-63B-4 آن را ممنوع می‌کند؛ طول و blocklist مؤثرند
حفظ session ناشناس در login خوب استfixation است؛ هر تغییر privilege، rotation
signed cookie قابل ابطال استچیزی روی سرور برای حذف ندارد؛ تا expiry معتبر
JWT رمزگذاری شده استpayload در JWS، base64url و خواندنی است
امضای معتبر یعنی token معتبرiss و aud و exp و typ و الگوریتم هم باید بررسی شوند
logout، JWT را باطل می‌کندexpiry، denylist یا بازنشستگی کلید اثر می‌کنند
auth middleware همان Authorization استمالکیت شیء در handler بررسی می‌شود؛ IDOR/BOLA
SameSite=Lax دفاع کامل CSRF استمهاجم same-site، اثر جانبی GET و مرورگر قدیمی می‌مانند
sanitizing ورودی XSS را می‌بنددencoding خروجی هنگام render جلوی XSS را می‌گیرد؛ فقط HTMLی را sanitize کنید که به‌شکل HTML نمایش می‌دهید
reset link می‌تواند login کندOWASP منع می‌کند؛ sessionهای موجود را پایان دهید
پس از پنج شکست حساب قفل شوددکمهٔ DoS است؛ تأخیر نمایی سقف‌دار
totp.Validate مانع replay استstateless است؛ آخرین گام پذیرفته‌شده را ذخیره کنید

یادسپار (Cheat sheet) ​

موضوعبه خاطر بسپارید
Hash؛ هش گذرواژهargon2.IDKey، PHC، m=19456 t=2 p=1 در OWASP یا 64 MiB t=3 p=4 در RFC 9106؛ salt با 16 بایت
bcryptcost حداقل 10، این‌جا 12؛ سقف 72 بایت؛ bcrypt.Cost برای rehash
Pepper؛ secret مشترکHMAC با کلید vault؛ base64(HMAC-SHA-384) پیش از bcrypt
Compare؛ مقایسهsubtle.ConstantTimeCompare / hmac.Equal؛ hash ساختگی (Dummy hash) برای کاربر ناشناخته
Errors؛ خطاهایک پیام invalid email or password؛ 429 و Retry-After برای throttling
Policy؛ سیاستحداقل 15 کاراکتر، 8 با MFA؛ پذیرش حداقل 64، blocklist، بدون composition و rotation اجباری
Session ID؛ شناسه32 بایت crypto/rand، base64url، ذخیرهٔ sha256(id)
Cookie__Host-sid؛ Path=/; HttpOnly; Secure; SameSite=Lax
Rotation؛ چرخشID تازه در login و logout و تغییر password و role
Timeout؛ مهلتidle برابر 15-30 min، حساس 2-5؛ absolute برابر 4-12 h، اعمال سرور
JWTWithValidMethods، WithIssuer، WithAudience، WithExpirationRequired، WithLeeway(30s)
Keys؛ کلیدهاEdDSA یا ES256؛ kid، بازنشستگی پس از max TTL؛ cache JWKS با refresh محدودشده
Tokens؛ توکن‌هاaccess برابر 5-15 min؛ refresh opaque و hash‌شده و چرخشی؛ reuse خانواده را باطل می‌کند
Identity؛ هویتکلید ctx نوع unexported؛ From(ctx)؛ مالکیت در handler، 404 برای شیء دیگران
CSRFCrossOriginProtection در 1.25 و HMAC متصل به session؛ logout با POST
XSSvalidation ورودی، bluemonday برای HTML غنی، همیشه html/template
Reset؛ بازیابیtoken با 256 بیت، فقط hash، 30-60 min، یک‌بارمصرف، پاسخ عمومی، پایان sessionها
TOTPpquerna/otp، 30 s، skew برابر 1، رد replay، recovery code به‌شکل hash

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

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

۱ — چرا sha256(salt + password) یک password hash قابل قبول نیست و در Go به‌جایش چه استفاده می‌کنید؟ حیاتی ​

پاسخ

پاسخ: salt جلوی جدول‌های ازپیش‌محاسبه‌شده را می‌گیرد، اما جلوی حدس‌زدن را نه. SHA-256 برای سرعت طراحی شده است؛ مهاجم دارای جدول کاربران با هر GPU میلیاردها candidate را در ثانیه می‌آزماید. به‌جایش تابعی عمداً کند و memory-hard استفاده کنید: argon2.IDKey از golang.org/x/crypto/argon2 با حداقل پارامترهای OWASP، یعنی m=19456 KiB، t=2، p=1 و salt تصادفی 16 بایتی، ذخیره‌شده به‌صورت رشتهٔ PHC. bcrypt با cost ≥ 10 و سقف 72 بایت فقط برای سیستم legacy است.

۲ — رشتهٔ PHC با شکل $argon2id$v=19$m=19456,t=2,p=1$<salt>$<hash> چه مزیتی بر ستون hash تنها دارد؟ تکمیلی ​

پاسخ

پاسخ: الگوریتم و نسخه و پارامتر و salt همراه hash می‌مانند. Verify برای هر سطر همان پارامترهای زمان ایجاد را مصرف می‌کند، پس قدیم و جدید هم‌زیستی دارند. پس از login موفق، تا plaintext موجود است پارامترها را با policy امروز مقایسه و در صورت needsRehash ارتقا می‌دهید.

۳ — login شما «چنین کاربری نیست» را در 1 ms و «password غلط است» را در 15 ms با پیام یکسان جواب می‌دهد؛ اشکال چیست و چگونه اصلاحش می‌کنید؟ حیاتی ​

پاسخ

پاسخ: زمان پاسخ هنوز حساب‌ها را شناسایی‌پذیر می‌کند؛ همان مشکل quick exit که OWASP توصیف می‌کند. وقتی کاربر وجود ندارد، hash ساختگی (Dummy hash) از Argon2id را با پارامترهای فعلی محاسبه کنید، password را در برابر آن verify کنید و با همان status و body شکست بدهید. همهٔ secretها را با subtle.ConstantTimeCompare مقایسه کنید. throttling هم برای هر شناسهٔ تایپ‌شده باشد، چه حساب واقعاً موجود باشد چه نباشد.

۴ — NIST SP 800-63B-4 چه چیزهایی را در password policy الزامی و چه چیزهایی را ممنوع می‌کند؟ مهم ​

پاسخ

پاسخ: حداقل طول password تک‌عامل 15 کاراکتر است (8 اگر فقط همراه MFA استفاده می‌شود) و باید طول حداقل 64 کاراکتر را مجاز بدانید. password را با blocklist رایج و compromiseشده مقایسه کنید، salt حداقل 32 بیتی بدهید و با یک password hashing scheme، hash کنید؛ نرخ شکست‌ها هم محدود باشد، حداکثر 100 شکست متوالی. composition rule، تغییر دوره‌ای اجباری (جز در صورت شواهد compromise) و درخواست پاسخ knowledge-based ممنوع‌اند.

۵ — چرا ID نشست باید در login عوض شود و در scs و store دست‌نویس چگونه؟ حیاتی ​

پاسخ

پاسخ: وگرنه مهاجمی که ID معلوم را پیش از login در مرورگر کاشته، پس از login قربانی به حساب دسترسی دارد؛ session fixation. در scs پیش از Put، sm.RenewToken(r.Context()) و در بستهٔ session، Store.Rotate(oldID, userID) را صدا بزنید تا رکورد قبلی حذف و ID تازهٔ 256 بیتی صادر شود. همین اصل برای logout و تغییر password و role برقرار است.

۶ — session cookie چه ویژگی‌هایی می‌خواهد و __Host- چه اضافه می‌کند؟ مهم ​

پاسخ

پاسخ: HttpOnly برای منع دسترسی script، Secure برای HTTPS، SameSite=Lax یا Strict برای محدودکردن ارسال cross-site، Path=/ و نبود Domain. پیشوند __Host- فقط وقتی پذیرفته می‌شود که Secure تنظیم شده باشد، Path=/ تنظیم شده باشد و هیچ ویژگی Domain وجود نداشته باشد؛ مرورگر cookie فاقد Secure یا Path=/، یا دارای Domain را رد می‌کند. بنابراین زیردامنهٔ همسایه نمی‌تواند آن را بازنویسی کند.

۷ — حملهٔ RS256-to-HS256 و گزینهٔ دفاعی golang-jwt v5 را توضیح دهید. حیاتی ​

پاسخ

پاسخ: مهاجم alg را HS256 می‌کند و با بایت‌های public key به‌عنوان secret، HMAC می‌سازد. verifierی که alg را باور کند و کلید را به HMAC بدهد آن را می‌پذیرد. jwt.WithValidMethods([]string{"EdDSA"}) یا همان یک الگوریتم نامتقارن انتخابی، بقیه را با token signature is invalid: signing method HS256 is invalid رد می‌کند. RFC 8725 هم هر کلید را به دقیقاً یک الگوریتم محدود می‌کند.

۸ — v5، token سرویس دیگری را پذیرفته؛ کدام بررسی‌ها کم بوده‌اند؟ مهم ​

پاسخ

پاسخ: exp و nbf موجود خودکار بررسی می‌شوند ولی iss و aud فقط با درخواست شما. WithIssuer(...)، WithAudience("<this service>")، WithExpirationRequired() و leeway کوچک اضافه کنید. typ را هم صریح بسنجید تا ID token یا refresh به‌جای access مصرف نشود.

۹ — refresh token rotation چگونه سرقت را تشخیص می‌دهد و چه اتفاقی برای کاربر واقعی می‌افتد؟ مهم ​

پاسخ

پاسخ: هر refresh، یک refresh token جدید برمی‌گرداند و قبلی را used علامت می‌زند، در حالی که رابطهٔ خانواده حفظ می‌شود. اگر token مصرف‌شده دوباره ارائه شود، یا مهاجم یا خود کاربر آن را replay کرده است؛ سرور نمی‌تواند تشخیص دهد کدام‌یک، پس کل خانواده را باطل می‌کند (RFC 9700 بخش 4.14.2). token فعلی کاربر واقعی هم دیگر کار نمی‌کند و او باید دوباره login کند؛ این کار دسترسی مهاجم را هم پایان می‌دهد.

۱۰ — کاربر واردشده فاکتور /invoices/1002 متعلق به دیگری را می‌خواند؛ باگ و پاسخ درست چیست؟ حیاتی ​

پاسخ

پاسخ: کنترل مجوز سطح شیء در handler وجود ندارد؛ همان IDOR در OWASP API1:2023. پس از بارگیری فاکتور، مالک آن (یا tenant) را با هویت گرفته‌شده از context مقایسه کنید. برای اشیایی که فراخواننده حق دیدنشان را ندارد، 404 بدهید تا نتواند با probe کردن IDها وجودشان را بفهمد. به‌عنوان دفاع چندلایه، AND owner_id = $2 را هم به query اضافه کنید.

۱۱ — با session cookieهای SameSite=Lax چرا هنوز دفاع CSRF لازم است و Go 1.25 چه اضافه می‌کند؟ مهم ​

پاسخ

پاسخ: SameSite=Lax صریح، مهاجم same-site (مثلاً زیردامنهٔ همسایهٔ compromiseشده) یا GET تغییردهندهٔ state را متوقف نمی‌کند؛ مرورگری که این attribute را نادیده بگیرد به‌هرحال cookie را می‌فرستد. اگر attribute غایب باشد، مرورگرهای دارای Lax پیش‌فرض از شکل آسان‌گیرتری استفاده می‌کنند که هنوز تا دو دقیقه پس از تنظیم cookie آن را در POST میان‌سایتی می‌فرستد (MDN)، و مرورگرهای دیگر همیشه ارسالش می‌کنند؛ پس SameSite را همیشه صریح تنظیم کنید. http.CrossOriginProtection در Go 1.25 درخواست غیرامن را رد می‌کند اگر Sec-Fetch-Site آن نه same-origin باشد نه none، یا Origin آن با Host تطبیق نکند. برای مرورگری که هیچ‌یک از دو header را نمی‌فرستد، token متصل به session نگه دارید.

۱۲ — ویژگی‌های flow امن password reset چیست؟ حیاتی ​

پاسخ

پاسخ: برای ایمیل موجود و ناشناخته همان پاسخ و زمانی مشابه بدهید؛ token تصادفی با حداقل 128 بیت بسازید و فقط hash آن را ذخیره کنید. expiry کوتاه 30-60 دقیقه‌ای، مصرف یک‌بارهٔ اتمیک و ابطال tokenهای قدیمی لازم است. لینک از configuration ساخته شود، نه header نوع Host؛ صفحه باید Referrer-Policy: no-referrer داشته باشد. پس از reset، تک‌تک sessionها و refresh tokenهای کاربر باطل شوند و هیچ login خودکاری انجام نشود.

۱۳ — چرا totp.Validate به‌تنهایی RFC 6238 را برآورده نمی‌کند و اصلاح چیست؟ تکمیلی ​

پاسخ

پاسخ: stateless است؛ در پنجرهٔ گام 30 ثانیه و skew برابر 1، همان کد دوباره معتبر می‌شود. RFC می‌گوید "MUST NOT accept the second attempt of the OTP after the successful validation". با GenerateCodeCustom گام مطابق را پیدا کنید و فقط اگر بزرگ‌تر از آخرین گام پذیرفته‌شدهٔ ذخیره‌شده برای کاربر است قبول کنید.

۱۴ — خروج امن برای cookie session و موبایل tokenدار چه می‌کند؟ تکمیلی ​

پاسخ

پاسخ: برای cookie، POST محافظت‌شده با CSRF رکورد سرور را حذف و cookie منقضی با Max-Age=0 و اختیاری Clear-Site-Data می‌فرستد. برای موبایل، refresh family در سرور باطل و tokenها از keychain حذف می‌شوند؛ access تا exp معتبر است مگر jti آن denylist شود. هر دو باید گزینهٔ خروج همه‌جا داشته باشند.

واژه‌نامه (Glossary) ​

اصطلاحمعنی
احراز هویت (Authentication)اثبات هویت فراخواننده
کنترل مجوز (Authorization)تعیین کار مجاز فراخواننده روی شیء
هش گذرواژه (Password hashing)ذخیرهٔ تابع یک‌طرفهٔ کند و saltدار password
Argon2idhash حافظه‌بر در RFC 9106؛ argon2.IDKey در Go
پارامترهای RFC 9106 (RFC 9106 parameters)t و m و p؛ گزینهٔ دوم t=3، p=4، 64 MiB
bcrypthash تطبیقی بر پایهٔ Blowfish؛ cost برابر 4-31 و سقف 72 بایت
هزینه / ضریب کار (Cost / work factor)پارامتر کندکننده؛ bcrypt دارای 2^cost دور
قالب PHC (PHC string format)کدگذاری hash با $id$v=..$params$salt$hash
نمک (Salt)مقدار تصادفی هر password همراه hash
پپر (Pepper)کلید secret مشترک بیرون database
هش دوباره در ورود (Rehash on login)ارتقای hash پس از verify موفق
مقایسهٔ زمان‌ثابت (Constant-time compare)زمان مستقل از محل اختلاف؛ crypto/subtle
حملهٔ زمانی (Timing attack)کشف secret یا واقعیت از زمان پاسخ
هش ساختگی (Dummy hash)محاسبه برای ناشناس جهت برابر کردن هزینهٔ شکست
شناسایی حساب‌ها (User enumeration)کشف وجود حساب از پاسخ یا زمان
سیاست گذرواژه (Password policy (NIST 800-63B))طول و blocklist، بدون composition و rotation اجباری
فهرست منع (Blocklist)passwordهای رایج یا افشاشدهٔ ممنوع
نشست (Session)رکورد سرور برای کاربر واردشده
مخزن سرور (Server-side store)محل session؛ حافظه، Redis، SQL
بی‌نظمی شناسه (Session ID entropy)غیرقابل‌پیش‌بینی بودن؛ حداقل 64 بیت، این‌جا 256 از crypto/rand
تثبیت نشست (Session fixation)کاشت ID معلوم پیش از login قربانی
چرخش هنگام ورود (Rotation on login)ID تازه با تغییر privilege
مهلت بی‌فعالیتی (Idle timeout)پایان session پس از بی‌فعالیتی
مهلت مطلق (Absolute timeout)پایان پس از فاصلهٔ ثابت از login
HttpOnlyflag پنهان‌کنندهٔ cookie از JavaScript
Secureflag محدودکننده به HTTPS
SameSiteمحدودسازی cross-site با Strict و Lax و None
پیشوند __Host-الزام Secure و Path=/ و نبود Domain
alexedwards/scsمدیر session سرور در Go با store قابل تعویض
gorilla/sessionssessionهای cookie و filesystem، cookie امضاشده/رمزشده
JWTclaims در JSON امضاشده؛ RFC 7519 و فرم فشردهٔ JWS
golang-jwt/jwt v5کتابخانهٔ نگه‌داری‌شدهٔ github.com/golang-jwt/jwt/v5
HS256امضای HMAC-SHA-256 با secret مشترک
RS256 / ES256 / EdDSAامضای RSA، ECDSA P-256 و Ed25519
بررسی ادعاها (Claims validation)کنترل exp، nbf، iat، aud، iss و sub و typ
سردرگمی الگوریتم (Alg confusion)alg انتخابی مهاجم؛ none یا HS256 با public key
kidheader نام‌گذار کلید تأیید JWT
چرخش کلید (Key rotation)افزودن signing key و بازنشستگی قبلی پس از max TTL
JWKSJSON Web Key Set؛ public keyها در URL، RFC 7517
توکن دسترسی (Access token)credential کوتاه‌عمر API
توکن نوسازی (Refresh token)credential بلندعمر ابطال‌پذیر برای access تازه
چرخش نوسازی (Refresh token rotation)token تازه در هر مصرف؛ reuse خانواده را باطل می‌کند
ابطال (Revocation)بی‌اعتبار کردن credential پیش از expiry
فهرست منع jti (jti denylist)IDهای token باطل‌شده تا exp خودشان
OAuth2پروتکل واگذاری Authorization؛ golang.org/x/oauth2
OIDCلایهٔ هویت OAuth2؛ coreos/go-oidc برای ID token
PKCEproof key for code exchange؛ حفاظت authorization code
میان‌افزار احراز (Auth middleware)wrapper بررسی هویت و قرار دادن آن در context
هویت context (Context identity)Identity زیر کلید unexported
IDOR / BOLAنبود Authorization سطح شیء؛ OWASP API1:2023
جعل درخواست میان‌سایتی (CSRF)عمل سایت دیگر با cookie کاربر
کوکی دوبارارسال (Double-submit cookie)token در cookie و request؛ نوع امضاشدهٔ متصل به session توصیه می‌شود
توکن همگام (Synchronizer token)token هر session برای بررسی هر درخواست unsafe
بررسی مبدأ (Origin check)مقایسهٔ Origin با مبدأ مورد انتظار
Sec-Fetch-Sitemetadata با same-origin، same-site، cross-site و none
http.CrossOriginProtectionmiddleware ضد CSRF در Go 1.25 بر مبنای fetch metadata
اعتبارسنجی (Validation)رد ورودی خارج allow-list
پاک‌سازی (Sanitization)حذف HTML غیرمجاز از محتوای قابل render به‌شکل HTML؛ bluemonday
کدگذاری خروجی (Output encoding)escape برای context نمایش؛ html/template
#ZgotmplZجایگزین html/template برای URL یا CSS ناامن
توکن بازیابی (Password reset token)secret لینک تصادفی، hash‌شده، یک‌بارمصرف، منقضی‌شونده
تأیید ایمیل (Email verification)اثبات کنترل آدرس با token یک‌بارمصرف
قفل حساب (Account lockout)تأخیر یا بستن تلاش پس از شکست‌ها
محدودسازی نرخ (Rate limiting)سقف تلاش مبدأ؛ token bucket و x/time/rate
آزمودن اعتبارنامهٔ افشاشده (Credential stuffing)امتحان زوج‌های username/password روی حساب‌های فراوان
احراز چندعاملی (MFA)Multi-factor authentication
گذرواژهٔ زمانی (TOTP)time-based one-time password؛ RFC 6238 و pquerna/otp
کدهای بازیابی (Recovery codes)backup یک‌بارمصرف برای عامل دوم گمشده
کلید عبور (Passkey / WebAuthn)credential کلیدعمومی متصل به origin؛ go-webauthn
خروج امن (Secure logout)حذف state سرور، انقضای cookie، ابطال refresh
Laravel Breezescaffold حداقلی auth تا Laravel 11؛ جایگزین با starter kit
Laravel Fortifybackend احراز در starter kitهای Laravel 13
Laravel Sanctumبستهٔ API tokenهای opaque و SPA cookie auth

منابع ​

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