How-To Guide

How to Implement Two-Factor Authentication with TOTP

Add TOTP-based two-factor authentication: enroll a secret, verify time-based codes with a window, prevent replay, and provide recovery codes.

On this page

  1. Introduction
  2. Enroll and confirm the shared secret
  3. Verify codes within a small window
  4. Prevent replay of a code
  5. Issue recovery codes
  6. Test enrollment, skew, and replay
  7. Common pitfalls
  8. Conclusion

Introduction

Passwords alone are one factor: something the user knows, which can be phished, reused, or leaked. Two-factor authentication adds a second factor, often a time-based one-time password generated by a phone app. TOTP is the algorithm behind the six-digit codes that change every thirty seconds, defined by RFC 6238 on top of HOTP. Implementing it well means enrolling the secret carefully, tolerating clock skew without opening the window too wide, and preventing a code from being reused.

This tutorial implements TOTP enrollment and verification: generate and confirm a shared secret, verify codes within a small window, record the last accepted step to block replay, and issue recovery codes. It ends with tests for enrollment, skew, and replay. The examples use a TOTP library, but the protocol is standardized so the pieces are interchangeable.

Enroll and confirm the shared secret

Enrollment generates a random shared secret per user and shares it with the authenticator app, usually by encoding it in an otpauth URI rendered as a QR code. The secret is a base32 string the app stores and uses with the current time to compute each code. Do not enable 2FA until the user proves they scanned it, by entering a valid code, or a mis-scan silently locks them out.

Store the secret encrypted at rest, because it is a shared credential: whoever has it can generate valid codes. If a database is read, an unencrypted TOTP secret lets the attacker produce codes and defeat the second factor. Encrypt it with a key held outside the database, and confirm enrollment by verifying one code before setting the account to two-factor enabled.

import { authenticator } from 'otplib';

function beginEnrollment(userId: number) {
  const secret = authenticator.generateSecret(); // base32, high entropy
  const uri = authenticator.keyuri('[email protected]', 'ExampleApp', secret);
  return { secret, uri }; // render uri as a QR code; store secret encrypted
}

function confirmEnrollment(secret: string, code: string): boolean {
  return authenticator.verify({ token: code, secret });
}

Verify codes within a small window

A TOTP code is computed from the secret and the current time step, where the step is the unix time divided by the period, thirty seconds by default. A code is valid for its step and becomes invalid in the next. To tolerate the clock skew between the phone and the server, accept a window of one step before and after the current one, and no more.

The window is a trade-off. A window of zero rejects codes when the phone’s clock is off by a few seconds, frustrating users. A window of several steps lets a code remain valid for minutes, which weakens the second factor and increases the chance a code guessed or observed is still usable. One step on each side, a total of about ninety seconds, is the common balance; document it and keep it small.

authenticator.options = { window: 1 }; // accept current step +/- 1

function verifyCode(secret: string, code: string): boolean {
  return authenticator.verify({ token: code, secret });
}

Prevent replay of a code

Within the window a code is accepted, an attacker who observes it could replay it in the same window even without the secret. TOTP has no built-in replay protection; the server must add it. Record the time step of the last accepted code per user and reject a code whose step is not strictly greater than the last. A replayed code in the same step is then rejected.

Store the last accepted step per user and update it atomically with the successful verification, in the same transaction that marks the login. This closes the replay window while the clock tolerance still allows a slightly old code once. It also handles the case where a user enters a code twice quickly, which would otherwise let a second factor be reused.

ALTER TABLE users ADD COLUMN totp_last_step bigint;

-- accept only if the current step is newer than the last accepted one
UPDATE users
SET totp_last_step = $2
WHERE id = $1 AND totp_last_step IS NULL OR totp_last_step < $2
RETURNING id;  -- a row means accepted; no row means replay

Issue recovery codes

Users lose their phone. Without a fallback, a lost device means a locked account and a support burden. Issue a set of one-time recovery codes at enrollment, each a high-entropy random string that can be used in place of a TOTP code. Generate them once, show them once, and store only their hashes, exactly as with a password or a reset token.

Consume each recovery code on use by marking it used, so it works once. A recovery code is as powerful as a TOTP code, so it must be hashed and rate-limited, and using one should trigger a notification so the owner notices an unexpected recovery. Let the user regenerate the set, invalidating the old ones, when they suspect the list leaked.

import { randomBytes, createHash } from 'node:crypto';

function generateRecoveryCodes(n = 10) {
  return Array.from({ length: n }, () => {
    const code = randomBytes(10).toString('base64url'); // shown to the user once
    return { code, hash: createHash('sha256').update(code).digest('hex') }; // store hash
  });
}

Test enrollment, skew, and replay

Test that a code from the current step verifies and a code from many steps away does not, proving the window is bounded. Test that the same code used twice fails the second time, proving replay protection. Test that enrollment is not complete until a valid code is confirmed. Test that a recovery code works once and is then rejected. These four tests cover the window, the replay guard, the enrollment gate, and the fallback.

# current code accepted, same code again rejected (replay), far-future code rejected
node scripts/totp-verify.mjs $SECRET $(node scripts/totp-now.mjs)     # accepted
node scripts/totp-verify.mjs $SECRET $(node scripts/totp-now.mjs)     # rejected (replay)
node scripts/totp-verify.mjs $SECRET 000000                            # rejected

Common pitfalls

Enabling 2FA before the user confirms a code so a mis-scan locks them out, storing the TOTP secret unencrypted, a verification window wide enough to weaken the factor, no replay protection so an observed code is reusable, and recovery codes stored in plaintext or unlimited are the recurring mistakes. Confirmed enrollment, encrypted secrets, a one-step window, a stored last step, and hashed one-time recovery codes address them.

Conclusion

TOTP is a standardized second factor: a shared secret, a time step, and a code. Enroll and confirm the secret, verify within a small window, record the last accepted step to block replay, and issue hashed one-time recovery codes. Self-check by asserting an old code is rejected, a replay is rejected, enrollment requires a valid code, and a recovery code works once. Then the second factor is meaningful instead of a checkbox.

Sources: RFC 6238: TOTP, RFC 4226: HOTP, OWASP: Multifactor authentication cheat sheet.

FAQ

How wide should the verification window be?
One step before and after the current one, which with a 30-second period tolerates about 30 seconds of clock skew. Wider windows increase the chance a code is valid across two attempts or brute forced; keep it small.
Why store recovery codes hashed?
They are as powerful as a code: whoever has one can log in. Hash them like passwords so a database read does not hand over the ability to bypass 2FA, and mark each used so it works once.

Related Examples