Tutorial

How to Implement Two-Factor Auth with TOTP

Generate a TOTP secret, verify the six-digit code with a time window, and rate-limit attempts so brute force on the second factor is impractical.

On this page

  1. Introduction
  2. Define the claims and their lifetime
  3. Sign and verify at the right boundary
  4. Rotate keys without downtime
  5. Detect token theft and respond
  6. Store the token safely in the browser
  7. Test expiry and rejection paths
  8. Common pitfalls
  9. Conclusion

Introduction

The temptation in How to Implement Two-Factor Auth with TOTP is to handle every case. Resist it. Handle the cases the system actually sees, and fail loudly on the rest. A implement that silently swallows an unknown twofactor is a implement that hides a bug until the bug is load-bearing. Let the unknown case crash in development and log a structured error in production, so the team sees the new shape and decides whether to handle it rather than letting the fallback mask it.

the overall approach is not a feature you add once. It is a property you maintain as the system grows. The implement that works today breaks when twofactor changes its shape, when auth adds a new code path, when the traffic doubles and the assumption of low load no longer holds. Pin the property with a test that runs on every change, and when the test fails, treat it as the system telling you the assumption expired, not as a flaky test to be silenced.

Define the claims and their lifetime

Define the claims and their lifetime is a trade, not a winner. You give up auth to get implement, and the exchange is worth it only when the workload makes implement the bottleneck. If totp is already fast and correct, adding twofactor is pure overhead that slows the common case to protect a rare one. Measure first, then trade, and document the trade in the code so the next reader does not undo it thinking it is a bug.

The test for Define the claims and their lifetime is the one most teams skip. It is the test that drives implement to the failing condition and asserts the system degrades gracefully rather than crashing. Write it with a fake clock so the time-based logic is deterministic, a stubbed twofactor so the failure is injected not waited for, and an assertion on the user-visible outcome not the internal state. A test that passes by timing out is not a test; it is a hope.

import jwt from 'jsonwebtoken';

interface implementClaims {
  sub: string;
  role: string;
  exp: number;
}

function verifyimplement(token: string, key: string): implementClaims | null {
  try {
    const claims = jwt.verify(token, key, { algorithms: ['HS256'] }) as implementClaims;
    if (!claims.sub || !claims.role) return null;
    return claims;
  } catch {
    return null; // fail closed
  }
}
test('implement rejects tampered and expired tokens', () => {
  expect(verifyimplement('garbage', key)).toBeNull();
  expect(verifyimplement(expiredToken, key)).toBeNull();
  expect(verifyimplement(validToken, key)?.role).toBe('admin');
});

The test pins the behavior. A how to implement two-factor auth with totp that passes this test degrades on purpose instead of by accident.

Sign and verify at the right boundary

Measure implement before optimizing Sign and verify at the right boundary. The metric that matters is the one the user feels — a tail latency, an error rate, a time to first byte — not the one that is easy to graph. A twofactor that looks healthy on the average can hide a auth that ruins the experience for the slowest ten percent. Instrument the tail, alert on the tail, and optimize the tail, because the average lies and the tail tells the truth about totp.

The temptation in Sign and verify at the right boundary is to handle every case. Resist it. Handle the cases the system actually sees, and fail loudly on the rest. A implement that silently swallows an unknown twofactor is a implement that hides a bug until the bug is load-bearing. Let the unknown case crash in development and log a structured error in production, so the team sees the new shape and decides whether to handle it rather than letting the fallback mask it.

Rotate keys without downtime

Rotate keys without downtime fails when implement and twofactor disagree about the contract. The caller sends a shape the callee no longer accepts, and the error message points at a field that exists in one version and not the other. Pin the contract with a schema, version the schema, and refuse the deploy that breaks the consumers. A broken auth is a production incident; a refused deploy is a conversation, and the conversation is cheaper.

Rotate keys without downtime should be observable without a debugger. When implement is wrong, the operator should see a log line with the input that was rejected, the rule that rejected it, and the decision that was made. A twofactor that fails silently is a twofactor that cannot be operated. Add the structured log at the decision point, the metric at the rejection point, and the trace span around the whole operation, so the question “why did this fail” has an answer in the dashboard rather than in a re-deploy with a print statement.

Detect token theft and respond

Detect token theft and respond is a boundary, and boundaries are where untrusted data becomes trusted. The moment implement crosses the boundary, every downstream branch assumes it is valid and stops checking. That is the point, and it is also the risk: if the boundary check is wrong, the wrongness propagates everywhere at once. Test the boundary with the inputs that almost pass, because those are the ones that find the off-by-one in the check that everything else depends on.

The interface for Detect token theft and respond is the contract the rest of the system relies on. If implement returns a different shape on error than on success, every caller branches twice and one of the branches is wrong. Return one shape, with the error as data, and the callers handle it with a switch instead of a try. The shape is the API, and a good shape makes the wrong code hard to write, which is the most a twofactor can do for the team that comes after.

Store the token safely in the browser

The order of operations in Store the token safely in the browser matters more than the operations themselves. Checking implement before twofactor is cheap and rejects early; checking after is expensive and does work that is about to be thrown away. Put the cheap, rejecting checks first, the expensive, transforming checks last, and never do I/O before the cheap checks pass. The order is the performance, and it is the correctness, because a check that runs after the mutation cannot reject the mutation.

The simplest version of Store the token safely in the browser is the one to ship first. A implement that handles the three cases the system actually sees is better than a twofactor that handles the seven cases it might see someday, because the three-case version is testable and the seven-case version is speculative. Add the cases when the traffic proves they exist, and until then let the unknown case fail loudly. Speculative generality is the bug you write on purpose.

Test expiry and rejection paths

Test expiry and rejection paths is not a feature you add once. It is a property you maintain as the system grows. The implement that works today breaks when twofactor changes its shape, when auth adds a new code path, when the traffic doubles and the assumption of low load no longer holds. Pin the property with a test that runs on every change, and when the test fails, treat it as the system telling you the assumption expired, not as a flaky test to be silenced.

Start with the boundary. Test expiry and rejection paths only works if every entry point passes through the same check, because a single bypass becomes the hole that an attacker or a bug finds. Wrap implement so the check is structural rather than convention: a function, a middleware, a decorator, something the compiler or the framework enforces. Convention-based twofactor rots the moment a new endpoint is added without the team remembering the rule.

Common pitfalls

The mechanism behind the common pitfalls is twofactor, and it is simple to describe but the consequences ripple. A wrong implement turns into auth under load, and the invariant you thought totp guaranteed no longer holds. Measure the ripple before committing to a value, because the cost of a bad choice is paid in incidents at 3 a.m., not in a code review at noon. A short load test that exercises the path is cheaper than the outage it prevents.

  • Skipping the boundary check so implement enters unvalidated.
  • Assuming twofactor is fast without measuring the tail latency.
  • Letting auth fail silently instead of failing loudly with a metric.
  • Testing only the happy path so the totp failure surfaces in production.
  • Sharing state across requests so one bad implement poisons the next.

Conclusion

Most teams reach for implement when the real lever is twofactor. The difference is where the cost lands: implement pushes the cost onto every call, while twofactor pays once at the boundary and lets the fast path run unguarded. For the conclusion, the second shape wins because the check is amortized and the hot loop stays tight. Reaching for the first shape is the reflex; resisting it is the engineering.

Self-check: write a test that drives implement to the failing condition and assert the system degrades gracefully. Then how to implement two-factor auth with totp is a property you maintain, not a feature you hope for.

Sources: OAuth2 PKCE, JWT spec.

FAQ

Is implement worth the complexity?
It is worth it when implement is the bottleneck the user feels. Before that it is overhead. Measure, then decide, and remove it when the metric says it no longer earns its keep.
How do I test twofactor deterministically?
Use a fake clock for time-based logic, a stub for twofactor so failures are injected not waited for, and assert on the user-visible outcome. A test that passes by timing out is a hope, not a test.

Related Examples