Explore your app. Build your testing knowledge.Explore your app.Meet State Explorer

Testing Logins Protected by TOTP: Automate Two-Factor Flows Without Weakening Them

How to automate logins that require a TOTP authenticator code: a dedicated test identity, code generation in the test, session reuse, and the shortcuts that quietly weaken your security.

Qate AI Team
8 min read
427 916427916

Two-factor authentication used to be something your security team asked for and your test suite ignored. That no longer works. More identity providers turn multi-factor authentication on by default, more customers require it in procurement questionnaires, and more of your own admin screens sit behind it. The first time a nightly run goes red because a login form now asks for a six-digit code, teams tend to reach for one of two shortcuts: switch MFA off for the test account, or add a bypass flag to the application build. Both make the tests pass. Both mean you are no longer testing what you ship.

This article is about the third option: automate the two-factor flow itself, the way a user experiences it, without putting secrets in places they do not belong.

What a TOTP code actually is

The codes an authenticator app shows are time-based one-time passwords, defined in RFC 6238. The app holds a shared secret that the server generated when you scanned the QR code. Every thirty seconds it combines that secret with the current time, runs the result through an HMAC, and shows six digits. The server does the same calculation and compares.

That is the whole trick: the authenticator app is a calculator. Anything that knows the secret and the time can produce the same code, including a test. Libraries exist for every language. In Node, otplib generates a code from a base32 secret in one call; in Python, pyotp does the same. There is nothing exotic about it, and nothing insecure, as long as the secret is handled like the password it effectively is.

The otplib README on GitHub: RFC 6238 compliance, the note that version 13 is a rewrite, and the Quick Start

Pattern 1: a dedicated test identity with its own secret

Start with an account that exists only for automated tests, enrolled in MFA exactly like a real user. When you enrol it, the provider shows a QR code and, almost always, a "can't scan? enter this key" fallback. That key is the base32 secret. Store it in the same secret store your pipeline already uses for API keys and database passwords: GitHub Actions secrets, Azure Key Vault, the Jenkins credentials plugin. Never in the repository, never in a ticket, never as a screenshot of the QR code.

In a Playwright test the login then looks like any other form fill, with one extra line. The example uses otplib 13, whose generate call is asynchronous and takes the secret as an option; if you are on otplib 12 the equivalent is authenticator.generate(secret).

import { test, expect } from '@playwright/test';
import { generate } from 'otplib';

test('signs in with a TOTP code', async ({ page }) => {
  await page.goto('/login');
  await page.getByLabel('Email').fill(process.env.TEST_USER_EMAIL!);
  await page.getByLabel('Password').fill(process.env.TEST_USER_PASSWORD!);
  await page.getByRole('button', { name: 'Continue' }).click();

  const code = await generate({ secret: process.env.TEST_USER_TOTP_SECRET! });
  await page.getByLabel('Verification code').fill(code);
  await page.getByRole('button', { name: 'Verify' }).click();

  await expect(page.getByRole('heading', { name: 'Dashboard' })).toBeVisible();
});

Two details matter in practice.

The first is timing. Generate the code immediately before you fill it in, not at the top of the test. A code is valid for its thirty-second window, usually plus one window of tolerance on the server side. A test that spends twenty seconds on earlier steps and then uses a code it computed at the start will fail intermittently, and you will spend an afternoon blaming the wrong thing.

The second is reuse. Most servers reject a code that has already been accepted, to stop replay. If two tests log in with the same identity inside the same thirty-second window, the second one fails. The fix is not a sleep. It is the next pattern.

Pattern 2: log in once, reuse the session

Playwright's authentication guide describes the setup project pattern: one "setup" test performs the full login, including the TOTP step, and saves the browser's cookies and local storage to a file. Every other test starts from that saved state and never sees the login form.

// auth.setup.ts
import { test as setup } from '@playwright/test';
import { generate } from 'otplib';

setup('authenticate', async ({ page }) => {
  // ... same login steps as above ...
  await page.context().storageState({ path: 'playwright/.auth/user.json' });
});

Playwright's authentication documentation describing the setup project and storageState pattern

This does three things at once. It makes the two-factor step run once per suite instead of once per test, which keeps you clear of the replay rule. It makes the suite faster. And it keeps the login journey itself under test, in that one setup test, so a regression in the MFA screen still fails the run.

Limits to know about: sessions expire, so a long run may need to re-authenticate; and some providers tie a session to a device fingerprint or limit concurrent sessions per user, so parallel workers may need their own identities, each with its own secret.

Pattern 3: use the identity provider's own test facilities

If your application signs in through Microsoft Entra ID, Okta, Auth0 or a similar provider, do not fight the provider. Create a test tenant or a test user group and express the exception there, scoped as narrowly as the provider allows. Microsoft's conditional access policies, for instance, can require MFA for everyone except a named group signing in from a named network, which lets a CI runner authenticate with password plus TOTP while nothing changes for real users.

The principle is the same as in the first two patterns: the test accounts go through a real, policy-governed login. What you avoid is an application-level switch that says "skip MFA when this header is present", because that switch ships to production with everything else.

The shortcuts that look harmless

A short list of things that are common and worth undoing:

  • MFA disabled on the test account. The login journey your customers use is now untested. The first broken deploy of the verification screen reaches them before it reaches you.
  • A bypass flag in the build. Even behind an environment check, it is code in production that disables a security control. Auditors notice; attackers look for it.
  • The real admin's authenticator secret, shared. A test identity costs nothing. A shared human secret turns every CI log into a credential leak waiting to happen.
  • Codes read from an email or SMS inbox. Possible, slow, flaky, and it makes your tests depend on a delivery system that is not under test. If the application offers TOTP, use TOTP.
  • A secret in a .env file committed "just for the test environment". Git history is forever. Rotate it and move it to the secret store.

Where a testing platform fits

Everything above you can build yourself, and if you already own a Playwright suite the setup project pattern is an hour's work. The place where tooling earns its keep is the other half of the problem: keeping the login journey itself tested across changes, on more than one surface, without every team re-implementing the secret handling.

Hosted platforms increasingly treat the verification step as a first-class part of a test rather than an obstacle. Qate, for example, stores the TOTP secret with the test account's credentials in the application's authentication roles, encrypted at rest, and computes the code at the verification step during the run, so a test created from a conversation includes the same two-factor screen a user sees, on web and on a Windows desktop application alike. Other platforms offer equivalent hooks. Whichever you use, apply the same questions you would to your own code: is the secret stored encrypted or in a vault, is the journey still exercised end to end, and does nothing in the application change to make it pass?

A short checklist

  1. One test identity per parallel worker, enrolled in MFA like a real user.
  2. The base32 secret lives in the pipeline's secret store, nowhere else.
  3. Generate the code right before filling it in.
  4. Log in once per run and reuse the session; keep that one login as a real test.
  5. Express exceptions in the identity provider's policies, never in application code.
  6. Rotate test secrets on the same schedule as other credentials.

Conclusion

Two-factor logins are not a reason to test less. The code an authenticator shows is a deterministic function of a secret and a clock, which means a test can produce it honestly, through the same screens your users see, with the secret guarded like any other credential. Do that once, in a setup step, and the rest of the suite never notices MFA exists, while the login journey stays covered. If the failures you do see afterwards are the login screen itself changing, treat them like any other CI failure worth classifying rather than a reason to retry.

Ready to put a two-factor login under test without weakening it? Start for free and create your first test from a conversation.

Put it into practice

Explore a better way to test.

Create tests by talking to an agent, investigate failures and keep your team moving with Qate AI.

Get started free