How to test TOTP / authenticator 2FA in E2E tests

Last updated 2026-12-03 · By the Humanless team at Ninety Nine Oranges · Markdown version

Short answer: TOTP codes are computed, not delivered. If your test knows the shared secret, it can generate the current code itself: RFC 6238, which for almost every app means HMAC-SHA1, a 30-second step and 6 digits. Capture the secret when you enroll the test user (from the "can't scan? enter this key" text or the secret= parameter of the otpauth:// URI in the QR code), store it with the test user, and generate a code with a library such as otplib (Node) or pyotp (Python) whenever the app asks. The two things that break these tests are the 30-second boundary and servers rejecting a code that was already used.

Use policy: Use these techniques on test accounts in applications you own or are authorized to test. See the Terms.

How TOTP works, in one paragraph

At enrollment, your app generates a random secret (usually base32), shows it as a QR code containing an otpauth://totp/Issuer:user?secret=... URI, and asks for one code to confirm. Afterwards, the server and the authenticator both compute HOTP(secret, floor(unix_time / 30)) and compare. There is no message to wait for, so you don't need an inbox. You only need the secret and an accurate clock.

Capture the secret during enrollment

Most enrollment screens show the secret as text next to the QR code. Read it from the page. If you only have the QR code's URI (for example in a data- attribute or your API response), parse it:

enroll-2fa.spec.ts
import { expect, test } from "@playwright/test";
import { generate } from "otplib"; // otplib v13: async API

test("enroll and log in with an authenticator app", async ({ page }) => {
  await page.goto("http://localhost:3000/settings/security");
  await page.getByRole("button", { name: "Set up authenticator app" }).click();
  await page.getByRole("button", { name: "Can't scan the code?" }).click();

  const secret = (await page.getByTestId("totp-secret").innerText()).replace(/\s+/g, "");
  // or from a URI: new URL(otpauthUri).searchParams.get("secret")

  await page.getByLabel("Authentication code").fill(await generate({ secret }));
  await page.getByRole("button", { name: "Verify" }).click();
  await expect(page.getByText("Two-factor authentication is on")).toBeVisible();
});

In Python, pyotp.TOTP(secret).now() does the same. For long-lived test accounts, store the secret in your CI secrets next to the account's password and generate a code at each login.

Or seed it

If your app's test fixtures or admin API can create a user with 2FA already enabled, generate a secret in the fixture and write it directly. That's faster and doesn't drive the enrollment UI in every test. Keep one test that goes through the real enrollment screen.

Option 2: The Humanless TOTP channel

Humanless can also hold the secret and give you the current code over REST or MCP. That's useful when the thing doing the login can't run a TOTP library, for example an AI agent in Claude or Cursor, or when you want the secret to live and expire with a disposable test identity instead of in your CI config.

There's one constraint: Humanless generates the secret. It returns totp_secret (32 base32 characters, SHA1, 6 digits, 30 seconds) when you create an identity with the totp channel. It doesn't currently import a secret that your app generated. So this fits apps where the test account can be enrolled with a known secret: a test fixture, a seed script or an admin API that sets it, or an enrollment flow that accepts a user-supplied key. If your app always generates the secret itself, use Option 1.

seeded-2fa.spec.ts
import { expect, test } from "@playwright/test";
import { Humanless, withIdentity } from "./humanless"; // TypeScript SDK, one file: usehumanless.com/sdk/humanless.ts

const hl = new Humanless({ apiKey: process.env.HUMANLESS_API_KEY! });

test("log in with TOTP 2FA", async ({ page }) => {
  await withIdentity(hl, { channels: ["email", "totp"] }, async ({ identity_id, email, totp_secret }) => {
    await createTestUser({ email: email!, password: "correct-horse", totpSecret: totp_secret! }); // your fixture

    await page.goto("http://localhost:3000/login");
    await page.getByLabel("Email").fill(email!);
    await page.getByLabel("Password").fill("correct-horse");
    await page.getByRole("button", { name: "Log in" }).click();

    let t = await hl.getTotp(identity_id); // { code: "159026", seconds_remaining: 14 }
    if (t.seconds_remaining <= 3) {
      await page.waitForTimeout(t.seconds_remaining * 1000 + 500); // wait for the next window
      t = await hl.getTotp(identity_id);
    }
    await page.getByLabel("Authentication code").fill(t.code);
    await page.getByRole("button", { name: "Verify" }).click();
    await expect(page.getByRole("heading", { name: "Dashboard" })).toBeVisible();
  });
});

Over REST it's GET /v1/identities/:id/totp, which returns { "code": "159026", "seconds_remaining": 14 }. For agents it's the get_totp_code MCP tool. Identities expire (default 1 hour, maximum 24 hours via ttl_seconds), so for permanent test accounts, a stored secret and Option 1 are the better fit.

Pitfalls

FAQ

How do I automate Google Authenticator 2FA in Playwright?

Get the TOTP secret at enrollment (the text key or the secret in the otpauth:// URI), then generate the current code in the test with otplib (await generate({ secret })) and fill it. Google Authenticator itself isn't involved. It runs the same RFC 6238 algorithm.

Where do I get the TOTP secret for a test account?

From the enrollment screen's "enter this key manually" text, from the QR code's otpauth:// URI, or by seeding the test user with a secret you chose. Store it as a CI secret, the same way you store the password.

Why is my generated TOTP code rejected?

Usually the code rolled over between generating and submitting it, the same code was already used (replay protection), the secret still has spaces in it, or the app uses non-default parameters (SHA256, 8 digits, a 60-second period).

Can an AI agent pass TOTP 2FA?

Yes, on your own app. Give it a tool that returns the current code. Humanless's get_totp_code MCP tool returns { code, seconds_remaining } for an identity created with the totp channel. Or expose a small function that runs otplib on a secret the agent never sees.

Do I need a paid plan for TOTP on Humanless?

No. TOTP is included in the Free plan, along with email codes and magic links.

Humanless: disposable inboxes, dedicated US SMS numbers and TOTP for testing apps you own. Email and TOTP are free.

Get an API key