How to Implement TOTP Two Factor Auth
Implement TOTP two-factor auth with a shared secret and a 30-second window, so a stolen password is not enough to log in.
On this page
Introduction
The hardest part of add a second factor is not writing the code — it is deciding what the code is allowed to reject. A TOTP setup that accepts everything is easy to ship and expensive to operate, because every malformed input becomes a production surprise. The discipline is to enumerate the shapes the system actually receives, encode them in TOTP, and let the library reject the rest loudly. This keeps the happy path fast and the failure path visible.
Most teams adopt TOTP for add a second factor after an incident teaches them that unvalidated input is load-bearing. The incident is the expensive way to learn the lesson; a quarterly review of the input shapes is the cheap way. Pin the shapes with TOTP, refuse the deploy that breaks the pin, and treat the pin as a contract the rest of the system can rely on. A contract that is not enforced is a wish.
The sections below walk through the concrete decisions: where to put the totp check, how to keep it fast under load, what to do when the contract changes, and how to test the failure paths so they degrade on purpose instead of by accident.
Generate a secret
Generate a secret is the first decision because it determines what the rest of the TOTP pipeline can assume. A wrong choice here turns into add a second factor under load, and the invariant you thought TOTP guaranteed no longer holds. Measure the impact before committing, because the cost of a bad choice is paid in incidents, not in a code review.
The test for Generate a secret is the one most teams skip: drive totp to the failing condition and assert the system degrades gracefully. Write it with a fake clock for time-based logic, a stub for the failure path, and an assertion on the user-visible outcome. A test that passes by timing out is a hope, not a test.
import { authenticator } from 'otplib';
const secret = authenticator.generateSecret();
const token = authenticator.generate(secret);
const ok = authenticator.verify({ token: userInput, secret });
The javascript above is the shape to ship for add a second factor. It is small enough to audit and specific enough that the failure behavior is obvious. Adapt the constants to your traffic and latency budget, and resist the urge to handle cases the system has not seen yet.
Show a QR code
The mechanism behind Show a QR code is straightforward in TOTP, but the consequences ripple. A wrong choice here turns into add a second factor under load, and the invariant you thought TOTP guaranteed no longer holds. Measure the impact before committing, because the cost of a bad choice is paid in incidents, not in a code review.
The test for Show a QR code is the one most teams skip: drive totp to the failing condition and assert the system degrades gracefully. Write it with a fake clock for time-based logic, a stub for the failure path, and an assertion on the user-visible outcome. A test that passes by timing out is a hope, not a test.
Verify the code
Verify the code is where most TOTP implementations leak performance. A wrong choice here turns into add a second factor under load, and the invariant you thought TOTP guaranteed no longer holds. Measure the impact before committing, because the cost of a bad choice is paid in incidents, not in a code review.
The test for Verify the code is the one most teams skip: drive totp to the failing condition and assert the system degrades gracefully. Write it with a fake clock for time-based logic, a stub for the failure path, and an assertion on the user-visible outcome. A test that passes by timing out is a hope, not a test.
test('valid code passes', () => {
expect(authenticator.verify({ token: authenticator.generate(secret), secret })).toBe(true);
});
Pin the behavior with this test. A TOTP setup that passes this test degrades on purpose instead of by accident, which is the difference between a managed failure and an incident.
Allow drift windows
The hard part of Allow drift windows is not the happy path — it is what happens when totp fails halfway. A wrong choice here turns into add a second factor under load, and the invariant you thought TOTP guaranteed no longer holds. Measure the impact before committing, because the cost of a bad choice is paid in incidents, not in a code review.
The test for Allow drift windows is the one most teams skip: drive totp to the failing condition and assert the system degrades gracefully. Write it with a fake clock for time-based logic, a stub for the failure path, and an assertion on the user-visible outcome. A test that passes by timing out is a hope, not a test.
Backup codes
Backup codes should be observable without a debugger. A wrong choice here turns into add a second factor under load, and the invariant you thought TOTP guaranteed no longer holds. Measure the impact before committing, because the cost of a bad choice is paid in incidents, not in a code review.
The test for Backup codes is the one most teams skip: drive totp to the failing condition and assert the system degrades gracefully. Write it with a fake clock for time-based logic, a stub for the failure path, and an assertion on the user-visible outcome. A test that passes by timing out is a hope, not a test.
Test TOTP
Test TOTP is a trade, not a winner. A wrong choice here turns into add a second factor under load, and the invariant you thought TOTP guaranteed no longer holds. Measure the impact before committing, because the cost of a bad choice is paid in incidents, not in a code review.
The test for Test TOTP is the one most teams skip: drive totp to the failing condition and assert the system degrades gracefully. Write it with a fake clock for time-based logic, a stub for the failure path, and an assertion on the user-visible outcome. A test that passes by timing out is a hope, not a test.
Common pitfalls
The common pitfalls in add a second factor all reduce to one mistake: treating TOTP as a formality instead of a contract. The contract is the thing the rest of the system relies on, and a weak contract propagates weakness everywhere.
- Skipping the totp boundary so add a second factor enters unvalidated.
- Assuming TOTP is fast without measuring the tail latency under load.
- Letting add a second factor fail silently instead of failing loudly with a metric.
- Testing only the happy path so the totp failure surfaces in production.
- Sharing mutable state across requests so one bad input poisons the next.
Conclusion
Do not conflate the conclusion with the implementation. They look similar from the outside but the failure modes differ: TOTP fails fast and the caller knows, while an unchecked path fails slow and the caller guesses. Choose the one whose failure mode your system can absorb, and document the choice at the call site.
Self-check: write a test that drives totp to the failing condition and assert the system degrades gracefully. Then add a second factor is a property you maintain, not a feature you hope for.
Sources: otplib, RFC 6238 TOTP
FAQ
- Allow time drift?
- One window before and after. More is convenient but weaker.
- Backup codes?
- Generate one-time codes for device loss. Store hashed.
Report a problem with this articleOpens a pre-filled issue on GitHub.