Skip to content

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

"Verifiers and CSPs SHALL NOT require subscribers to change passwords periodically. However, verifiers SHALL force a change if there is evidence that the authenticator has been compromised." — NIST, SP 800-63B-4: Digital Identity Guidelines, Authentication and Authenticator Management, section 3.1.1.2 (Password Verifiers), July 2025

Summary: Authentication is the system that turns "someone typed an email" into "this request belongs to account 42, proven with these factors, at this time". It has four parts you design together: how secrets are stored (Argon2id, bcrypt, peppers), how guessing is stopped (throttling, uniform errors, breached-password checks), how a second factor is added (TOTP, passkeys, recovery codes), and how the proof is carried afterwards (server-side sessions, JWTs, opaque tokens, refresh tokens). Focus: Identity vs authentication vs authorization, NIST SP 800-63B-4 password policy, Argon2id/scrypt/bcrypt/PBKDF2 parameters with measured costs, pepper and rehash on login, credential stuffing, password spraying, enumeration and timing attacks, rate limits per account and IP, lockout vs progressive delay, CAPTCHA and risk-based authentication, MFA and AAL levels, TOTP/HOTP (RFC 6238/4226) with drift windows and replay protection, SMS/email OTP, push and MFA fatigue, WebAuthn/FIDO2 passkeys (ceremonies, attestation, discoverable credentials, synced passkeys), recovery codes, sessions vs JWT vs opaque tokens with introspection, refresh token rotation and reuse detection, DPoP, password reset, remember me, logout everywhere, step-up authentication, audit events, and the products: Laravel Fortify/Sanctum/Passport, Keycloak, Auth0, Okta, Cognito, Ory, go-webauthn, pquerna/otp. Learning goal: Design a login system from the password form to the last logout: pick the hashing parameters from numbers, make every failure look the same, stop online guessing without letting attackers lock users out, add a phishing-resistant second factor with a recovery path, choose sessions or tokens per client, and make "reset password" and "log out everywhere" actually end every session.

This chapter is the system-design view of authentication: the decisions, the numbers and the flows. Neighbours keep their depth: Password Hashing & Signed Tokens teaches how bcrypt and Argon2 work inside and how tokens are signed; Web Sessions, Cookies, Serialization & CORS owns cookie attributes, CSRF and CORS; JWT Deep Dive owns JWT structure, algorithms and validation; OAuth 2.0, OpenID Connect & Single Sign-On owns delegated login and SSO; Authorization Models decides what an authenticated user may do; Mutual TLS & Securing Service-to-Service Traffic authenticates machines; Rate Limiting owns the limiter algorithms; Authentication in Go is the Go-only walkthrough; Security Foundations gives the threat-modelling frame.

Page map ​

If you are looking forGo to
The whole page in three tablesEverything in one minute
Why authentication is a system, not a formWhy it exists
From Unix crypt to NIST SP 800-63B-4 and passkeysWhere it comes from
Identity vs authentication vs authorizationIdentity, authentication, authorization
Length, blocklists, no composition rules, no rotationPassword policy
Argon2id, scrypt, bcrypt, PBKDF2 and their parametersPassword hashing
Salt, pepper, rehash on login, migrating old hashesPepper and rehash
Brute force, credential stuffing, password sprayingOnline attacks
"No account with that email", timing differencesEnumeration and timing
Per-account and per-IP limits, lockout, CAPTCHA, risk scoringThrottling and lockout
Factors, AAL1/2/3, phishing resistanceMFA
TOTP/HOTP, QR provisioning, drift window, replayTOTP and HOTP
SMS, email, push, SIM swap, MFA fatigueSMS, email and push
WebAuthn ceremonies, attestation, passkeysWebAuthn and passkeys
Recovery codes and account recoveryRecovery
Server-side sessions and cookiesSessions
JWT, opaque tokens, introspectionTokens
Refresh token rotation, reuse detection, DPoPRefresh tokens
Forgot-password flowPassword reset
Remember me, logout everywhere, step-upSession lifecycle
SSO, OAuth, service-to-serviceSSO and machines
What to logAuditing
Hash formats, timings, knobs, error messagesMechanics
CodeGo, Laravel
Eleven classic failures and their fixesSolving the classic problems
Which hash, which factor, sessions or tokens, build or buyChoosing
From a monolith to many regionsIn architecture
Runnable timings and expected experimentsLab
Wrong beliefs, summary, quiz, termsMisconceptions, Cheat sheet, Self-check, Glossary

Everything in one minute ​

Storing passwords.

ChoiceParameters to start fromUse whenWatch out
Argon2idOWASP minimum m=19 MiB, t=2, p=1; RFC 9106 second option m=64 MiB, t=3, p=4New systemsMemory per login: 64 MiB x 50 parallel logins = 3.2 GB
scryptN=2^17, r=8, p=1 (OWASP)Argon2id is not availableSame memory planning
bcryptcost 10 minimum (OWASP), 12 is the Laravel and PHP 8.4+ defaultLegacy, or Argon2 missingOnly the first 72 bytes count
PBKDF2-HMAC-SHA256600,000 iterations (OWASP)FIPS 140 validated crypto is requiredNot memory-hard: GPUs love it
Pepper32 random bytes in a KMS/HSM, HMAC before hashingDefence against a database-only leakRotating it needs every user to log in or reset
SHA-256, MD5, plainneverneverBillions of guesses per second per GPU

Stopping guessing.

AttackWhat it looks likePrimary defence
Brute forceMany passwords, one accountPer-account throttling, long passwords, MFA
Credential stuffingLeaked email/password pairs from another site, many accounts, many IPsBreached-password check, MFA, bot detection, per-IP and global signals
Password sprayingOne common password ("Winter2026!") against many accountsBlocklist of common passwords, per-IP limits, global failure-rate alarms
Enumeration"No account with that email", faster answers for unknown usersSame message, same status, dummy hash, same timing
Phishing / real-time proxyFake login page relays password and OTPPasskeys/WebAuthn (origin-bound), not OTP
MFA fatigueDozens of push prompts at 2 a.m.Number matching, push rate limits, passkeys

Carrying the proof.

MechanismWhere state livesRevocationBest for
Server-side session + cookieRedis or a sessions tableDelete the row: instantBrowser apps on your own domain
Stateless JWT access tokenIn the token (signed claims)Waits for exp (or a deny list)Service-to-service, short-lived (5 to 15 min)
Opaque access token + introspectionAuthorization serverInstant (or the cache TTL)Third-party APIs, high-value scopes
Refresh token with rotationAuthorization server, one row per tokenRevoke the familyMobile and SPA clients that must stay signed in
Sanctum personal access tokenpersonal_access_tokens (SHA-256)Delete the rowLaravel API keys, first-party mobile apps

Why it exists ​

Every request reaching your server is anonymous bytes. Authentication is the step that attaches an account to those bytes with some level of confidence, and then keeps that attachment cheap for the next thousand requests. It has to work against three kinds of adversary at once: one who guesses online (tries passwords on your login form), one who has stolen your database (and guesses offline at GPU speed), and one who tricks the user (phishing, SIM swap, push fatigue). A choice that helps against one often hurts against another: a hard lockout stops guessing but lets anyone lock your CEO out; a long-lived JWT saves a database lookup but cannot be revoked.

Simpler, cheaperStronger, costlier
Fast hash, no pepperArgon2id with tuned memory, pepper in a KMS
Password onlyPassword + TOTP, or a passkey alone (two factors in one gesture)
Long-lived stateless JWTShort JWT + rotating refresh token, or a server-side session
Detailed error messagesOne generic message and an audit log for the details
Lock the account after 5 failuresProgressive delays, per-IP limits, risk scoring, notify the user
Email a reset link with the user idSingle-use, hashed, short-lived token; sessions revoked afterwards

The analogy used through this page: a hotel. The front desk checks your passport once (authentication) and gives you a key card (session or token). The card opens your room and the gym, not the manager's office (authorization). The desk keeps a register of which cards are valid, so a lost card can be cancelled at once (server-side session); a printed paper pass that says "room 305, valid until Friday" works without the register but cannot be cancelled (a stateless JWT). The master copy of the guest list is locked in a safe (password hashes), and the safe's combination is kept in a different building (the pepper).

Three common misunderstandings, up front ​

  1. "Strong passwords need uppercase, digits and symbols, changed every 90 days." NIST SP 800-63B-4 says the opposite: verifiers "SHALL NOT impose other composition rules" and "SHALL NOT require subscribers to change passwords periodically". Users answer composition rules with Password1!; length and a blocklist work better.
  2. "MFA makes phishing impossible." A six-digit code typed into a fake page is relayed in real time; NIST says OTP and out-of-band authenticators "SHALL NOT be considered phishing-resistant". Only origin-bound cryptographic authenticators (WebAuthn, client certificates) are.
  3. "JWTs are more secure than sessions." They are a different trade: no lookup, but no instant logout either. For a browser talking to its own backend, a server-side session in an HttpOnly cookie is usually the safer default.

Where it comes from ​

  • 1979, Unix crypt. Morris and Thompson's "Password Security: A Case History" introduced salted, deliberately slow password hashing on Unix (secondary source for the date; the principle survives in every modern scheme).
  • 1999, bcrypt. Provos and Mazières' bcrypt added an adjustable cost factor. Its 72-byte input limit still matters: Go's bcrypt.GenerateFromPassword returns ErrPasswordTooLong ("password length exceeds 72 bytes"), while PHP 8.5's password_hash silently ignores the rest (we tested both; see Mechanics).
  • 2005 and 2011, HOTP and TOTP. RFC 4226 defined the HMAC-based one-time password; RFC 6238 made it time-based with a recommended "default time-step size of 30 seconds". Google Authenticator made it mainstream.
  • 2009 and 2017, scrypt and PBKDF2 guidance. scrypt introduced memory-hardness; PBKDF2 remained the FIPS-approved option, which is why OWASP still lists it "if FIPS-140 compliance is required".
  • 2015 to 2021, Argon2. Argon2 won the Password Hashing Competition (2015); RFC 9106 (September 2021) standardised it and recommends Argon2id with "t=1 iteration, p=4 lanes, m=2^(21) (2 GiB of RAM)" as the first option and 64 MiB, t=3 as the second.
  • 2017, NIST SP 800-63B (rev 3). Dropped composition rules and forced rotation and introduced breached-password blocklists. July 2025, SP 800-63B-4 (final, published 31 July 2025 per CSRC) raised single-factor passwords to "a minimum of 15 characters", made the PSTN (SMS, voice) a restricted authenticator, added syncable authenticators (passkeys) and described phishing resistance precisely.
  • 2019 to 2026, WebAuthn. W3C Web Authentication Level 1 (2019), Level 2 (2021), and Level 3, a W3C Recommendation dated 25 August 2026, which defines an API for "strong, attested, scoped, public key-based credentials". FIDO Alliance and the platform vendors branded discoverable, synced WebAuthn credentials as passkeys.
  • 2012 to 2025, tokens. OAuth 2.0 (RFC 6749, 2012) introduced refresh tokens; RFC 7662 (2015) token introspection; RFC 8471 (2018) Token Binding; RFC 9449 (2023) DPoP; RFC 9700 (January 2025), the OAuth 2.0 Security Best Current Practice, requires that "Refresh tokens for public clients MUST be sender-constrained or use refresh token rotation".

The concept catalogue ​

Each block follows the same order: plain words, the usual wrong belief, a definition, a timeline, real scenarios, what products do, and the fix.

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

Identity, authentication, authorization Must-know ​

In plain words: identity is who you are in the system (account 42, with an email, a name and attributes); authentication is proving that the current request comes from that identity; authorization is deciding what that identity may do now.

Common misunderstanding: "The user is logged in, so the request is allowed." Being authenticated says nothing about whether account 42 may read invoice 9001. Mixing them produces IDOR bugs (insecure direct object references): the login works perfectly and every user can read every invoice.

Definition: an identity (NIST: subscriber account) is a set of attributes bound to a person or service. A credential or authenticator is something the claimant controls (a password, a TOTP secret, a private key). Authentication verifies that the claimant controls authenticators bound to the account and produces an authentication event with a time and a set of methods (RFC 8176 names them pwd, otp, hwk, mfa, sms...). A session carries that event forward. Authorization then evaluates policy (RBAC, ABAC, ReBAC) against the identity and the resource.

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

Real scenario: a B2B SaaS where SSO through Okta authenticates the employee but the app decides whether they are an admin of tenant 17; a support agent impersonating a user (authenticated as the agent, authorized as the user, audited as both); a mobile banking app that is logged in but needs a fresh face scan to send money (step-up); an API key that authenticates a partner's server but is scoped to orders:read.

What provides it:

Concern401 or 403Product examples
Not authenticated401 Unauthorized (with WWW-Authenticate for APIs)Laravel auth middleware redirects or returns 401; Go middleware
Authenticated, not allowed403 ForbiddenLaravel Gates/Policies, OPA, Cedar, OpenFGA
Authenticated, but not recently enough401/redirect to re-authenticateLaravel password.confirm, OIDC max_age/acr_values
Identity providern/aKeycloak, Auth0, Okta, Amazon Cognito, Ory Kratos, Microsoft Entra ID

Fix / how to use it: keep three separate modules: an identity store (users, credentials), an authenticator (produces user_id, amr, auth_time), and an authorizer (policies). Pass the authentication result as a small struct, not as "the user object", so code that needs freshness or factors can check them. Authorization is the subject of Authorization Models.

Password policy (NIST SP 800-63B-4) Must-know ​

In plain words: require length, check the password against a list of known-bad ones, and stop there. Let people paste, use spaces and emoji, and see what they typed.

Common misunderstanding: "Composition rules and 90-day rotation make passwords stronger." NIST's appendix explains that users respond "in very predictable ways": password becomes Password1, then Password1!. Rotation produces Spring2026! followed by Summer2026!.

Definition: the SP 800-63B-4 password verifier rules, quoted from section 3.1.1.2:

RuleNIST SP 800-63B-4 wording
Minimum length"a minimum of 15 characters" for single-factor use; at least eight when the password is only part of MFA
Maximum length"SHOULD permit a maximum password length of at least 64 characters"
Character set"SHOULD accept Unicode"; each code point counts as one character; normalise with NFC before hashing
Composition"SHALL NOT impose other composition rules (e.g., requiring mixtures of different character types)"
Rotation"SHALL NOT require subscribers to change passwords periodically" but "SHALL force a change if there is evidence" of compromise
Blocklist"SHALL compare the prospective secret against a blocklist that contains known commonly used, expected, or compromised passwords" (the entire password, not substrings)
Hints and KBA"SHALL NOT prompt subscribers to use knowledge-based authentication (KBA)" or security questions
Truncation"SHALL verify the entire submitted password (e.g., not truncate it)"
Show password"SHOULD offer an option to display the password" while typing
Password managersAllow paste and autofill (usability appendix)
text
     User types                        Old policy (8 chars, 1 upper, 1 digit, 1 symbol)   NIST SP 800-63B-4 (15 chars + blocklist)
1    "Password1!"                      accepted                                           rejected: in breach corpus
2    "correct horse battery staple"    rejected: no uppercase, no digit                   accepted
3    "Summer2026!" (rotation month 3)  accepted                                           rejected: too short, common pattern
4    "🔑 my keys live in the blue bowl" rejected: emoji not allowed                      accepted, NFC-normalised, 30 code points

Real scenario: a sign-up page that rejected passphrases and pushed users to Company2026!; a bank whose "max 12 characters" rule broke password managers; an employee portal with 90-day rotation whose help desk spent a third of its calls on resets; a password that was in the RockYou list and fell to the first spraying run.

What provides it:

ProductLength and blocklistNotes
Laravel Password rulePassword::min(15)->max(128)->uncompromised()uncompromised() uses the haveibeenpwned.com k-Anonymity range API (first five SHA-1 characters, Add-Padding: true); mixedCase(), symbols() exist but NIST says do not use them
Have I Been Pwned Pwned PasswordsGET https://api.pwnedpasswords.com/range/{first 5 SHA-1 chars}Free, k-anonymity, can be mirrored offline
Keycloak password policiesLength, "Not Recently Used", "Password Blacklist" file, also composition rules (switch those off)Per realm
Amazon CognitoMinimum length, optional character classes, compromised-credentials protection in its threat protection featuresPer user pool
Auth0Password strength levels, Breached Password DetectionTenant setting

Fix / how to use it: minimum 15 (or 8 when MFA is mandatory for everyone), maximum at least 64 characters (this chapter's Go code caps at 1024 bytes to stop a denial of service), NFC normalisation, a blocklist check on set and change, a strength meter as guidance, autocomplete="new-password" and a show-password toggle. Force a reset only on evidence: a breach match, a known leak, or detected stuffing success.

Password hashing: Argon2id, scrypt, bcrypt, PBKDF2 Must-know ​

In plain words: store a slow, salted fingerprint of the password, never the password. Slow means each guess costs the attacker real CPU and memory once they have your database.

Common misunderstanding: "SHA-256 is a secure hash, so it is fine for passwords." SHA-256 is designed to be fast; that is exactly wrong here. A password hash must be deliberately expensive, and Argon2id and scrypt are also memory-hard, so a GPU with thousands of cores cannot run thousands of guesses in parallel cheaply.

Definition: a password hashing scheme takes a password, a per-user random salt and a cost, and outputs a verifier. NIST: "Password hashing schemes take a password, a salt, and a cost factor as inputs and generate a password hash." The salt "SHALL be at least 32 bits"; the scheme and cost "SHOULD be stored for each password to allow migration". The four schemes in use:

SchemeCost knobsOWASP Password Storage Cheat Sheet starting pointMemory-hardNotes
Argon2idmemory m (KiB), time t (passes), parallelism p (lanes)m=47104 (46 MiB) t=1 p=1, or m=19456 (19 MiB) t=2 p=1, or m=12288 t=3, m=9216 t=4, m=7168 t=5 ("equal level of defense")YesRFC 9106; "increasing p does not multiply the total memory"
scryptN (CPU/memory), r (block size), pN=2^17 (128 MiB), r=8, p=1YesUse when Argon2id is missing
bcryptcost (log2 rounds)"minimum of 10"No (4 KiB)72-byte input limit; $2y$ / $2a$ / $2b$ prefixes
PBKDF2iterations, PRFHMAC-SHA-256: 600,000; HMAC-SHA-512: 220,000NoThe FIPS 140 choice; NIST SP 800-132
text
     Attacker with a stolen users table, one GPU, guessing "Summer2026!"-style candidates
1    unsalted SHA-256    one hash per candidate covers every user; rainbow tables work          (billions per second)
2    salted SHA-256      one hash per candidate per user; still fast                             (billions per second)
3    bcrypt cost 12      ~190 ms per guess on one CPU core (this chapter's lab)                  (a few per second per core)
4    Argon2id 19 MiB t=2 ~16-23 ms per guess, and each guess needs 19 MiB of memory              (memory bandwidth bound)
5    + pepper in a KMS   without the pepper, no guess can be checked at all

Real scenario: LinkedIn's 2012 leak of unsalted SHA-1 hashes (widely reported; secondary source) cracked in days; a SaaS migrating 2 million bcrypt cost-10 hashes to Argon2id as users log in; a government system that must use PBKDF2 because only FIPS-validated modules are allowed; a login service on 2 vCPU pods where 64 MiB Argon2id and 50 concurrent logins means 3.2 GB of memory just for hashing.

What provides it:

PlatformDefaultHow to change
Laravel 13 (config/hashing.php)bcrypt, rounds 12; argon memory 65536, time 4, threads 1HASH_DRIVER=argon2id, BCRYPT_ROUNDS, ARGON_MEMORY, ARGON_TIME, ARGON_THREADS, BCRYPT_LIMIT
PHP 8.5 password_hash (measured)PASSWORD_BCRYPT cost 12; PASSWORD_ARGON2ID m=65536, t=4, p=1Options array
Go golang.org/x/crypto/argon2No default: IDKey(password, salt, time, memory, threads, keyLen); docs show the RFC 9106 first optionYou choose and encode the PHC string yourself
Go golang.org/x/crypto/bcryptDefaultCost 10, MinCost 4, MaxCost 31GenerateFromPassword(pw, cost); Cost(hash) to read it back
Keycloak"Argon2 (default for non-FIPS deployments)"; PBKDF2 variants for FIPSRealm password policy "Hashing Algorithm", "Hashing Iterations"
Spring Security, DjangoDelegatingPasswordEncoder with {bcrypt} prefix; Django PBKDF2 by default with Argon2 optionalFramework settings

Fix / how to use it: new systems use Argon2id. Measure on the production instance type and pick the largest parameters that keep a login under about 100 ms and fit memory times peak concurrent logins. Store the full PHC string ($argon2id$v=19$m=...,t=...,p=...$salt$hash) so parameters can change later. Code: pwhash.go.

Salt, pepper and rehash on login Important ​

In plain words: the salt makes every user's hash different; the pepper is one secret key kept outside the database, so a database dump alone is useless; rehash on login upgrades old hashes the moment the user proves they know the password.

Common misunderstanding: "A pepper is just a second salt." A salt is public and stored next to the hash; a pepper is secret and stored elsewhere (KMS, HSM, a secrets manager). OWASP: "the pepper should not be public and should not be stored along with the generated hash." And unlike a salt, a pepper cannot be rotated without the plaintext: "changing a pepper will require forcing all users whose passwords were protected by the previous pepper to reset their passwords" (unless you wrap: store HMAC(newPepper, oldHash) and rehash at the next login).

Definition: NIST SP 800-63B-4: verifiers "SHOULD perform an additional iteration of a keyed hashing or encryption operation using a secret key known only to the verifier", stored "separately from the hashed passwords", ideally "within a hardware-protected area". OWASP lists two forms: pre-hashing (HMAC the password, then Argon2id) and post-hashing (Argon2id, then HMAC or encrypt the result). Rehash on login: after a successful verify, if the stored hash uses an old algorithm or weaker parameters, compute the new hash and save it.

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

Real scenario: moving 1.8 million legacy MD5 hashes by wrapping them (argon2id(md5)) on day one and unwrapping at each login; a pepper kept in AWS KMS so a SQL-injection dump yields nothing crackable; a bcrypt-to-Argon2id migration that silently stopped because the login path used Auth::validate(), which does not rehash; a dummy hash whose parameters lag behind the real ones and therefore answer faster.

What provides it:

PlatformRehash on loginPepper
Laravel 13rehash_on_login (default true) in Auth::attempt() and the starter kits; Hash::needsRehash() for custom flowsNot built in: HMAC before Hash::make, keep the key outside .env if you can
PHPpassword_needs_rehash($hash, $algo, $options)Manual
Go (this chapter)Verify returns needsRehash for other parameters or bcryptHasher.Pepper, HMAC-SHA-256 pre-hash
Djangocheck_password upgrades automaticallySECRET_KEY is not a pepper; manual
KeycloakRe-hashes on login when the realm policy changesn/a

Fix / how to use it: store the algorithm and parameters with each hash (PHC string); call needsRehash on every successful login path, including custom ones; keep the dummy hash generated with the current parameters; if you add a pepper, version it (kid next to the hash) so a later rotation is a per-login upgrade, not a mass reset.

Online attacks: brute force, credential stuffing, password spraying Must-know ​

In plain words: brute force hammers one account with many passwords; credential stuffing replays email/password pairs leaked from other sites; password spraying tries one or two very common passwords on many accounts, slowly, to stay under per-account limits.

Common misunderstanding: "Our per-account lockout stops all of these." It stops only brute force. Stuffing tries each account once or twice (with the user's real old password), from thousands of residential IPs; spraying tries one password per account per day. Neither ever reaches a per-account threshold.

Definition: OWASP's Credential Stuffing Prevention Cheat Sheet treats stuffing and spraying together and puts MFA first: "by far the best defense against the majority of password-related attacks". Then layered controls: breached-password checks, CAPTCHA, IP reputation, device fingerprinting, connection fingerprinting, requiring unpredictable usernames, multi-step login, and notifying users of unusual logins.

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

Real scenario: a streaming service whose login success rate dropped from 70% to 2% overnight (stuffing with a purchased combo list); a university where spraying Autumn2026! hit 40 staff accounts in a week; a game company whose attackers used residential proxies so per-IP limits never fired; an API login endpoint without the CAPTCHA the web form had, so bots used the API.

What provides it:

ProductRelevant controls
CloudflareBot Management, Turnstile (CAPTCHA alternative), leaked credentials detection (adds a request header when a submitted credential pair is known to be leaked; the older "Exposed-Credential-Check" header is deprecated), rate limiting rules on /login
AWSAWS WAF Fraud Control account takeover prevention (ATP) managed rule group; Cognito threat protection (compromised credentials, adaptive authentication)
Auth0Brute-force protection, suspicious IP throttling, Breached Password Detection, Bot Detection
OktaThreatInsight, adaptive MFA, Okta FastPass (phishing-resistant)
KeycloakBrute Force Detection (per user), with lockout modes; IP-level limits must come from a proxy/WAF
Laravelthrottle:login named limiter, Fortify EnsureLoginIsNotThrottled (email + IP), Password::uncompromised() at registration

Fix / how to use it: MFA for everyone you can; breached-password checks at sign-up, change and login (warn and force a reset on match); throttles on several keys at once (account, IP, IP subnet, device, global failure rate); bot detection in front of the login API, not only the HTML form; alert on a sudden drop of the login success ratio.

Account enumeration and timing attacks Must-know ​

In plain words: if your login, sign-up or reset page answers differently for "this email exists" and "it does not", an attacker can build a list of your customers and then attack only them. Differences can be in the message, the status code, a redirect, a header, or just the time it takes.

Common misunderstanding: "We show the same message, so we are safe." If unknown emails return in 2 ms and known ones in 190 ms (because only they run bcrypt), the stopwatch tells the attacker what the message hides. OWASP spells this out: when the user does not exist "the application will directly throw an error", so "the response time will be different".

Definition: OWASP Authentication Cheat Sheet: "an application must respond with a generic error message regardless of whether" the user ID or password was wrong, the account does not exist, or it is locked or disabled, on login, password reset and recovery. Example of wrong and right: "Login for User foo: invalid password." versus "Login failed; Invalid user ID or password." Constant-time comparison (subtle.ConstantTimeCompare, hash_equals) stops byte-by-byte timing leaks inside one comparison; a dummy hash for unknown users stops the much larger "no hashing happened" leak.

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

Real scenario: an attacker enumerating which emails have accounts on a dating site before extorting them; a B2B app where the sign-up form confirmed which competitors were customers; a reset endpoint whose ResetThrottled message only appeared for real accounts; an OTP endpoint whose 6-digit comparison used == on strings.

What provides it:

Product / APIBehaviour
Laravel SessionGuard::attempt() and validate()Run inside a Timebox of 200,000 µs (200 ms) that returns early only on success, so failures take at least 200 ms. If your hash takes longer than 200 ms, wrong-password failures are slower than unknown-user failures again
Laravel lang auth.failed"These credentials do not match our records." (uniform)
Laravel lang passwords.user"We can't find a user with that email address." (enumeration by default: replace it)
Gocrypto/subtle.ConstantTimeCompare; no framework: you write the dummy verification yourself
PHPhash_equals(), password_verify() (constant time for equal-length input)
WebAuthn Level 3Section 14.6.2 "Username Enumeration" discusses the same leak for passkey flows

Fix / how to use it: one message for login failures; one message for reset requests, sent from a queued job so timing is equal; registration that always says "check your inbox" and emails the existing owner instead of saying "taken"; a dummy hash with current parameters; ConstantTimeCompare for every secret comparison; the same status code and response shape on every branch.

Throttling, lockout, CAPTCHA and risk-based authentication Must-know ​

In plain words: limit how many guesses anyone can make, but do it so that an attacker cannot use your limit to lock real users out. Slow down instead of slamming the door, count by more than one key, and ask for more proof when something looks unusual.

Common misunderstanding: "Lock the account for 30 minutes after five failures." That is a denial-of-service button: anyone who knows your CEO's email can keep them locked out forever. NIST allows up to 100 consecutive failures before disabling an authenticator and recommends delays and bot challenges in between.

Definition: NIST SP 800-63B-4 (Rate Limiting): the verifier "SHALL limit consecutive failed authentication attempts using a specific authenticator on a single subscriber account to no more than 100", may add a bot challenge, waits that grow "(e.g., 30 seconds up to an hour)", and risk-based techniques using "IP address, geolocation, timing of request patterns, or browser metadata"; after a success it "SHOULD disregard any previous failed attempts". OWASP adds the three lockout knobs: lockout threshold, observation window, lockout duration, and suggests exponential lockout. Risk-based (adaptive) authentication scores each attempt (new device, impossible travel, Tor exit, known-bad IP) and adds a step (MFA, CAPTCHA) or blocks.

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

Real scenario: a support queue flooded by "I'm locked out" tickets after a botnet targeted every employee email; a consumer app that shows a Turnstile challenge only after the third failure; a bank that requires MFA for logins from a new device and blocks logins from a country the customer never used; an exponential delay that lets the user in after a few seconds while making 10,000 guesses take years.

What provides it:

ProductMechanism and defaults (from their docs)
Laravel starter kits / Fortify"throttling is unique to the user's username / email address and their IP address"; Fortify stub: Limit::perMinute(5) keyed by email plus IP; two-factor limiter 5/min by login.id; passkeys 10/min
Keycloak Brute Force DetectionModes include temporary and permanent lockout; permanent lockout defaults: Max Login Failures 30, Quick Login Check Milliseconds 1000, Minimum Quick Login Wait 1 minute
Auth0Brute-force protection (per user per IP), suspicious IP throttling
Amazon CognitoAdvanced security adaptive authentication (low/medium/high risk actions)
Cloudflare / AWS WAFRate limiting rules on the login path, managed bot rules, ATP
GoNo framework: counters in Redis (INCR + EXPIRE, or a Lua token bucket), see Rate Limiting

Fix / how to use it: throttle before hashing (a throttled attempt must not cost you 20 ms of Argon2id); count per account (normalised email, also for unknown emails), per IP and per /24 or /64, and globally; use progressive delays and a CAPTCHA step rather than hard lockout; disable the password (not the account) at the hard limit and let the reset flow re-enable it; notify the user by email after unusual failures; feed risk signals into "require MFA" rather than "deny".

MFA, factors and assurance levels Must-know ​

In plain words: combine two different kinds of proof (something you know, something you have, something you are) so that stealing one is not enough. 2FA is MFA with exactly two factors.

Common misunderstanding: "Any second factor is equally good." An SMS code can be stolen by SIM swap and relayed by a phishing page; a TOTP code can be relayed too; a passkey signs the website's origin and is useless on a fake domain. NIST places them at different levels and calls only the last "phishing-resistant".

Definition: NIST SP 800-63B-4 Authentication Assurance Levels: AAL1 (single factor allowed; reauthentication "no more than 30 days"), AAL2 (two factors; reauthentication within 24 hours, inactivity no more than 1 hour; a phishing-resistant option must be offered), AAL3 (a cryptographic authenticator with a "non-exportable private key" that "SHALL provide phishing resistance"; 12 hours overall, 15 minutes inactivity). Phishing resistance is "the ability of the authentication protocol to prevent the disclosure of authentication secrets and valid authenticator outputs to an impostor verifier ... without relying on the vigilance of the claimant", achieved by channel binding (client-authenticated TLS) or verifier name binding (WebAuthn).

FactorKindPhishing-resistantNIST statusTypical product
PasswordKnowNoAllowed; 15+ chars aloneEvery login form
TOTP appHaveNo (code can be relayed)Allowed (multi-factor OTP when the app is locked)Google Authenticator, Microsoft Authenticator, 1Password, Authy
SMS / voice OTPHave (phone number)NoRestricted authenticatorTwilio Verify, Cognito SMS MFA
Email OTP / magic linkHave (mailbox)NoNot an AAL2 out-of-band authenticatorCognito email MFA, Auth0 passwordless
Push approval (with number matching)HaveNoAllowed; prompts must be rate-limitedOkta Verify, Duo, Microsoft Authenticator
Passkey (synced)Have + (know or are)YesSyncable authenticator, AAL2iCloud Keychain, Google Password Manager, 1Password
Security key / device-bound passkeyHave + (know or are)YesAAL3 when hardware-protectedYubiKey, Titan, Windows Hello with TPM
Recovery codeKnow (saved secret)NoRecovery only, 64+ bits, single useEvery MFA product

Real scenario: a fintech that must reach AAL2 for regulators and chooses passkeys first, TOTP second, SMS only as a last resort; an admin console that requires a hardware key (AAL3); a consumer app that offers MFA but makes it optional (and sees 5% adoption); a company that enforced push MFA and was breached through push bombing.

Fix / how to use it: offer passkeys first, TOTP second, SMS last (and never as the only option); require at least two methods or saved recovery codes so a lost phone is not a lost account; record amr and auth_time on the session; ask for MFA again for high-risk actions (step-up).

TOTP and HOTP Must-know ​

In plain words: the server and the phone share a random secret. Every 30 seconds both compute HMAC(secret, current 30-second step), cut it to six digits, and compare. No network is needed on the phone.

Common misunderstanding: "A TOTP code is valid for 30 seconds, so replay is not a problem." RFC 6238 is explicit: "The verifier MUST NOT accept the second attempt of the OTP after the successful validation has been issued for the first OTP." With a drift window of ±1 step a code is acceptable for up to 90 seconds; without a "last used step" check a shoulder-surfer or relay can use it again.

Definition: HOTP (RFC 4226): HOTP(K, C) = Truncate(HMAC-SHA-1(K, C)) mod 10^d, with dynamic truncation picking four bytes at an offset taken from the last nibble. TOTP (RFC 6238): C = floor((now - T0) / X) with X = 30 s recommended and T0 = 0; HMAC-SHA-1, SHA-256 or SHA-512. Drift: "We RECOMMEND that at most one time step is allowed as the network delay"; resynchronisation can record a detected drift per user. HOTP servers use a look-ahead window s and a throttling parameter T. Provisioning uses the otpauth://totp/Issuer:account?secret=BASE32&issuer=...&algorithm=SHA1&digits=6&period=30 URI, shown as a QR code. NIST: the verifier "SHALL accept a given OTP only once while it is valid" and OTPs shorter than 64 bits need the rate limit.

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

Real scenario: a SaaS that enabled TOTP but forgot the replay check, found by a pentest; a user whose phone clock was off by 3 minutes (the fix is phone time sync, not a ±10 window); 6-digit codes with no rate limit (100 guesses per account per hour gives a 1-in-10,000 chance per hour; NIST chose its 100-attempt limit with exactly this arithmetic in mind); TOTP secrets stored in plaintext next to password hashes, so one SQL injection gives the attacker both factors.

What provides it:

ProductDetails
Laravel FortifySix-digit TOTP via pragmarx/google2fa; secret and recovery codes stored encrypted; confirm step before enabling; optional window; replay blocked by caching used timestamps (verifyKeyNewer plus a cache key per code)
Go github.com/pquerna/otp v1.5.0totp.Generate(GenerateOpts{Issuer, AccountName}), totp.ValidateCustom(code, secret, t, ValidateOpts{Period, Skew, Digits, Algorithm}); Skew "Values greater than 1 are likely sketchy"; no replay store: you add it
This chapter's Go totp packageStandard library only, RFC test vectors, Verify(key, code, lastStep)
KeycloakOTP policy per realm: TOTP/HOTP, algorithm, digits, look-around window, period
Amazon Cognito"TOTP software token MFA"
Auth0, OktaGuardian / Okta Verify OTP, plus any TOTP app

Fix / how to use it: 160-bit secret from a CSPRNG; show the QR and the Base32 text; require one valid code before enabling ("confirm"); encrypt the secret at rest with a key outside the database; skew 1; store the last accepted step in the same transaction as the login; rate limit per pending login (5 per minute in Fortify); issue recovery codes at enrolment. Code: totp.go, Totp.php.

SMS, email OTP and push; MFA fatigue Important ​

In plain words: codes sent over SMS or email, or a push "Approve?" prompt, are easy for users but each has a known way to fail: SIM swap and SS7 interception for SMS, a compromised mailbox for email, and "approve to make it stop" for push.

Common misunderstanding: "SMS is still MFA, so it is fine for admins." NIST SP 800-63B-4 lists PSTN delivery as a restricted authenticator: organisations must offer an unrestricted alternative, warn users, and have a migration plan; OWASP: "Do not use SMS for high-value or PII-handling applications."

Definition: SIM swap: the attacker convinces the carrier to move the victim's number to a new SIM, then receives the codes. SMS pumping / toll fraud: bots request codes to premium numbers to make you pay ("Calls and SMS messages may cost money to send", OWASP). MFA fatigue (push bombing): "Attackers repeatedly send MFA push notifications, often combined with social engineering, hoping the user eventually approves one." NIST no longer accepts approve-only out-of-band flows ("This method is no longer considered acceptable"), and requires the secret to be transferred between channels; push verifiers "SHOULD implement a reasonable limit on the rate or total number of push notifications".

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

Real scenario: a crypto exchange customer losing funds after a SIM swap; an SMS bill of thousands of dollars from bots hitting /send-code with premium numbers; a large company breached through push bombing of a contractor; an email OTP that is useless because the mailbox uses the same password.

What provides it:

ProductControl
Microsoft Authenticator, Okta Verify, DuoNumber matching, location and app context in the prompt
OktaOkta FastPass (device-bound, phishing-resistant), ThreatInsight
Amazon CognitoSMS and email message MFA (email needs SES), TOTP; passkeys as first factor
Twilio VerifyFraud Guard against SMS pumping, geo permissions
NIST risk indicators before PSTN"device swap, SIM change, number porting, other abnormal behavior"

Fix / how to use it: if you must send SMS, rate limit per number and per account, block premium ranges, check SIM-swap signals, and never let SMS alone reset a password and MFA; for push, use number matching and cap prompts; for everything, prefer passkeys.

WebAuthn, FIDO2 and passkeys Must-know ​

In plain words: the user's device creates a key pair for your domain. The public key goes to your server; the private key never leaves the device (or the user's synced keychain). To log in, the device signs a fresh challenge from your server, and the browser includes the site's origin in what is signed, so a fake domain gets a signature that is useless on the real one.

Common misunderstanding: "A passkey is a password stored in the cloud." Nothing secret is sent or stored on the server; a database leak exposes only public keys. And "passkeys are always device-bound": synced passkeys are copied (end-to-end encrypted) across the user's devices by the passkey provider; device-bound passkeys on a security key are not.

Definition: WebAuthn Level 3 (W3C Recommendation, 25 August 2026) defines a Relying Party (your site), its RP ID (a domain; "A public key credential can only be used for authentication with the same entity (as identified by RP ID) it was registered with"), authenticators (platform: Face ID, Touch ID, Windows Hello; roaming: security keys), and two ceremonies. Registration (navigator.credentials.create()) returns a credential ID, public key and an attestation object; authentication (navigator.credentials.get()) returns an assertion (signature over authenticatorData and the hash of clientDataJSON, which contains the origin and the challenge). A discoverable credential (formerly "resident key") lets the user sign in without typing a username; user presence (UP) and user verification (UV: PIN or biometric) are flags; backup eligibility (BE) and backup state (BS) say whether it is a multi-device (synced) credential; the signature counter helps detect cloned authenticators ("a signal, but not proof"). FIDO2 = WebAuthn + CTAP2 (the browser-to-authenticator protocol). FIDO Alliance: "Passkeys can be securely synced across a user's devices, or bound to a particular device (device-bound passkeys)."

AuthenticatorBrowser (client)Relying Party serverRegistration creates a key pair; authentication proves possession of itchallenge, rp.id, user.id, residentKeycredentials.create()UP + UV (PIN, biometric);new key pair for this RP IDpublic key, credential ID, attestation+ clientDataJSON (origin, challenge)check challenge,origin, rpIdHash,flags; store keynew challenge (+ allowCredentials or none)credentials.get()sign authenticatorData +assertion: signature, userHandlehash(clientDataJSON)+ clientDataJSONverify signaturewith stored keyREGISTRATIONAUTHENTICATION
text
     Phishing attempt against a passkey user
1    victim opens https://examp1e-login.test (look-alike)       page calls navigator.credentials.get()
2    browser: RP ID must be a suffix of examp1e-login.test         no credential for that RP ID exists -> nothing to sign
3    attacker proxies to the real site instead                     real site's challenge is signed with origin = examp1e-login.test
4    real server checks clientDataJSON.origin                      "https://examp1e-login.test" not in allowed origins -> reject
     Compare TOTP: the victim types 123456 into the fake page, the proxy forwards it within 30 s, attacker is in.

Real scenario: a consumer site offering "Sign in with a passkey" and seeing fewer support tickets than with passwords plus SMS; an enterprise requiring device-bound passkeys on YubiKeys for production access (AAL3) and checking attestation against the FIDO Metadata Service; a user who loses their phone but keeps their synced passkeys on a new phone through iCloud Keychain; an RP that registered credentials on app.example.com and later wanted them on example.com (choose the RP ID up front: the registrable domain is the flexible choice).

What provides it:

Product / libraryNotes
Go github.com/go-webauthn/webauthn (v0.15.0 here; v0.18.2 needs Go 1.26)webauthn.New(&Config{RPID, RPDisplayName, RPOrigins}); BeginRegistration/FinishRegistration, BeginDiscoverableLogin/FinishPasskeyLogin; Credential.Authenticator.CloneWarning; Flags.BackupEligible/BackupState
Laravel FortifyFeatures::passkeys(['confirmPassword' => true]); wraps laravel/passkeys; config relying_party_id, allowed_origins, user_handle_secret, timeout 60000; routes /passkeys/login/options, /passkeys/login; npm @laravel/passkeys
Passkey providersiCloud Keychain, Google Password Manager, Windows Hello, 1Password, Dashlane, Bitwarden
Identity providersKeycloak (WebAuthn and passwordless policies), Auth0, Okta, Amazon Cognito (passkeys as a passwordless first factor), Ory Kratos
Attestation conveyancenone (default, most consumer sites), indirect, direct, enterprise; verify with the FIDO MDS when you need models

Fix / how to use it: require residentKey: required and userVerification: required for passwordless passkeys; use attestation: none unless policy needs device models; store credential ID, public key, sign count, transports, BE/BS, AAGUID, created/last-used times and a user-chosen name; allow several passkeys per account; send excludeCredentials at registration; keep the challenge server-side and single-use; require a recent step-up before adding or removing a passkey. Code: passkey.go.

Recovery codes and account recovery Important ​

In plain words: every second factor will be lost by somebody. Recovery is the back door you build on purpose, and attackers will try it first, so it has to be as strong as the front door.

Common misunderstanding: "If they lose their phone, support can disable MFA after they answer a few questions." Then your real MFA is "knows the user's birthday and can sound convincing on the phone". NIST forbids knowledge-based authentication for this purpose.

Definition: NIST SP 800-63B-4 section 4.2 (account recovery): saved recovery codes "SHALL include at least 64 bits from an approved random bit generator", are stored "in hashed form", "SHALL be subject to the throttling requirements", and after use "the CSP SHALL invalidate that recovery code and SHALL issue a new saved recovery code"; any recovery or new code "SHALL result in an account recovery notification". Other recovery methods: issued recovery codes sent to a verified address, recovery contacts, repeated identity proofing. OWASP Forgot Password: after recovery "invalidate existing sessions and outstanding password reset and recovery links or codes".

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

Real scenario: a social network account takeover through a support agent who reset MFA on request; Fortify users regenerating recovery codes via POST /user/two-factor-recovery-codes; a company with a 7-day waiting period plus email notification for MFA removal without a recovery code; ten codes of 10 random characters printed and stored in a drawer.

Fix / how to use it: 8 to 10 codes of at least 64 bits each, shown once, stored hashed, burned on use; "download / print" and "I saved them" confirmation at enrolment; notifications for every use; a slow, audited, out-of-band path for "lost everything" (identity proofing, waiting period); never let SMS alone reset both the password and the second factor.

Server-side sessions and cookies Must-know ​

In plain words: after login, the server stores "session x7Kp... belongs to account 42, logged in at 09:00 with password + TOTP" and gives the browser only the random x7Kp... in a cookie. Each request brings the cookie back; the server looks it up.

Common misunderstanding: "Sessions do not scale." A Redis lookup is sub-millisecond and Redis handles hundreds of thousands of such lookups per second; the real scaling question is sticky sessions on in-memory stores, which a shared store removes. See Web Sessions, Cookies, Serialization & CORS for cookie attributes and CSRF.

Definition: NIST SP 800-63B-4 session rules: the session secret is generated "in direct response to an authentication event"; cookies "SHALL be tagged to be accessible only on secure (i.e., HTTPS) sessions", "SHOULD be tagged as inaccessible via JavaScript (i.e., HttpOnly)", "SHOULD have the "__Host-" prefix and set "Path=/"", "SHOULD set "SameSite=Lax" or "SameSite=Strict"", and "SHOULD contain only an opaque string". OWASP: session IDs need "at least 64 bits of entropy" (128 bits recommended if you generate them yourself); renew the session ID "after any privilege level change" (login, step-up) to prevent session fixation; enforce an idle timeout and an absolute timeout.

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

Real scenario: a Laravel monolith with the database session driver where "log out everywhere" is DELETE FROM sessions WHERE user_id = 42; a Go service storing sessions in Redis with EXPIRE for the idle timeout; a site that kept sessions in process memory and logged everyone out on every deploy; a cookie without HttpOnly stolen by one XSS.

What provides it:

ProductStorage and knobs
Laravel 13SESSION_DRIVER file, cookie, database (default in new apps), redis, memcached, dynamodb, array; SESSION_LIFETIME minutes; expire_on_close; secure, http_only, same_site; session()->regenerate(), invalidate()
GoNo built-in sessions: alexedwards/scs, gorilla/sessions, or a small store like this chapter's session package
Expressexpress-session with a Redis store
SpringSpring Session (Redis, JDBC)
NGINX / EnvoyDo not manage app sessions; may do sticky routing (avoid when the store is shared)

Fix / how to use it: 128+ bit random ID; store user id, auth_time, amr, created, last seen, IP and user agent (for the "your devices" page); rotate on login and step-up; idle and absolute timeouts enforced on the server, not by cookie expiry; __Host- cookie, Secure, HttpOnly, SameSite=Lax; an index by user id so "log out everywhere" is one query. Code: session.go.

Stateless tokens (JWT), opaque tokens and introspection Must-know ​

In plain words: a JWT is a signed note that says "this is user 42, scopes X, valid until 09:15"; anyone with the public key can check it without asking anyone. An opaque token is a random string that means nothing by itself; the API must ask the authorization server what it means.

Common misunderstanding: "We can revoke JWTs by deleting them from the database." There is nothing to delete: the token is valid until exp wherever it is presented. Revocation needs a deny list (which reintroduces the lookup) or a short lifetime plus refresh tokens.

Definition: a stateless (self-contained) token carries its claims and a signature (JWS); verification is local. An opaque (reference) token is a handle to server-side state. RFC 7662 token introspection lets a resource server POST the token to the authorization server and receive JSON with a "REQUIRED" boolean active plus scope, client_id, sub, exp. Many systems use a hybrid: opaque or session at the edge, short JWTs between internal services ("phantom token" pattern: the gateway introspects and forwards a JWT). The JWT format, algorithms and validation pitfalls are owned by JWT Deep Dive.

Server-side sessionStateless JWTOpaque token + introspectionBrowserAppRedis / tableClientServicedeny list?ClientAPIAuth servercookie: opaque ID onlyHttpOnly, Secure, SameSitelookup on every requestrevoke: delete row, instantbest for browserssigned claims, verify locallyno lookup, scales freelyrevoke: wait for expkeep exp at 5 to 15 minbest between servicesrandom string, RFC 7662active: true / falsecache the answer brieflyrevoke: instant (or TTL)best for third-party APIsHybrid: session or opaque token at the edge (BFF, gateway), short JWT inside, rotating refresh tokens for mobile apps.
text
     User 42 is fired at 10:00; admin revokes access
1    session cookie      10:00:01 next request: row deleted -> 401                         (instant)
2    JWT exp 15 min      10:00:01 .. 10:14:59 every service still accepts the token          (up to 15 min)
3    JWT exp 24 h        valid until tomorrow 09:00 unless every service checks a deny list  (do not do this)
4    opaque + introspect 10:00:01 introspection returns {"active": false}; with a 30 s cache: up to 30 s

Real scenario: a microservice mesh where the gateway validates the user's session and mints a 5-minute JWT for downstream services; a public API with opaque tokens because partners must be cut off instantly; a mobile app holding a 15-minute JWT access token and a rotating refresh token; Laravel Sanctum SPA authentication that uses no tokens at all, just the session cookie ("Sanctum does not use tokens of any kind").

What provides it:

ProductToken style
Laravel SanctumOpaque personal access tokens, stored as SHA-256, abilities, optional expiration; SPA mode uses session cookies
Laravel PassportFull OAuth 2.0 server: JWT access tokens and refresh tokens
Keycloak, Auth0, Okta, CognitoJWT access and ID tokens; introspection endpoints (Keycloak, Okta); refresh tokens
Ory HydraOpaque or JWT access tokens, RFC 7662 introspection
Envoy / Kong / AWS API GatewayJWT authentication filters/authorizers; Envoy ext_authz for introspection

Fix / how to use it: browsers on your own domain: server-side session. Third parties and partners: opaque tokens with introspection (cache seconds, not minutes). Internal services: short JWTs (5 to 15 minutes), audience-restricted. Never put a long-lived JWT in localStorage.

Refresh tokens: rotation, reuse detection, DPoP and token binding Must-know ​

In plain words: keep the access token short-lived and give the client a second, longer-lived token that can only be used to get new access tokens. Every time it is used, swap it for a new one; if an old one ever comes back, someone copied it, so cancel the whole chain.

Common misunderstanding: "Rotation means a stolen refresh token is harmless." Rotation detects theft only when both parties use the token; if the thief uses it first and the real client never refreshes again, the thief has a session until the family's absolute lifetime ends. That is why the family needs an absolute expiry, and why sender-constraining (DPoP, mTLS) is the stronger alternative.

Definition: RFC 6749: "Refresh tokens MUST be kept confidential in transit and storage". RFC 9700 section 4.14.2: rotation means "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"; on reuse "The authorization server cannot determine which party submitted the invalid refresh token, but it will revoke the active refresh token." The family (grant) is the chain from one login. DPoP (RFC 9449) binds tokens to a client-held key: each request carries a DPoP header with a signed proof JWT (htm, htu, iat, jti, and ath for access tokens); the token carries the key thumbprint (cnf.jkt). Token Binding (RFC 8471, 2018) bound tokens to the TLS layer; it did not reach broad browser support, and RFC 9700 names mTLS (RFC 8705) and DPoP as the two methods "in use in practice".

ClientAuth serverAttackerRotation turns a stolen refresh token into an alarmloginissue RT1 (family F)refresh with RT1RT1 used, issue RT2RT1 presented againreuse: revoke Frefresh with RT2invalid_grantRT1 copied (XSS, log,backup, malware)thief replays RT1gets nothingRT2user signs in again(cost of the alarm)Store only SHA-256 of each token; lock the row while rotating; give the family an absolute lifetime.
text
     Family F, idle TTL 14 days, absolute TTL 30 days
1    day 0    login                       RT1 issued (F)
2    day 10   client refresh with RT1     RT1 used; RT2 issued
3    day 11   attacker replays RT1        RT1 already used -> revoke F, log refresh_token.reuse_detected
4    day 12   client refresh with RT2     invalid_grant -> user signs in again
5    day 30   any token of F              absolute lifetime over: invalid_grant even if never stolen

Real scenario: a mobile banking app storing the refresh token in the Keychain/Keystore; an SPA where refresh tokens must rotate because the browser is a public client; two browser tabs refreshing at the same time and tripping reuse detection (the fix: a short reuse interval or a single refresh in flight); a logout endpoint that revokes the family, not just the current token.

What provides it:

ProductBehaviour
Auth0Refresh token rotation with "Automatic reuse detection": on reuse Auth0 "immediately invalidates the refresh token family"
KeycloakRealm setting "Revoke Refresh Token": "When Enabled, Keycloak revokes refresh tokens and issues another token that the client must use"
Amazon CognitoOptional refresh token rotation per app client; with it enabled, REFRESH_TOKEN_AUTH in InitiateAuth is not allowed, use GetTokensFromRefreshToken or the token endpoint
Laravel PassportOAuth 2.0 refresh_token grant; revoke with the Laravel\Passport\RefreshToken model's revoke method
This chapterGo refresh package and Laravel RefreshTokens service: SHA-256 storage, family, absolute lifetime, reuse detection

Fix / how to use it: opaque refresh tokens stored as SHA-256; rotation with family revocation on reuse; idle and absolute lifetimes; row lock during rotation; a small reuse interval only if real clients race; DPoP or mTLS for high-value clients; revoke families on logout, password change and recovery. Code: refresh.go, RefreshTokens.php.

Password reset flow Must-know ​

In plain words: "forgot password" is a login method: whoever controls the reset link controls the account. So the link must be unguessable, short-lived, single-use, stored hashed, and using it must end every old session.

Common misunderstanding: "We email a link with the user id and a timestamp." Anything predictable can be forged; anything stored in plaintext can be stolen from the database; anything that survives after use can be replayed from mail logs.

Definition: OWASP Forgot Password Cheat Sheet: "Return a consistent message for both existent and non-existent accounts"; tokens "Single use and expire after an appropriate period"; generate them with a CSPRNG and store them securely; do not build the URL from the Host header ("Host Header Injection"); set Referrer-Policy on the reset page; after a reset, "Ask the user if they want to invalidate all of their existing sessions, or invalidate the sessions automatically"; do not log the user in automatically. NIST treats a changed password as an event that requires a notification.

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

Real scenario: a reset link leaking through the Referer header to an analytics script on the reset page; an attacker who triggered resets with a poisoned Host header so links pointed to their server; a password changed by an attacker who kept their old session alive for weeks because the reset did not revoke sessions; a reset endpoint without a rate limit used to mail-bomb a victim.

What provides it:

ProductBehaviour
Laravel password brokerPassword::sendResetLink(), Password::reset(); database driver stores a bcrypt hash of a hash_hmac('sha256', Str::random(40), key) token; expire 60 minutes, throttle 60 seconds; cache driver keyed by SHA-256 of the email; auth:clear-resets prunes
Laravel statusesPassword::ResetLinkSent, PasswordReset, InvalidUser, InvalidToken, ResetThrottled (show one message for the first three)
Go (this chapter)reset package: SHA-256, single use, newest-only, fixed base URL
Auth0, Okta, Cognito, KeycloakHosted reset flows with configurable link lifetimes and templates

Fix / how to use it: see the timeline; plus a per-email and per-IP limit, a Referrer-Policy: no-referrer header, and MFA still required after the reset if the account has MFA (a reset proves mailbox control, not the second factor).

Remember me, logout everywhere and step-up authentication Important ​

In plain words: "remember me" keeps the user signed in across browser restarts; "logout everywhere" ends every session and token the user has; step-up asks for a fresh proof before a sensitive action even though the user is already signed in.

Common misunderstanding: "Logout everywhere means deleting the current cookie." The user's phone, the old laptop, the API tokens, the refresh token families and the remember-me cookie are all separate credentials. Each one needs its own revocation.

Definition: Remember me is a long-lived, rotating token in a separate cookie that recreates a session (Laravel: the remember_token column, "authenticated indefinitely or until they manually logout"; NIST: such features "SHALL NOT be used instead of authentication" except for AAL2 reauthentication after the inactivity limit). Logout everywhere invalidates every session and token for the account (Laravel Auth::logoutOtherDevices($password) with the auth.session middleware: it rehashes the password so AuthenticateSession rejects other sessions). Step-up authentication requires auth_time to be recent or amr to include a stronger method (OIDC max_age, acr_values; Laravel password.confirm with auth.password_timeout, default 10800 s = 3 hours).

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

Real scenario: a user whose laptop was stolen clicking "sign out of all devices"; a banking app asking for Face ID before a transfer above a threshold; Laravel's password.confirm middleware on "delete account"; a remember-me token that was never rotated and worked from a copied cookie for a year.

Fix / how to use it: remember-me tokens rotate on use and die on password change; "your devices" page lists sessions with created/last seen/IP/UA and lets the user end each; logout everywhere deletes sessions, rotates remember_token, deletes API tokens and revokes refresh families; step-up on change email/password/MFA, add passkey, show recovery codes, payouts and admin actions. Code: session.go, SecurityController.php.

SSO, OAuth and service-to-service authentication Good to know ​

In plain words: with SSO the user authenticates once at an identity provider and your app receives a signed statement about it; machines authenticate with keys or certificates, not passwords.

Common misunderstanding: "OAuth is an authentication protocol." OAuth 2.0 is delegated authorization; OpenID Connect adds the ID token that carries authentication (sub, auth_time, amr, acr). The details belong to OAuth 2.0, OpenID Connect & Single Sign-On.

Definition: with OIDC your app becomes a relying party of Keycloak, Auth0, Okta, Entra ID or Cognito: it redirects, receives a code, exchanges it for tokens, validates the ID token and creates its own local session. Machine identities use client credentials, mTLS (Mutual TLS), SPIFFE identities in a mesh, or cloud workload identity; never a shared service password in a config file.

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

Real scenario: a B2B app supporting "Sign in with your company SSO" through SAML/OIDC per tenant; internal services authenticating with mTLS certificates issued by a mesh (Istio); a cron job using a short-lived cloud workload token instead of a static API key.

Fix / how to use it: buy or self-host an IdP once you have several apps or enterprise SSO demands; keep local sessions short and honour IdP logout; give every machine its own identity with rotation.

Auditing authentication events Important ​

In plain words: write down every login, failure, MFA change, password change, reset and token revocation, with who, when, from where and how, but never the secret itself.

Common misunderstanding: "We log the request body for debugging." Then your logs contain passwords, OTPs and reset tokens. Log the event, not the credential.

Definition: an authentication audit event has a type (login.succeeded, login.failed, login.throttled, mfa.enabled, mfa.disabled, recovery_code.used, password.changed, password.reset_requested, session.revoked, refresh_token.reuse_detected, passkey.registered), the account (or a hash of the attempted identifier), time, IP, user agent, amr, result and a correlation id. NIST requires notifications to the subscriber for authenticator binding and recovery events; OWASP Logging Cheat Sheet lists authentication successes and failures as events to record.

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

Real scenario: detecting stuffing by the ratio of failed to successful logins per minute; a SOC rule for "MFA disabled within 10 minutes of a new-device login"; GDPR-friendly logs that store a keyed hash of the email for failures of unknown accounts; immutable storage for compliance (SOC 2, PCI DSS).

Fix / how to use it: an auth_events table or log stream with the fields above; user-facing "recent activity" built from it; alerts on rate and ratio changes; retention by policy. Broader logging belongs to Secure SDLC, Logging & Incident Response.

Mechanics ​

Hash formats you will see ​

Prefix / shapeSchemeExample (truncated)Parse it as
$argon2id$v=19$m=65536,t=4,p=1$salt$hashArgon2id, PHC string format$argon2id$v=19$m=65536,t=4,p=1$S7Xu...$ylCv... (PHP 8.5 default, measured)version 19 (0x13), memory KiB, passes, lanes, Base64 without padding
$2y$12$ + 53 charactersbcrypt (PHP), cost 12$2y$12$SmVw2j1rEScoC.5CDpEMiu...22-character salt + 31-character hash, bcrypt's own Base64 alphabet
$2a$ / $2b$bcrypt (Go, OpenBSD, Node)$2a$10$...Same; Go accepts $2a$/$2b$; this chapter's code maps $2y$ to $2a$
$scrypt$ln=17,r=8,p=1$...scrypt (PHC style, passlib)ln = log2(N)
pbkdf2_sha256$600000$salt$hashDjango PBKDF2iterations in the string
{bcrypt}$2a$...Spring DelegatingPasswordEncoderid in braces selects the encoder
32 or 40 hex characters, no saltMD5 / SHA-1Legacy: wrap now, migrate at login

What we measured on PHP 8.5.0 (this machine): password_hash(str_repeat("a", 80), PASSWORD_BCRYPT) succeeds, and password_verify with the first 72 characters plus anything else returns true, so bytes 73 and later are ignored. Laravel's BcryptHasher refuses longer input only when bcrypt.limit is set ("Value is too long to hash. Value must be less than 72 bytes."); Go's bcrypt.GenerateFromPassword always returns ErrPasswordTooLong.

Measured costs and capacity ​

One run of this chapter's lab program on an Apple M4 Pro, Go 1.27, one hash at a time (numbers vary by about 30% between runs; measure on your own instance type):

SettingTime per hashHashes per second (one caller)Memory per hash
Argon2id m=19 MiB t=2 p=1 (OWASP)16 ms6219 MiB
Argon2id m=46 MiB t=1 p=1 (OWASP)21 ms4746 MiB
Argon2id m=64 MiB t=4 p=1 (PHP and Laravel default)131 ms864 MiB
Argon2id m=64 MiB t=3 p=4 (RFC 9106 second option, four goroutines)27 ms3764 MiB
bcrypt cost 1048 ms214 KiB
bcrypt cost 12 (Laravel default)193 ms54 KiB
bcrypt cost 14761 ms14 KiB

Capacity, back of the envelope (labelled estimate). Peak login rate 200/s, Argon2id 19 MiB t=2 at about 20 ms of one core each: 200 x 0.02 = 4 cores busy hashing, and at most about 200 x 0.02 = 4 hashes in flight on average, so roughly 4 x 19 MiB = 76 MiB of hashing memory (plan 10x headroom for bursts: 40 cores' worth of burst capacity or a queue). The same rate on bcrypt cost 12 needs 200 x 0.19 = 38 cores. A credential-stuffing burst of 5,000 attempts per second that reaches the hasher needs 100 cores with Argon2id: this is why throttling must run before the hash.

The attacker's side (estimate). An offline attacker with your dump pays the same cost per guess per hash. At 62 Argon2id guesses per second per core, testing the 10,000 most common passwords against one account takes about 160 core-seconds; against 1 million accounts, about 5 core-years. With a pepper they cannot start.

TOTP arithmetic ​

QuantityValueSource
Time step X30 s recommendedRFC 6238
T00 (Unix epoch)RFC 6238
Counterfloor(unix_time / 30), 8 bytes big-endianRFC 6238 / RFC 4226
HMACSHA-1 (apps), SHA-256, SHA-512 allowedRFC 6238
Truncationoffset = low 4 bits of last byte; 31-bit integer; mod 10^digitsRFC 4226 section 5.3
Secret length160 bits recommended (20 bytes, 32 Base32 characters)RFC 4226
Drift"at most one time step" for network delay; record per-user driftRFC 6238 sections 5.2 and 6
Window with skew 13 codes valid at once; a code is usable for up to 90 sArithmetic
Guessing a 6-digit code3 valid codes / 1,000,000 per attempt with skew 1Arithmetic
Online guesses allowedat most 100 consecutive failures per authenticatorNIST SP 800-63B-4
Test vectorsecret "12345678901234567890", t = 59 s, SHA-1, 8 digits = 94287082RFC 6238 Appendix B

WebAuthn data you store ​

FieldFromWhy
Credential IDRegistrationLook up the key; send in allowCredentials/excludeCredentials
Public key (COSE)RegistrationVerify every assertion signature
User handleYour random 64-byte idReturned by discoverable credentials; must not be the email
Sign countEvery assertionClone detection; synced passkeys often report 0
Flags UP, UV, BE, BSauthenticatorDataUV = two factors in one; BE/BS = synced or not
AAGUID, attestation formatRegistrationAuthenticator model (with attestation); policy for AAL3
TransportsRegistrationHints (internal, usb, hybrid, nfc, ble)
Name, created, last usedYour UI"MacBook passkey, last used yesterday"

DOMExceptions the browser raises: NotAllowedError (user cancelled, timed out, or no credential), InvalidStateError (an authenticator in excludeCredentials is already registered), SecurityError (RP ID not a valid domain for the origin).

Knobs per product ​

ProductKnobDefault (from docs or source)
Laravel config/hashing.phpdriver, bcrypt.rounds, bcrypt.limit, argon.memory/time/threads, rehash_on_login, verifybcrypt, 12, null, 65536/4/1, true, true
Laravel config/auth.phppasswords.users.expire, .throttle, password_timeout60 min, 60 s, 10800 s
Laravel SessionGuardTimebox duration for attempt/validate200,000 µs
Laravel Fortify stublimiters.login, limiters.two-factor, limiters.passkeys, lowercase_usernames, twoFactorAuthentication(['confirm', 'confirmPassword', 'window'])5/min email+IP, 5/min login.id, 10/min credential/session+IP, true, confirm on
Laravel Sanctumexpiration (minutes), sanctum:prune-expirednull (never expire)
Go x/crypto/bcryptcostDefaultCost 10
Go pquerna/otp/totpPeriod, Skew, Digits, Algorithm, SecretSize30, 0, 6, SHA1, 20 bytes
Go go-webauthnRPID, RPOrigins, AttestationPreference, AuthenticatorSelection, Timeoutsnone; you must set RPID and origins
Keycloak Brute Force Detection (permanent lockout)Max Login Failures, Quick Login Check Milliseconds, Minimum Quick Login Wait30, 1000 ms, 1 minute
NIST SP 800-63B-4AAL2 reauthentication overall / inactivitySHOULD be no more than 24 h / 1 h
NIST SP 800-63B-4AAL3 reauthentication overall / inactivityno more than 12 h / SHOULD 15 min
OWASP Session Managementsession ID entropyat least 64 bits

Error messages and status codes you will actually see ​

WhereMessage or codeMeaning
Laravel auth.failed"These credentials do not match our records."Login failed (uniform)
Laravel auth.throttle"Too many login attempts. Please try again in :seconds seconds."Login limiter hit (HTTP 429 via ThrottleRequests, or validation error in the starter kits)
Laravel auth.password"The provided password is incorrect."current_password rule failed
Laravel passwords.sent / .user / .throttled / .token / .reset"We have emailed your password reset link." / "We can't find a user with that email address." / "Please wait before retrying." / "This password reset token is invalid." / "Your password has been reset."Broker statuses; .user and .throttled leak existence if shown
Laravel BcryptHasher"This password does not use the Bcrypt algorithm." (RuntimeException)HASH_VERIFY=true and a hash from another driver; set HASH_VERIFY=false while migrating
Laravel logoutOtherDevices"The given password does not match the current password." (InvalidArgumentException)Wrong confirmation password
Fortify XHR422 with validation errors; 204 after a successful two-factor challenge; two_factor: true in the login JSONTwo-factor flow for SPAs
Go x/crypto/bcryptbcrypt: password length exceeds 72 bytes, crypto/bcrypt: hashedPassword is not the hash of the given passwordErrPasswordTooLong, ErrMismatchedHashAndPassword
OAuth 2.0 token endpoint400 {"error":"invalid_grant"}Refresh token expired, revoked, reused or unknown
OAuth / DPoP401 with WWW-Authenticate: DPoP error="use_dpop_nonce"Server wants a fresh nonce in the DPoP proof
HTTP401 (who are you?), 403 (not allowed), 429 + Retry-After (slow down)Do not use 404 for "no such user"

Schema ​

The tables a login system needs, in PostgreSQL syntax (the Laravel migration in Laravel creates the same ones):

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

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

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

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

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

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

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

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

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

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

Why SHA-256 is enough for reset tokens, session IDs and refresh tokens but not for passwords: those secrets carry 128 to 256 bits of randomness, so there is nothing to guess; NIST only requires the slow, salted hash for low-entropy secrets ("shorter than ... 112 bits"). Laravel's reset broker uses bcrypt anyway, which is harmless.

Go ​

The Go module (academy/authentication-passwords-mfa-sessions) has one package per idea and a fake clock so every timer is tested without sleeping. Dependencies: golang.org/x/crypto v0.43.0 (argon2, bcrypt), golang.org/x/text v0.30.0 (NFC), github.com/pquerna/otp v1.5.0 (cross-check in tests), github.com/go-webauthn/webauthn v0.15.0. The go directive is 1.24.0 because go-webauthn v0.15.0 declares it; v0.18.2 (the newest on pkg.go.dev) requires Go 1.26.

Before ​

A login handler that works and is wrong six ways: unsalted SHA-256, enumeration by message, status and timing, != comparison, no throttling, identity in the cookie, no cookie flags:

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

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

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

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

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

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

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

After ​

The fake clock used by every package:

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

import (
	"sync"
	"time"
)

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

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

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

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

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

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

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

Argon2id PHC strings, NFC normalisation, optional pepper, legacy bcrypt verification and needsRehash, with tests for salts, parameter upgrades, $2y$ hashes, the 72-byte limit and Unicode:

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

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

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

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

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

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

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

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

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

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

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

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

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

import (
	"strings"
	"testing"

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

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

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

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

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

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

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

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

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

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

Login with uniform errors, a dummy hash for unknown users, progressive delay per account, a per-IP window and rehash on login. The tests prove that unknown and wrong-password failures are identical, that throttled attempts never reach the hasher, and that spraying from one IP is stopped:

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

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

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

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

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

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

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

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

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

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

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

type accountState struct {
	failures  int
	notBefore time.Time
}

type ipState struct {
	failures    int
	windowStart time.Time
}

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

type fakeHasher struct{ verifies int }

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

type memStore struct{ users map[string]User }

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

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

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

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

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

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

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

TOTP and HOTP from the standard library, with all RFC 4226 and RFC 6238 test vectors, drift and replay tests, and a cross-check against pquerna/otp:

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

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

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

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

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

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

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

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

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

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

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

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

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

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

import (
	"testing"
	"time"

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

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

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

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

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

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

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

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

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

Passkeys with go-webauthn: relying-party configuration, registration and discoverable login handlers, single-use ceremonies, clone warning. The test checks the generated creation options; a full ceremony needs a real or virtual authenticator, so the finish handlers are compile-checked only:

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

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

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

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

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

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

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

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

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

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

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

const cookieName = "__Host-webauthn"

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

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

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

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

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

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

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

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

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

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

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

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

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

Refresh tokens with rotation, families, idle and absolute lifetimes, and reuse detection:

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

import (
	"testing"
	"time"

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

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

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

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

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

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

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

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

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

Password reset tokens: 256 bits, SHA-256 at rest, single use, newest-only, one public message:

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

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

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

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

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

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

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

type entry struct {
	userID  int64
	expires time.Time
}

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

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

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

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

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

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

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

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

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

type users map[string]int64

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

type mailer struct{ links []string }

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

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

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

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

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

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

Server-side sessions: idle and absolute timeouts, ID rotation on step-up, freshness checks, logout other devices, __Host- cookie:

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

import (
	"testing"
	"time"

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

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

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

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

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

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

The Go angle ​

Go featureUse in authenticationNote
golang.org/x/crypto/argon2IDKey(pw, salt, t, m, p, keyLen)Returns raw bytes; you write the PHC encoding and parsing
golang.org/x/crypto/bcryptGenerateFromPassword, CompareHashAndPassword, CostRefuses more than 72 bytes with ErrPasswordTooLong
golang.org/x/crypto/scrypt, pbkdf2scrypt.Key, pbkdf2.Key (Go 1.24 also has crypto/pbkdf2)PBKDF2 for FIPS builds (GOFIPS140)
crypto/subtle.ConstantTimeCompareEvery secret comparisonEqual-length inputs; compare hashes, not raw strings of different length
crypto/randSalts, session IDs, tokens, TOTP secretsrand.Read never fails on supported platforms since Go 1.24; still check the error
crypto/hmac, crypto/sha256Pepper, HOTP, token hasheshmac.Equal for MACs
golang.org/x/text/unicode/normNFC before hashingNIST SP 800-63B-4
github.com/pquerna/otpTOTP/HOTP, otpauth:// keys, QR images (Key.Image)Add your own replay store
github.com/go-webauthn/webauthnWebAuthn RP: ceremonies, attestation formats, MDSPin a version that matches your Go toolchain
net/http CookieSecure, HttpOnly, SameSite, __Host-http.SameSiteLaxMode
Session librariesalexedwards/scs (Redis, Postgres stores), gorilla/sessionsOr a small store as above
No frameworkGo has no Fortify: you assemble the piecesAuthentication in Go builds a full service

Laravel ​

Before ​

MD5, enumeration, no throttling, no session regeneration:

php
<?php

namespace App\Http\Controllers\Auth;

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

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

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

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

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

        return redirect('/dashboard');
    }
}

After ​

Hashing configuration: Argon2id, explicit bcrypt limit for legacy hashes, rehash on login:

php
<?php

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

return [

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

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

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

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

];

Password defaults and named rate limiters (account+IP, account, IP; two-factor; reset):

php
<?php

namespace App\Providers;

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

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

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

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

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

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

A manual login controller: Auth::validate() inside Laravel's 200 ms timebox, one message, rehash, MFA handoff, session regeneration, audit log:

php
<?php

namespace App\Http\Controllers\Auth;

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

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

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

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

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

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

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

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

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

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

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

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

        return redirect('/');
    }
}

The two-factor challenge with row lock, TOTP replay guard and burned, hashed recovery codes:

php
<?php

namespace App\Http\Controllers\Auth;

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

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

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

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

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

                return true;
            }

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

            return true;
        });

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

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

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

A raw RFC 6238 implementation in PHP and a script that checks it against the RFC test vectors (we ran it: all TOTP/HOTP vectors pass):

php
<?php

namespace App\Support;

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

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

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

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

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

        return $matched;
    }

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

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

        return $out;
    }

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

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

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

use App\Support\Totp;

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

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

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

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

Password reset with the Password broker, one public message, and "log out everywhere" after the reset:

php
<?php

namespace App\Http\Controllers\Auth;

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

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

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

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

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

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

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

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

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

Logout other devices and step-up (Auth::logoutOtherDevices, auth.session, password.confirm):

php
<?php

namespace App\Http\Controllers\Settings;

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

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

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

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

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

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

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

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

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

Sanctum personal access tokens with abilities and expiry:

php
<?php

namespace App\Http\Controllers\Api;

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

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

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

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

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

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

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

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

Refresh token rotation with reuse detection for a mobile client of a Laravel API:

php
<?php

namespace App\Services;

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

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

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

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

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

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

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

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

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

                throw new RuntimeException('invalid_grant');
            }

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

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

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

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

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

        return $plain;
    }
}

Migration and routes:

php
<?php

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

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

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

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

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

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

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

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

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

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

The same policy with Fortify (headless backend for any frontend):

php
<?php

namespace App\Providers;

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

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

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

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

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

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

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

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

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

The Laravel angle ​

Laravel 13 featureWhat it does for authenticationWatch out
Hash::make, Hash::check, Hash::needsRehashbcrypt (default), argon, argon2id driversHASH_VERIFY throws when the stored hash uses another algorithm; disable during migration
rehash_on_loginAuth::attempt() upgrades hashesAuth::validate() and custom checks do not: call needsRehash yourself
Auth::attempt, Auth::validate, Auth::loginSession login; 200 ms timebox on failuresCall $request->session()->regenerate() after login
RateLimiter::for, Limit::perMinute()->by(), throttle: middlewareNamed limiters; arrays of limitsKey by normalised email and IP
Password::defaults(), Password::min()->uncompromised()Length and HIBP k-anonymity checkSkip mixedCase()/symbols() per NIST
Password brokerReset links, expire, throttle, database or cache driverShow one message for every status
Auth::logoutOtherDevices() + auth.sessionInvalidates other sessions by rehashingAlso delete database sessions and API tokens
password.confirm middleware, password_timeoutStep-up for sensitive routesDefault 3 hours is long; set 10 to 15 minutes
"Remember me" (Auth::attempt($creds, $remember), remember_token)Long-lived re-login cookieRotate remember_token on reset
FortifyHeadless login, registration, reset, email verification, TOTP 2FA, recovery codes, passkeysYou build the views (or use a starter kit)
Starter kits (React, Vue, Svelte, Livewire)Fortify-based screens out of the boxLaravel's default is bcrypt in the kits
SanctumSPA session auth + personal access tokens (SHA-256, abilities, expiration)Tokens never expire unless configured
PassportFull OAuth 2.0 server (authorization code + PKCE, client credentials, refresh tokens)Only when third parties need OAuth
SocialiteLogin with Google, GitHub, Apple and othersYou still create a local session

Solving the classic problems ​

Passwords stored with a fast hash ​

SolutionHowAdvantageCost / limitation
Wrap nowargon2id(old_md5) for every row in one migrationEvery row protected todayVerify must know it is wrapped
Rehash on loginVerify old scheme, store Argon2idNo user impactInactive users stay weak
Force reset for the restAfter N months, expire unconverted hashesRemoves the long tailSupport load

Credential stuffing wave ​

SolutionHowAdvantageCost
Breached-password check at loginHIBP range API or offline list; force reset on matchKills the attack's inputOne HTTP call (cache, or mirror the list)
Bot defence at the edgeCloudflare Bot Management/Turnstile, AWS WAF ATPStops traffic before the hasherVendor cost, false positives
MFATOTP or passkeysPassword alone is uselessAdoption, support
Global alarmAlert on login success ratio dropDetects new waves fastTuning

Users locked out by attackers ​

SolutionHowAdvantageCost
Progressive delay1 s, 2 s, 4 s ... cap 15 minReal user waits secondsAttack slowed, not stopped
CAPTCHA after N failuresTurnstile/hCaptchaBots pay, humans clickSolvers exist
Known-device bypassDevice cookie from a past MFA login skips the delayOwner unaffectedDevice cookie theft
Reset re-enablesHard limit disables the password, reset clears itAttacker cannot keep you outMailbox becomes the key

Enumeration through reset and sign-up ​

SolutionHowAdvantageCost
One message"If an account exists..."No oracleSlightly worse UX
Queued mailDispatch the broker call to a jobEqual timingAsync infrastructure
Sign-up by email link"Check your inbox"; mail existing owners a noticeRegistration no longer leaksExtra step

TOTP code replayed ​

SolutionHowAdvantageCost
Last accepted stepStore and require step > last_step in the login transactionExactly what RFC 6238 requiresOne column
Cache used codesFortify caches used timestamps per codeNo schema changeCache must be shared by all instances

Phished OTPs and push fatigue ​

SolutionHowAdvantageCost
PasskeysWebAuthn with UVOrigin-bound; nothing to relayRecovery design
Number matchingPush shows a number from the login pageBlind approvals impossiblePush provider support
Push capsN prompts per 10 minutesEnds bombingEdge cases

Lost second factor ​

Recovery codes (hashed, single-use, regenerated), at least two enrolled factors, synced passkeys, and a slow audited human process with notification and waiting period. Never let support "just turn MFA off".

Logout does not log out ​

Delete the server session, rotate remember_token, delete API tokens, revoke refresh families; for JWTs, keep access tokens at 5 to 15 minutes and check a revocation list for high-risk actions.

Stolen refresh token ​

Rotation with family revocation, absolute lifetime, storage in the OS keystore on mobile, an HttpOnly cookie or a BFF for browsers, and DPoP or mTLS binding for high-value clients.

Reset link hijacked ​

Fixed base URL (never the Host header), Referrer-Policy: no-referrer, 256-bit token stored hashed, 15 to 60 minute lifetime, single use, newest-only, sessions revoked after use, MFA still required.

Hashing melts the login servers ​

Throttle before hashing, size Argon2id memory against peak concurrency, run hashing in a bounded worker pool (Go: a semaphore channel), scale the login service separately, and avoid a cost that pushes a login above about 100 ms.

Choosing ​

Which password hash ​

SituationChooseParametersReason
New system, Go or PHPArgon2id19 MiB t=2 p=1 or more, measuredOWASP first choice, memory-hard
Memory-constrained podsArgon2id with lower memory, higher t (12 MiB t=3, 9 MiB t=4)OWASP equivalent rowsSame defence, less RAM
FIPS 140 requiredPBKDF2-HMAC-SHA256600,000 iterationsApproved and validated
Existing bcryptKeep, raise cost, migrate at logincost 12Safe if inputs are limited to 72 bytes
Need offline-dump resistance beyond the hashAdd a pepper in KMS/HSMHMAC-SHA-256Dump alone is useless

Which second factor ​

UsersFirst choiceFallbackAvoid
ConsumersPasskeys (synced)TOTP, email OTP for low-risk appsSMS as the only option
EmployeesPasskeys or Okta FastPass / platform authenticatorTOTP, push with number matchingPlain approve/deny push
Admins, production accessDevice-bound security keys (AAL3)Second security keyAnything phishable
Regulated (banking)Passkeys + device binding, step-up per transactionTOTPSMS without SIM-swap checks

Sessions or tokens ​

ClientCarrierLifetimesReason
Server-rendered web appServer-side session cookieidle 1 h, absolute 24 h (AAL2)Instant revocation, no token in JS
SPA on the same siteSession cookie via Sanctum SPA mode or a BFFsameTokens stay out of JavaScript
Mobile appShort access token + rotating refresh token5 to 15 min / 14 days idle, 30 to 90 days absoluteSurvives restarts, revocable
Third-party API clientOpaque token + introspection, or OAuth client credentialsPer contractInstant cut-off
Internal service-to-servicemTLS identity + short JWT5 minNo shared secrets

Build or buy ​

SituationRecommendationProducts
One app, small team, LaravelBuilt-in: Fortify or a starter kit, SanctumLaravel
One Go serviceLibraries + this chapter's patternsx/crypto, go-webauthn, pquerna/otp, scs
Several apps, SSO, enterprise customersAn identity providerKeycloak (self-hosted), Ory (open source / cloud), Auth0/Okta, Amazon Cognito, Microsoft Entra ID
Strict data residency, full controlSelf-hosted IdPKeycloak, Ory Kratos + Hydra

In architecture: from a single process to a distributed system ​

Monolith: one process, one database ​

A Laravel monolith with Fortify, the database session driver and Argon2id is a complete, correct design: login throttling in the cache, sessions in a table (logout everywhere is one DELETE), TOTP secrets encrypted with APP_KEY-derived encryption, audit events in a table. The traps are local: a cache store that is per-process (the array or file driver on several servers breaks the limiter), and an APP_KEY that encrypts the TOTP secrets and lives next to the database.

Modular monolith: boundaries without the network ​

Make "Identity" a module that owns users, credentials, sessions and audit events, with a small interface: authenticate(credentials) -> AuthResult{user_id, amr, auth_time}, revokeAll(user_id), requireFresh(maxAge). Other modules (Billing, Orders) never read users.password_hash or sessions directly. That boundary is what later lets you replace the module with an IdP without touching the rest.

Microservices: every arrow is a decision ​

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

Authentication is centralised (one identity service or an IdP), verification is distributed (each service verifies a short JWT locally with a cached JWKS), and revocation flows as events or as short lifetimes. Service identity is mTLS or workload identity, see Mutual TLS and API Gateway, BFF & Service Mesh.

Distributed data: replicas, caches, regions ​

  • Read replicas. A session revoked on the primary may still be read from a lagging replica: read sessions and token revocations from the primary or from Redis, never from an async replica.
  • Caches. Introspection results and JWKS are cached; the cache TTL is your revocation delay. Keep it at seconds for introspection.
  • Rate-limit state. Counters must be shared (Redis), or attackers multiply your limit by the number of instances (Rate Limiting).
  • Multi-region. Sessions in a global store (DynamoDB global tables, Redis active-active with CRDTs) or region-pinned users; a password change in one region must revoke sessions in the others, so publish revocations as events. WebAuthn RP ID is one domain across regions.
  • Clocks. TOTP and JWT exp depend on synced clocks (NTP); allow a small leeway for exp/nbf (seconds), not minutes.

Scaling path: 1x, 10x, 100x ​

ScaleLogins per secondDesign
1x1 to 10Monolith, sessions table, Argon2id 19 to 64 MiB, cache-based throttling
10x100Sessions in Redis, login pods sized for hash memory, WAF bot rules on /login, breached-password mirror
100x1,000+ and stuffing burstsDedicated identity service or IdP, edge bot management, hashing worker pools, risk engine, event-driven revocation, short JWTs inside

Lab: measure, test, attack your own login ​

Everything here runs in one process; the HTTP experiments are expected, not run.

1. Measure hashing cost on your machine (run; the numbers on this page came from it):

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

import (
	"fmt"
	"time"

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

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

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

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

2. Run the tests (run):

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

3. Timing oracle against a Laravel app (expected, not run). With bcrypt cost 12 (about 190 ms) and the 200 ms timebox, both answers take about 200 ms. Raise BCRYPT_ROUNDS to 14 (about 760 ms) and the wrong-password case becomes about 560 ms slower than the unknown-email case:

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

4. Throttling (expected, not run): six wrong attempts for one email within a minute from one IP.

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

5. TOTP replay (expected, not run): submit the same valid code twice within 30 seconds to /two-factor-challenge; the first returns 204, the second 422.

6. Refresh reuse (expected, not run): call the token endpoint with RT1 (200, returns RT2), again with RT1 (400 invalid_grant, an auth_events row refresh_token.reuse_detected), then with RT2 (400 invalid_grant).

Common misconceptions ​

BeliefReality
Composition rules make passwords strongNIST SP 800-63B-4 forbids them; length and a blocklist work
Passwords should expire every 90 daysForbidden without evidence of compromise
SHA-256 with a salt is good enoughFast hashes fall to GPUs; use Argon2id, scrypt, bcrypt or PBKDF2 with a high count
bcrypt hashes the whole passwordOnly the first 72 bytes; PHP silently truncates, Go refuses
A pepper is a second saltIt is a secret key stored outside the database; rotation needs the plaintext
Locking the account after 5 failures is best practiceIt is a DoS tool; use delays, CAPTCHA and the NIST 100-failure ceiling
The same error message prevents enumerationTiming, status codes and the reset/sign-up flows leak too
SMS 2FA is fine for adminsNIST restricts PSTN; SIM swap and relay attacks are routine
TOTP is phishing-resistantCodes are relayed in real time; only WebAuthn-style origin binding is
Passkeys are stored on the serverOnly public keys are; the private key stays on the device or synced keychain
JWTs are more secure than sessionsThey trade revocation for statelessness
Refresh token rotation makes theft harmlessIt detects theft only when both parties refresh; add absolute lifetimes and DPoP
Logout clears the cookie, doneEvery session, remember-me token, API token and refresh family must be revoked
Password reset should log the user inIt should end other sessions and send them to login (with MFA)

Cheat sheet ​

TopicRemember
Password policy15+ chars (8+ with MFA), allow 64+, Unicode NFC, blocklist, no composition, no rotation, show-password
HashArgon2id m=19 MiB t=2 p=1 minimum; store the PHC string
bcryptcost 12, 72-byte limit, migrate at login
FIPSPBKDF2-HMAC-SHA256 600,000
PepperHMAC with a KMS/HSM key, versioned
RehashOn every successful login path
Uniform failureSame message, status, shape and time; dummy hash
ThrottlingBefore hashing; account + IP + global; progressive delay; 100 max
TOTP160-bit secret, 30 s, skew 1, store last step, rate limit
Phishing resistancePasskeys/WebAuthn or client certs only
Recovery codes64+ bits, hashed, single use, notify
Session128+ bit ID, rotate on login/step-up, idle 1 h, absolute 24 h, __Host-, HttpOnly, Secure, SameSite
TokensAccess 5 to 15 min; refresh rotating with families and absolute lifetime
Reset256-bit, hashed, 15 to 60 min, single use, revoke sessions, fixed base URL
Step-upauth_time freshness for email/password/MFA changes and payments
AuditEvery auth event, never the secret

Self-check: questions & answers ​

Show:
  • Must-know asked in almost every interview
  • Important frequent; expected at senior level
  • Good to know extra depth that sets you apart

1 — Why does NIST SP 800-63B-4 forbid composition rules, and what does it require instead? Important ​

Answer

Answer: Users respond predictably (Password1!), so composition adds little real strength and hurts usability. It requires a minimum length (15 for single-factor, 8 when part of MFA), support for at least 64 characters and Unicode, a blocklist check of the entire password against common and compromised values, and rate limiting.

2 — You must choose Argon2id parameters for login pods with 512 MiB of memory that handle up to 20 concurrent logins. What do you pick? Good to know ​

Answer

Answer: 20 x 19 MiB = 380 MiB fits; 20 x 46 MiB = 920 MiB does not. Pick m=19 MiB t=2 p=1 (or 12 MiB t=3 for headroom), measure the time on the pod type, and cap concurrent hashing with a semaphore so a burst queues instead of running out of memory.

3 — A user's bcrypt password is 80 characters long. What happens in PHP, in Go, and with Laravel's bcrypt.limit set to 72? Good to know ​

Answer

Answer: PHP 8.5 password_hash hashes only the first 72 bytes silently (we verified that a different suffix still verifies). Go's bcrypt.GenerateFromPassword returns ErrPasswordTooLong. Laravel with limit throws "Value is too long to hash". Argon2id has no such limit.

4 — Why does a dummy hash matter even if the error message is uniform? What breaks it in Laravel? Important ​

Answer

Answer: Without hashing for unknown users, they answer in milliseconds and known users in hundreds of milliseconds, which reveals existence. Laravel's attempt/validate hide this with a 200 ms timebox for failures; if the hash itself takes longer than 200 ms (bcrypt cost 14), wrong-password failures become slower again and the oracle returns.

5 — A botnet tries "Winter2026!" once against each of 100,000 accounts from 20,000 IPs. Which control catches it? Important ​

Answer

Answer: Not per-account limits (one try each) and barely per-IP limits (five tries per IP). The blocklist stops users from having that password at all; a global alarm on failure rate and on the same password hash across accounts detects the campaign; bot detection at the edge and MFA make success useless.

6 — Write the rule a TOTP verifier needs to prevent replay, and where the state lives. Important ​

Answer

Answer: Accept a code only if it matches a step in the window and that step is strictly greater than the last accepted step for this user; store the new step in the same transaction as the login (a column such as mfa_totp.last_step). RFC 6238: the verifier "MUST NOT accept the second attempt of the OTP".

7 — Why is a passkey phishing-resistant while TOTP is not? Must-know ​

Answer

Answer: The browser scopes the credential to the RP ID and puts the real origin into clientDataJSON, which the authenticator signs. A look-alike domain has no credential to use, and a proxied challenge is signed with the wrong origin, which the server rejects. A TOTP code is just six digits the user can be tricked into typing anywhere.

8 — What does refresh token reuse detection do when it sees a used token, and why does it punish the legitimate client too? Important ​

Answer

Answer: It revokes the whole family (every token from that login). The server cannot tell whether the client or the thief presented the old token, so ending the grant for both is the only safe answer; the user signs in again.

9 — List everything "log out everywhere" must revoke in a Laravel app with Sanctum and a mobile client. Must-know ​

Answer

Answer: All database or Redis sessions for the user (and logoutOtherDevices for auth.session), the remember_token, Sanctum personal access tokens, refresh token families, and any cached introspection results; then notify the user.

10 — Which actions deserve step-up authentication, and how do you implement it with sessions? Must-know ​

Answer

Answer: Changing email, password or MFA, adding or removing passkeys, viewing recovery codes, payouts, deleting the account and admin actions. Keep auth_time and amr in the session, require now - auth_time below a few minutes (Laravel password.confirm with a shorter password_timeout), re-authenticate, rotate the session ID and record the new auth_time.

Glossary ​

TermMeaning
AAL (Authentication Assurance Level)NIST SP 800-63B levels 1 to 3 of confidence in an authentication
Absolute timeoutMaximum session lifetime regardless of activity
Account enumerationLearning which identifiers have accounts from differing responses
AMRAuthentication Methods References (RFC 8176): pwd, otp, hwk, mfa, sms
Argon2idMemory-hard password hash (RFC 9106), hybrid of Argon2i and Argon2d
AssertionWebAuthn authentication response: a signature over authenticatorData and clientDataJSON
AttestationRegistration-time statement about the authenticator model; conveyance none, indirect, direct, enterprise
AuthenticationProving a request comes from a given identity
AuthenticatorSomething the user controls for authentication: password, OTP device, passkey, security key
AuthorizationDeciding what an authenticated identity may do
Backup eligibility / backup state (BE/BS)WebAuthn flags for multi-device (synced) credentials
bcryptAdaptive password hash with a cost factor and a 72-byte input limit
Breached password checkComparing a password against a corpus of leaked passwords (e.g. HIBP Pwned Passwords)
Brute forceMany guesses against one account
CAPTCHAChallenge that separates humans from bots; Turnstile, hCaptcha, reCAPTCHA
ChallengeRandom value a server asks an authenticator to sign
Composition rulesRequired mixes of character classes; forbidden by NIST
Constant-time compareComparison whose time does not depend on where inputs differ
CookieBrowser-stored value sent back to the origin; carries the session ID
Cost factorTunable work parameter of a password hash (bcrypt cost, Argon2 m/t/p, PBKDF2 iterations)
CredentialData bound to an identity used to authenticate
Credential stuffingReplaying leaked username/password pairs from other sites
Discoverable credential (resident key)WebAuthn credential stored with its user handle on the authenticator; enables username-less login
DPoPDemonstrating Proof of Possession (RFC 9449): tokens bound to a client key via signed proofs
Drift windowNumber of TOTP time steps accepted around the current one
FIDO2WebAuthn plus CTAP2, the FIDO Alliance standards for passwordless authentication
FortifyLaravel's headless authentication backend
HOTPCounter-based one-time password (RFC 4226)
IdentityAccount and attributes representing a person or service
Idle timeoutSession ends after a period without activity
IntrospectionRFC 7662 endpoint that returns whether a token is active and its metadata
JWTJSON Web Token, signed claims verified without a lookup
LockoutBlocking an account or authenticator after failed attempts
Logout everywhereRevoking every session and token of an account
Memory cost / time cost / parallelismArgon2 parameters m (KiB), t (passes), p (lanes)
MFA / 2FAAuthentication with two or more factor types; 2FA = exactly two
MFA fatiguePush bombing until the user approves
Number matchingPush MFA where the user types or picks a number shown on the login screen
Opaque tokenRandom reference token with no readable content
PasskeyDiscoverable FIDO credential, synced or device-bound
Password sprayingOne common password against many accounts
PBKDF2Iterated HMAC key derivation; FIPS-approved password hash
PepperSecret key applied to all password hashes, stored outside the database
Phishing-resistantAuthentication that cannot be relayed to an impostor verifier (WebAuthn, client TLS)
Recovery codeSaved single-use secret for regaining access
Refresh tokenLong-lived token used only to obtain new access tokens
RehashReplacing a stored hash with one using current algorithm/parameters at login
Relying party (RP)The site that relies on WebAuthn or federation for authentication; RP ID is its domain
Remember meLong-lived token that recreates a session after browser restart
ReplayReusing a captured code or token
Reuse detectionRevoking a refresh token family when a used token is presented again
Risk-based authenticationAdapting required proof to signals like device, IP and location
Rotation (token)Issuing a new refresh token on each use; (password) forced periodic change, which NIST forbids
SaltPer-hash random value stored with the hash
SanctumLaravel package for SPA session auth and personal access tokens
PassportLaravel OAuth 2.0 server
scryptMemory-hard key derivation function (N, r, p)
SessionServer-side state linking a random ID to an authenticated identity
Session fixationAttacker plants a session ID before login; prevented by regenerating the ID
Sign countWebAuthn counter used to detect cloned authenticators
Single-use tokenToken deleted on first use (reset links, recovery codes)
SIM swapMoving a victim's phone number to an attacker's SIM
SMS OTPOne-time code over the phone network; NIST restricted authenticator
Stateless tokenSelf-contained token verified without server state
Step-up authenticationFresh proof required before a sensitive action
Synced passkeyPasskey copied across devices by a passkey provider, end-to-end encrypted
Timing attackInferring secrets or existence from response time
Token bindingBinding tokens to a TLS channel (RFC 8471); superseded in practice by DPoP and mTLS
TOTPTime-based one-time password (RFC 6238)
User verification (UV)WebAuthn flag: PIN or biometric was checked by the authenticator
WebAuthnW3C API for public key credentials scoped to a relying party
Keycloak / Auth0 / Okta / Cognito / OryIdentity providers: self-hosted open source, SaaS, AWS-managed, open source with cloud
go-webauthn / pquerna/otpGo libraries for WebAuthn relying parties and TOTP/HOTP

References ​

Built by Morteza Negahi