Skip to content
TestLine Menu
TestLine
automation

2FA login in automated tests: how to handle it safely

Four ways to handle 2FA in E2E tests, an example of generating a TOTP code in Playwright, and rules so a shortcut for tests doesn't become a hole in production.

author
Artur Machowski, Senior QA Engineer
published
reading
6 min

Short answer

You handle two-factor login in automated tests in one of four ways: generate the TOTP code in the test from the test account’s secret, fetch the code from a captured email or SMS, log in once and save the session state for the other tests, or, carefully, use a shortcut that exists only in the test build. The best combination: 1-2 tests of the login itself with real 2FA (TOTP or a code from a message) and a saved session state for everything else. Keep secrets in CI, and test accounts exist only on the test environment.

Four ways

approachhow it workswhenrisk
TOTP code from a secretthe test computes the code from the account secret, like an authenticator app2FA through Google Authenticator and similarthe secret must be in CI secrets
code from email or SMSthe test fetches the code from Mailpit or a fake SMS gateway2FA by email or SMSneeds message capture on staging
saved session statelog in once per role, then cookies and token from a fileall tests except the login testthe session may expire during a long suite
shortcut in the test builde.g. a fixed code accepted only on stagingwhen no other approach worksdangerous if it can be enabled in production

Example: a TOTP code in Playwright

With the otpauth library, and the test account’s secret in an environment variable from CI secrets:

import { test, expect } from "@playwright/test";
import { TOTP } from "otpauth";

test("login with 2FA", async ({ page }) => {
  const totp = new TOTP({ secret: process.env.QA_TOTP_SECRET! });

  await page.goto("/login");
  await page.getByLabel("Email").fill(process.env.QA_USER!);
  await page.getByLabel("Password").fill(process.env.QA_PASSWORD!);
  await page.getByRole("button", { name: "Log in" }).click();

  await page.getByLabel("Code from app").fill(totp.generate());
  await page.getByRole("button", { name: "Confirm" }).click();

  await expect(page.getByRole("heading", { name: "Dashboard" })).toBeVisible();
  await page.context().storageState({ path: ".auth/user.json" });
});

The TOTP secret is the value the app shows when you enable 2FA, usually as a QR code. For a test account, save it once, when creating the account.

Saved session state for the other tests

In playwright.config.ts, set up a project that prepares the session and reuse it in the other tests:

projects: [
  { name: "setup", testMatch: /auth\.setup\.ts/ },
  {
    name: "e2e",
    dependencies: ["setup"],
    use: { storageState: ".auth/user.json" },
  },
],

The 2FA login runs once per run, not in every test. Add the .auth/ folder to .gitignore.

What not to do

  • don’t turn off 2FA for the whole environment: then the 2FA login isn’t tested at all;
  • don’t keep secrets and passwords in the repository: only in CI secrets;
  • don’t use test accounts in production with real data;
  • don’t add shortcuts controlled by a flag or variable that can be switched on in production;
  • don’t log in with 2FA in every test: it’s slow, and with SMS codes you may hit the provider’s limits.

Fetching codes from emails and SMS is covered in how to test emails and SMS in automated tests, and secrets in CI in Playwright tests in GitHub Actions and GitLab CI.

How I can help

As part of test automation I set up login in E2E tests, including with 2FA, with secrets in CI and a saved session state for each role. Describe how login works in your app in the contact form.

Frequently asked questions

How do you get through 2FA login in automated tests?

Ideally, generate the TOTP code in the test from the test account's secret, just as an authenticator app does. With codes sent by email or SMS, the test fetches the code from the tool capturing messages. Then it saves the session state so it doesn't log in in every test.

Should you turn off 2FA on the test environment?

For most tests you can log in with accounts without 2FA or with a saved session state, but the 2FA login itself must be tested on an account with 2FA enabled. Turning 2FA off for the whole environment means that path isn't tested at all.

Where should you store the test account's TOTP secret?

In CI secrets, like test passwords. The test account must exist only on the test environment and have no access to production data.

Is a fixed 2FA code on staging a good idea?

Only if it is technically impossible to enable in production, e.g. it doesn't exist in the production build. Shortcuts controlled by a flag or environment variable sometimes get switched on in production by accident and become a security hole.

How many times should the test suite log in with 2FA?

Once per role, in a setup step. All tests then reuse the saved session state (storageState in Playwright). The 2FA login itself is checked by 1-2 separate tests.

Got a release in a few weeks?

Describe your project in the form. I'll reply with questions about scope or an initial test plan.