Designing user authentication means deciding who a user is and proving that claim before granting access, then managing that trust over time. The core answer: store secrets so a breach can't reverse them, use standardized protocols instead of custom cryptography, keep sessions short-lived and revocable, and layer step-up checks and recovery without creating new bypasses. The key condition is that every path into the account—login, password reset, email change, recovery codes—must be as strong as the front door. This guide covers the full design in a workable order, from requirements through verification, with the failure modes that sink real systems.

Start with requirements, threats, and identity boundaries

Before choosing a scheme, write down what "authenticated" must guarantee for your product. Three questions drive everything else: What accounts exist (customers, employees, admins, machine clients)? What is the harm of impersonation (read-only profile data versus money movement)? And what is the user's realistic device and network context (mobile app, shared computer, unreliable connectivity)?

Model the adversary next. A realistic threat list includes credential stuffing with leaked password lists, phishing that captures codes, session token theft via cross-site scripting, account recovery abuse through compromised email, and insider access to logs or databases. Rank these by impact and likelihood for your population; the ranking decides where you spend complexity. A consumer social app and an employee admin console should not share a threat model.

Draw the identity boundary explicitly. Decide whether authentication lives in your app or in an external identity provider. Building it yourself is justified when you need deep control over the UI and data, or when you serve a small internal population. Delegating to a standards-based provider (OpenID Connect) usually wins for consumer apps because it inherits years of hardening on reset flows, fraud detection, and compliance. Either way, the rest of this guide applies: the provider is a component, not an exemption from design.

Finally, define the authentication states your system will track: anonymous, partially verified (password accepted, second factor pending), fully authenticated, and elevated (recent re-verification). Every endpoint and API should be able to answer "which state is required here?" That single habit prevents most authorization confusion downstream.

Credential storage: hashing, salts, and work factors

If you store passwords, you must store them in a form that is expensive to reverse. The supported method is a memory-hard password hashing function—Argon2id is the current general recommendation, with bcrypt and scrypt as long-established alternatives. Store the algorithm identifier and parameters alongside each hash so you can upgrade later, and generate a unique random salt per password (most modern libraries handle this for you).

A worked illustration, not a benchmark: suppose you pick Argon2id with a memory cost of 64 MiB, three iterations, and one lane of parallelism. On a typical server core, each verification might take on the order of 50–150 milliseconds—fine for a login endpoint, punishing for an attacker scoring billions of guesses without the same per-core memory. The exact milliseconds depend on your hardware; measure on your own deployment and tune so logins stay responsive under peak load. The design principle is that the cost parameters must produce a deliberate delay, not a token one.

Never invent your own scheme—no repeated SHA-256 rounds, no "encrypt with a secret key and call it hashed." Use a maintained library in your language, and keep the hashing code isolated so it can be reviewed. Two operational rules matter as much as the algorithm: rate-limit verification attempts per account and per source address, and log failures without logging the submitted password. If a breach does occur, having parameter metadata lets you force a rehash on next successful login rather than locking everyone out.

For non-password credentials, the storage rule changes with the type. Compare them on equivalent criteria:

Credential What is stored Replay risk if database leaks Notes
Password Argon2id/bcrypt hash + salt Low (slow to crack, but weak passwords fall) Needs reset and rate limiting
TOTP second factor Shared secret (encrypted at rest) High—secret allows code generation Encrypt the secret; rotate on re-enrollment
Passkey (WebAuthn) Public key + credential ID None for the private key (never leaves device) Phishing-resistant by design
Recovery codes Hashes of one-time codes Low if hashed Regenerate after use; show once
Session token Hash or keyed digest of the token Low if hashed Token itself returned only to client

That table is the decision aid: prefer passkeys where your user population supports them, keep passwords hashed with a modern function, and treat TOTP secrets and recovery codes as high-value secrets that deserve encryption and hashing respectively.

Registration, verification, and the first login

Registration is where many designs accidentally build the bypass they later try to close. The prerequisite is a decision on whether accounts are created by users (self-service) or provisioned by an administrator; self-service needs abuse controls from day one.

1: Collect the minimum identity data—typically an email address or phone number plus a password or passkey enrollment. Avoid collecting government IDs or security questions you cannot protect. 2: Validate format and normalize consistently (lowercase email domains, strip whitespace) so duplicate accounts and lookups behave predictably. 3: Check for an existing account without revealing it. If the address is taken, send a notification to that address rather than displaying "already registered" to an anonymous visitor—this prevents account enumeration. 4: Create the record in a "unverified" state and send a time-limited verification link or code. The token should be single-use, high-entropy, stored hashed, and expire in hours, not weeks. 5: On successful verification, mark the account verified and establish the first session. If the user never verifies, expire the record or restrict it to a re-sendable state; don't let unverified accounts accumulate as a spam vector.

Success looks like this: a new user receives one message, the link works once within its window, and a second click fails cleanly with a "link expired" message rather than an error page. A simple check: register with a duplicate address and confirm the response is identical to a fresh registration except for the email received.

First login after registration should not be a separate, weaker path. If you auto-login after verification, apply the same session rules described below. If you require re-entry of the password, rate-limit it. The common failure here is a "welcome" flow that trusts an identifier in a URL—avoid putting account-identifying and trusting data in query strings.

Login flow, rate limiting, and enumeration resistance

The login endpoint's job is to answer one question without leaking anything else. Prerequisites: password hashing in place, a rate-limit store (in-memory per node or a shared cache), and logging that never records credentials.

1: Accept the identifier and secret over TLS only; reject plaintext transport everywhere. 2: Normalize the identifier, then look up the account. To avoid timing leaks that reveal whether an account exists, perform a dummy hash verification even when no account is found, so response time is similar. 3: Verify the password with the stored algorithm and parameters, or verify the passkey assertion per WebAuthn. If verification fails, record the attempt keyed by account and by source address. 4: Apply progressive defenses: after a handful of failures for an account, add a delay and require an additional check (a second factor or a short lockout with backoff); after many failures from one address or subnet, throttle harder. Use exponential backoff rather than permanent lockout, which enables denial-of-service against a known username. 5: On success, if a second factor is enrolled, do not issue a full session yet—issue a short-lived "pending" token that only permits the second-factor endpoint. 6: Issue the full session (details below), record the event with time, coarse location, and device description for the user's activity log, and reset the failure counters.

Return a generic error message ("the credentials didn't match") for all failures, and keep response body and status identical whether the failure was a bad password, unknown account, or pending second factor. That is your enumeration defense, and it costs nothing in UX if your error copy is written well.

Success check: attempt five wrong passwords on one account from one address and confirm the response time degrades and a second factor or backoff engages; attempt the same from a different address and confirm the policy is per-account first, then per-address. The stop condition: if rate-limit failures affect legitimate users broadly (for example, shared office networks), move the primary throttle to per-account plus progressive challenge rather than blunt IP blocking.

Sessions and tokens: cookies, lifetimes, and revocation

After authentication succeeds, you must carry that proof across requests. Two supported patterns exist: server-side sessions identified by an opaque cookie, and signed tokens (JWTs) validated by the service. Pick one primary mechanism per surface rather than mixing freely.

For browser sessions, the robust default is a server-side session store keyed by a high-entropy random identifier, delivered in a cookie configured HttpOnly, Secure, and SameSite=Lax (or Strict where it doesn't break flows). HttpOnly keeps the token out of reach of page scripts, which blunts cross-site scripting token theft; Secure prevents transmission over plaintext; SameSite limits cross-site request forgery. Store the session server-side so revocation is immediate—deleting the record logs the user out everywhere the identifier was used. Set an absolute lifetime (for example, 30 days) plus an idle timeout (for example, 30 minutes for sensitive apps), and rotate the session ID at login and after privilege changes to prevent fixation.

For APIs and mobile clients, bearer tokens are practical but need discipline. If you use JWTs, keep access tokens short-lived (minutes), pair them with a refresh token that is stored server-side (hashed) and single-use, and implement rotation with reuse detection: if a refresh token is presented twice, revoke the whole family. That detection is the mechanism that converts a stolen refresh token from a permanent skeleton key into a detectable event. Put only necessary claims in the token, validate signature and expiry on every request, and remember that a stateless JWT cannot be revoked before expiry unless you check a denylist—so keep lifetimes genuinely short.

A concrete session table design: session_id (random, indexed), user_id, created_at, last_seen_at, absolute_expiry, device_label, and a revocation flag. On each request, look up by session_id, reject if expired or revoked, and update last_seen_at at a coarse interval (for example, once per minute) to avoid a write on every request. That interval is an illustrative tuning choice; check it against your database write budget.

Second factors, passkeys, and step-up authentication

Adding a second factor raises assurance only if the enrollment and fallback paths are as protected as the login. TOTP (time-based one-time passwords) is widely supported and cheap to operate; passkeys are stronger because they bind to the origin and resist phishing; SMS codes are better than nothing but vulnerable to SIM swap and interception, so treat them as a fallback of last resort for high-value accounts.

Enrollment procedure matters more than most teams expect:

1: Require a recent, full authentication before allowing enrollment of a new factor. 2: For TOTP, generate the secret server-side, show it once, require the user to prove possession by entering a valid code before activating it. Encrypt the stored secret at rest. 3: Generate recovery codes at the same time, show them exactly once, and store only their hashes. Mark each as consumed on use. 4: Send a notification to the user (and to any other verified channel) whenever a factor is added or removed, with a one-click way to freeze the account.

Step-up authentication is the practice of demanding fresh proof for sensitive actions even inside a valid session—changing a password, adding a payment method, exporting data. Implement it as a "recent authentication" timestamp on the session: if the last full verification is older than, say, five minutes, redirect to re-verify before proceeding. This is a design decision, not a constant; pick the window by action sensitivity and state it in your requirements document.

The comparison between factors deserves explicit criteria rather than a slogan. Passkeys win on phishing resistance and remove shared secrets; TOTP wins on universal support and simple recovery; SMS wins on reach and loses on interception risk. For most products, the sound sequence is passkeys offered first, TOTP as the broadly available option, and SMS restricted to recovery or low-risk contexts.

Recovery, account changes, and avoiding the bypass

Every recovery path is an authentication path and must be designed with the same rigor. The classic failure is a strong login protected by a second factor and a password reset by email that skips it entirely—the attacker simply resets.

Prerequisites: verified contact channels on file, a token store, and notification infrastructure. The reset flow:

1: Accept the identifier and always respond that "if an account exists, a message was sent," with no differentiation. 2: Generate a single-use, high-entropy token, store its hash with an expiry measured in minutes to a couple of hours, and invalidate prior outstanding tokens for that account. 3: Deliver the link only to the verified channel. On use, require the user to set a new password, and if a second factor is enrolled, require it before the reset completes—or at minimum notify and offer a cancel window. 4: Invalidate all existing sessions on password change, and record the event.

For email or phone number changes, treat the change as a sensitive action: require recent authentication and confirm from the new address before it becomes active. Never let a pending change silently receive recovery messages.

Recovery codes are the honest fallback for lost factors. Generate ten or so, hash them, let each work once, and regenerate the full set after any use. Show them only at generation and offer a re-issue flow that itself requires recent authentication.

Stop condition: if you cannot verify a recovery request through any channel the user controls, escalate to a human support process with identity checks appropriate to your risk. Do not invent a "security questions" shortcut to avoid that queue—knowledge-based questions are often guessable from public data.

Authorization boundaries, logging, and what to verify

Authentication answers who; authorization answers what. Keep them separate in code and in review. Sessions and tokens should carry a stable user identifier, not a role list that can drift out of sync; resolve permissions server-side per request or cache them with a short TTL. Every endpoint should default to deny and declare its required authentication state and permission explicitly.

Logging is part of the design, not an afterthought. Record successful and failed authentications, factor enrollments, recovery events, session revocations, and administrative access—each with a timestamp, user identifier, source address, and device label. Never log passwords, raw tokens, TOTP codes, or full recovery codes. Give users a visible activity page listing recent sessions and events, with the ability to revoke individual sessions. That page turns detection into a user-empowered control and is one of the highest-value features you can ship.

Verification checklist before launch: TLS enforced on all auth endpoints; password hashing parameters measured and documented; rate limits tested per account and per address; enumeration responses identical across failure types; session cookies configured HttpOnly, Secure, SameSite; refresh-token rotation with reuse detection tested; reset flow requires the same factors as login; all sessions invalidated on password or factor change; notifications sent on security events; logs free of secrets. Each item is checkable with a specific request and a specific expected response, which is how you convert a design into evidence.

Common failure modes and how to recognize them

The most expensive mistakes are structural, and they tend to announce themselves in specific symptoms. A login that responds measurably faster for unknown accounts reveals enumeration; fix it with the dummy-hash technique and identical error copy. A password reset that completes without the second factor is a bypass; confirm by resetting while a TOTP is enrolled and checking whether a full session is granted. A long-lived JWT with no denylist makes logout cosmetic; test by revoking a session and replaying the token. Session IDs that don't rotate at login leave fixation open; check that the identifier changes after authentication. Rate limits applied only per IP break shared networks and fail to stop distributed stuffing; test with rotating source addresses and confirm the per-account throttle still engages.

A subtler failure is inconsistent identity across channels. If the web app, mobile app, and support tool each maintain their own session logic, one of them will lag on revocation. Centralize the session store and expose one authentication service for all clients—this is an architectural decision worth making early, because retrofitting it later means auditing every client. Another is treating the identity provider as a black box: even with OIDC, you must configure redirect URIs strictly, validate the ID token's issuer and audience, and handle the logout and recovery flows the provider documents, rather than assuming they match your app's expectations.

Finally, resist the urge to add factors as a substitute for fixing flows. A second factor bolted onto a reset that already bypasses it adds friction without security. Fix the weakest path first; the strength of a chain is its weakest link, and in authentication the weakest link is usually recovery.

How to verify the design works before and after launch

A design is only real when it has been exercised. Before launch, run these checks in a staging environment with test accounts that mirror your population—consumer, admin, and machine clients if applicable.

Test the primary path: register, verify, log in with each supported factor, and confirm session attributes in the browser's developer tools (cookie flags, expiry). Test the negative space just as carefully: wrong password five times, expired verification link, reused reset token, revoked session replayed, refresh token used twice. Test the recovery path end to end, including a lost-factor scenario using a recovery code, and confirm every prior session dies on password change. Test step-up by attempting a sensitive action from a stale session and confirming the re-verification prompt appears.

After launch, watch three signals: failure rates by endpoint (a spike in resets or second-factor failures often means UX friction, not attack), rate-limit trigger counts by account and address, and session revocations initiated by users, which indicate compromised or shared devices. Instrument the login funnel—registration start to verified account to first successful login—so you can spot a broken verification email before support tickets arrive. These measurements are ordinary and don't require special tooling beyond your existing analytics and audit logs.

Success criteria are specific: no failure response distinguishes account existence; every listed check produces its expected result; and your activity log shows the test events with the right metadata. If any check reveals a discrepancy, fix the flow rather than documenting around it—authentication bugs are rarely isolated.

FAQ

Should I build authentication or use an identity provider? Build when you need deep UI control, a small or internal population, or unusual data residency; otherwise a standards-based provider usually carries less risk because it arrives with hardened recovery, fraud detection, and compliance. Either way, the checks in this guide apply to the provider's configuration.

Are passkeys ready to be the primary method? They are supported across major browsers and platforms, but your population's device mix and recovery readiness decide the roll-out. A sound pattern is to offer passkeys first, TOTP as the broadly compatible second factor, and keep recovery codes as the fallback. Check current platform support for your target users rather than assuming uniform availability.

How long should sessions last? Match lifetime to sensitivity: short idle timeouts (minutes) for admin and financial actions, longer absolute lifetimes (weeks) for low-risk consumer reading. Refresh tokens should rotate, be single-use, and revoke their family on reuse, so a stolen token becomes a detectable event rather than a durable key.

Do I need to encrypt the password hash? No—hashing is the protection, and encryption adds key-management risk without solving reversibility. What you must encrypt is the TOTP shared secret and any other recoverable credential; what you must hash is the password, recovery codes, and session or refresh tokens.