How to Add Two-Factor Authentication

Two-factor authentication stops most password-based account takeovers. The login step is the easy part. Recovery and rollout are where it usually goes wrong.

How to Add Two-Factor Authentication — Troiana insight cover

In short

Offer passkeys or security keys where you can, and authenticator app codes (TOTP) as a widely understood option. Avoid SMS for sensitive accounts. Issue single-use recovery codes during setup, and make sure that recovery isn't a weaker way in. Enforce the second factor on the server for every login path, including APIs and old endpoints, and start by requiring it for admin users.

Which methods to offer

OWASP's Multifactor Authentication Cheat Sheet is a good reference. In short:

MethodStrengthNotes
Passkeys, FIDO2, security keysStrongestPhishing-resistant; the private key never leaves the authenticator
Authenticator app (TOTP)GoodCheap and familiar, but codes can be phished
Push approvalGood, with careNeeds number matching, to reduce fatigue attacks
Email codeWeak to moderateOnly as secure as the mailbox
SMSWeakVulnerable to SIM swapping; avoid for personal or financial data
Security questionsNot acceptableOWASP no longer accepts them as a factor

OWASP's own summary is that “any MFA is better than no MFA”, so don't let the perfect stop you. For most web apps, a sensible default is passkeys plus TOTP, with recovery codes. If you don't want to build this yourself, an auth provider can do it for you. See how to choose an authentication method.

Passkeys and security keysStrongest
Authenticator app (TOTP)Good
Push approval, with number matchingGood, with care
Email codeWeak to moderate
SMSWeak
Security questionsNot acceptable
The ordering from OWASP's guidance as summarised above. Bar lengths show rank, not a measurement, and any MFA is better than none.

How TOTP works

During setup, your server generates a random secret and shares it with the user's authenticator app, usually through a QR code. From then on, both sides calculate a six-digit code from the secret and the current time, in 30-second steps (RFC 6238).

Both sides compute the same code
SetupServer and app share a secret
Each time stepEach computes a code from secret and time
LoginYou type the code, and the server compares
No code travels at setup and no network is needed by the app, which is why it works offline.

Here's a simplified flow in Node.js, using the otplib package. Check its current API before you copy this.

import { authenticator } from "otplib";

// 1. Setup: create and store a secret (encrypted)
const secret = authenticator.generateSecret();
const uri = authenticator.keyuri(user.email, "YourApp", secret);
// Show uri as a QR code

// 2. Confirm: only enable after the first valid code
if (authenticator.check(codeFromUser, secret)) {
  await enableTwoFactor(user.id, secret);
}

// 3. Login: after the password check succeeds
if (!authenticator.check(codeFromUser, user.totpSecret)) {
  // reject, and count the failure
}

Important details:

  • Encrypt the secret at rest, and keep the key out of your database. Unlike passwords, you do need to read it again, so it can't be hashed.
  • Confirm before enabling. Don't turn on 2FA until the user has proven that their app works.
  • Rate limit attempts. Six digits can be guessed by brute force without limits. See how to rate limit an API.
  • Prevent code reuse. Reject a code that's already been used within its time window.
  • Allow slight clock drift, typically one step either side.
  • Don't log codes or secrets.

Passkeys

Passkeys use public-key cryptography, through the WebAuthn standard. The site never receives a shared secret, and the browser ties the login to your real domain, which is why phishing sites can't capture anything useful. OWASP notes that you should require user verification, such as a PIN or biometric, and check that flag on the server, as a touch alone isn't a second factor.

Use a well-maintained WebAuthn library, rather than handling the protocol yourself. A passkey may replace both the password and the second factor, so it's worth considering as your long-term default. Also consider users who lose devices, and allow more than one passkey per account.

Recovery: where security gets undone

OWASP warns that recovery processes are a common attack route. If an attacker can bypass your 2FA by emailing support, then your 2FA isn't protecting much.

  • Issue single-use recovery codes at setup. Show them once. Store them hashed, as you would passwords.
  • Encourage more than one factor, such as a passkey and an authenticator.
  • Make support resets deliberate. Require strong verification, delays and notifications. Train staff to expect social engineering.
  • Notify users whenever 2FA is changed or a recovery code is used.
  • Don't let “forgot password” bypass the second factor. Password reset shouldn't sign someone in directly.

Where to require it

At every login path. OWASP notes that APIs and mobile apps are often missed. Old endpoints, single sign-on fallbacks and “remember me” routes can all allow a downgrade. List all your authentication routes, and test each one.

For sensitive actions. Ask again before changing a password, changing email, disabling 2FA or becoming an admin. Without this, a hijacked session can lock out the real user.

Always for privileged users. Admins, support staff and anyone with production access should have no choice in this.

Remembered devices. A “trust this device for 30 days” option is reasonable for many apps, but it should be a server-side record tied to the user, that can be revoked, and not simply a cookie that says “2FA passed”.

Looks protected
Web login: 2FA
API: 2FA
Mobile app: 2FA
But
Forgot password: no 2FA
Support reset: a phone call
An invented setup. The real strength is that of the weakest way in, so recovery paths count as login paths.

Rolling it out

  1. Start with admins and staff. Make it mandatory, and learn from the problems that come up.
  2. Offer it to all users as an option, with clear prompts in account settings.
  3. Make it mandatory for high-risk accounts, such as those with payment or personal data access.
  4. Give notice before enforcing it, along with a simple guide.
  5. Prepare your support team for lost phones and locked-out customers.
  6. Measure: enrolment rate, failed attempts, recovery use and support tickets.

Consider enterprise needs as well. Business customers often want single sign-on, which moves this responsibility to their own identity provider.

What 2FA doesn't solve

OWASP lists reverse-proxy phishing as a way of capturing codes and session tokens in real time, which is why passkeys are stronger. Session theft after login is another route, so protect your sessions as well. See sessions vs JWT. And a two-step login using a password plus a PIN isn't real MFA, because both are something you know.

If AI generated your authentication, review it closely, because a screen that asks for a code isn't proof that the server enforces one. Try the protected API directly, with only a password-level session. See the vibe-coded app security checklist.

If you'd like help reviewing your login and recovery flows, book a call.

Common questions

What is the best type of two-factor authentication?

Passkeys and hardware security keys are the strongest, as they resist phishing. Authenticator apps are a good, widely understood option. SMS is weaker, and should be avoided for accounts holding personal or financial data, though it's better than no second factor.

Should I build 2FA myself?

Often not. Auth providers and frameworks offer tested implementations of TOTP and passkeys. If you do build it, use maintained libraries, encrypt TOTP secrets, rate limit attempts and pay particular attention to recovery. Don't write your own crypto.

What happens if a user loses their phone?

Provide single-use recovery codes during setup, and encourage users to enrol more than one factor. Have a careful support process for everyone else, with strong verification and notifications, because recovery is a common way for attackers to get in.

Should I require 2FA for all users?

Require it for admins and anyone with sensitive access from day one. For general users, offer it first, then require it where the risk justifies it, such as payments or personal data. Mandatory rollouts need good guidance and support.

Have something worth building right?