Secure 2FA and MFA: A 10-Minute Developer Guide

How attackers get around 2FA through recovery and reset flows, and how to build TOTP, backup codes and factor changes that hold up. Ends with a production checklist.

By VikasPublished 8 Oct 2026Updated 9 Oct 20265 min read

Get the PDF

Free. No email or account needed. PDF · 195 KB

Download PDF

The preview only loads when you tap "Read PDF here", which saves mobile data. Download gives you the original PDF file.

Key takeaways

  • Every way to add, remove or reset a factor must be as strong as login.
  • Treat the TOTP seed like a long-lived password.
  • Store each accepted time-step so a code cannot be replayed.
  • Revoke sessions and notify the owner after any factor change.
  • Prefer passkeys or security keys for admins and payments.

Adding 2FA to an app is easy. Making 2FA that attackers cannot walk around is harder. This guide uses simple language and real attack examples to show the checks a production 2FA or MFA setup needs, from TOTP setup to recovery.

First understand the real problem

2FA means the user proves who they are with two different things: something they know (a password) and something they have (a phone, an authenticator app, a passkey or a security key).

Take an attacker who has the user's password but not the 6-digit code. They click Forgot 2FA. If one email link can switch 2FA off, the attacker never needs the code. The recovery path has defeated MFA.

The golden rule: every path that can add, remove, reset or replace a factor must be at least as secure as normal login.

  • Weak design: password → TOTP → login, but an email link can disable TOTP.
  • Secure design: strong proof → risk check → delay if needed → reset → revoke sessions → notify the owner.

How to implement TOTP correctly

TOTP is a time-based 6-digit code. The authenticator app and your server both calculate it from the same secret seed.

The QR code contains that secret seed. Anyone who copies the seed can generate valid codes forever, so treat it like a long-lived password, not a temporary picture.

When the user turns TOTP on

  1. Re-authenticate. Ask for the password or an existing strong factor. A stolen logged-in session alone must not be able to add MFA.
  2. Create and protect the seed. Generate at least 160 random bits with a CSPRNG. Encrypt the seed with authenticated encryption and keep the key in a KMS or HSM, away from the database.
  3. Show the QR once. Build an otpauth URI with an issuer and an account name. Never send the URI or the seed to logs, analytics, crash reports, support tools or third parties.
  4. Verify before activation. Ask for one fresh code. Only after it verifies should the factor become active. Then create backup codes and notify the owner.

What the server should do at login

  1. Load the encrypted seed and decrypt it only inside the auth service.
  2. Check codes in a small window: the current 30-second step, usually plus or minus one step for clock drift.
  3. Compare codes with a mature TOTP library. Never write your own crypto.
  4. Store the accepted time step atomically, and reject that same step if it is submitted again.
  5. On success, complete only the login or action that created this challenge, then expire the challenge.

Rate limiting. A 6-digit code has only 1,000,000 possibilities. Limit attempts per account, per IP or network, and per device signal. Increase the delay after failures, but avoid a permanent lockout that attackers could abuse to lock real users out.

Replay prevention. Two requests can submit the same valid code at the same moment. Use an atomic compare-and-set in the database so only one request can mark that time step as used.

Recovery: the part most teams weaken by accident

Treat recovery as another high-risk login protocol, not a support convenience.

A worked example: the attacker knows the password and controls the user's mailbox. Normal login stops them at TOTP. So they choose Forgot 2FA, use the email link, attach their own authenticator and walk in. 2FA existed, but email recovery was the real master key.

A safe recovery flow

  1. Use remaining proof. Password plus a backup code, an existing passkey or security key, another trusted factor, or carefully checked identity evidence. Email alone is weak proof.
  2. Evaluate risk. Check for a new device, an unusual location, many attempts in a short time, recent password, email or phone changes, and known-compromised signals. High risk should add a delay, a review or a denial.
  3. Reset with containment. Invalidate the old factor and its backup codes. Revoke all sessions, or at least every other session, and cancel pending challenges.
  4. Notify and keep evidence. Alert every verified channel with the time and device details and a safe "not me" option. Log who approved the reset, the evidence used, the risk signals and the outcome.

Backup codes

  • Generate random, high-entropy codes with a CSPRNG.
  • Show them once and let the user download or print them safely.
  • Store only a slow password hash or a keyed hash.
  • Each code works once. Generating a new set invalidates the whole old set.

Support and manual recovery

  • Support must never casually switch MFA off.
  • Follow a written policy: what evidence is acceptable, who approves, cooldowns and escalation.
  • For valuable or admin accounts, separate the requester, the reviewer and the approver.
  • Audit support access and every recovery decision.

Adding, removing or replacing a factor

Require recent strong re-authentication, verify the new factor, invalidate the old factor and its recovery codes, revoke sessions and notify the owner. A stolen session cookie must never be enough. For admins or money movement, prefer a security key or passkey and consider a second approver.

Which method should you use?

Prefer phishing-resistant factors, and keep weaker methods only where users really need them.

Method Good for Main risk
Passkey or security key (phishing-resistant) Admins, payments, the best default Device loss, so plan for several keys or devices
TOTP app (strong baseline) Most apps and developer tools Can be phished, and the seed can be stolen
SMS OTP (fallback only) Users without an authenticator app SIM swap, recycled numbers, delivery problems
Email OTP (not independent) Low-risk step-up checks The mailbox often controls recovery too

Final production checklist

  • The TOTP seed is created with a CSPRNG and encrypted at rest, with the key stored separately.
  • Enrollment requires re-authentication and one successful code before activation.
  • Verification has per-account and network or device rate limits, and a small clock-drift window.
  • The accepted TOTP time step is stored atomically to prevent replay.
  • Backup codes are random, hashed, single-use and replaced as one set.
  • Secrets, QR URIs, OTPs and recovery evidence never reach logs, analytics or support tools.
  • Recovery never disables MFA from an email link alone, and risk checks and cooldowns exist.
  • Adding, removing or resetting a factor requires recent strong re-authentication and verifies the new factor.
  • A factor reset or change revokes sessions, pending challenges and old recovery codes.
  • The owner gets useful notifications with a safe "not me" action.
  • Support recovery has written evidence, approval and audit requirements.
  • Trusted-device tokens are random, revocable from the server and expiring, and they are ignored for sensitive actions.
  • Audit logs record the actor, factor, action, time, device and risk signals, and the result, and alerts watch for abuse.

Remember

Your MFA is only as strong as the easiest path that can reset, remove or replace it.

Tags

All resources
Security & Privacy

Admin 2FA: The 2 Checks Most Tutorials Miss

A 21-page guide to adding TOTP 2FA to an admin panel properly, for Google sign-in or email and password, with replay protection, session rotation and a final checklist.

Updated 9 Oct 2026
Security & Privacy

Complete Website & App Security Checklist

27 website and app security checks in easy English. Review secrets, login, permissions, APIs, uploads, payments and backups with this free 5-page PDF checklist.

Updated 26 Oct 2026
Security & Privacy

Hidden File Extensions: A Safety Guide

How hidden extensions and names like photo.jpg.exe trick people on Windows and macOS, how to show real extensions, and what to do if you opened a suspicious file.

Updated 9 Oct 2026
Security & Privacy

Homograph Attacks: Spot Fake Look-Alike Links

A 5-minute guide to fake domains that use look-alike letters, how the scam works, and seven simple habits that protect your accounts.

Updated 9 Oct 2026