Playwright Automation Security
4 min read Testing

How to Automate Playwright MFA Logins Without Touching Your Phone Again

Every developer knows the frustration - your Playwright tests run perfectly until they hit an MFA prompt. You're stuck manually entering codes, breaking your CI/CD flow. Here's how to authenticate once with OTP and reuse secure sessions across all tests - just like a real user would.

The MFA Automation Problem Every Tester Faces

Picture this: Your Playwright test suite runs beautifully in CI/CD - until it hits that dreaded MFA prompt. Suddenly your automated pipeline requires manual intervention, defeating the purpose of automation. Teams resort to shared test accounts with MFA disabled (a security risk) or complex device forwarding setups (a maintenance nightmare).

The breakthrough came when we realized we were solving the wrong problem. Instead of trying to bypass MFA (which would compromise security), we needed to complete the MFA challenge once properly, then reuse that authenticated session - exactly how human users interact with systems daily.

Key insight: MFA isn't the enemy of automation - interrupting the flow for manual code entry is. The solution lies in authenticating once properly, then safely reusing that session state.

How Real Users Handle MFA (And Why Your Tests Should Too)

Humans don't solve MFA challenges repeatedly - they authenticate once per session. Your morning GitHub login with MFA lasts all day unless you manually log out. Playwright can mirror this behavior by persisting browser state after initial authentication.

The technical implementation involves three key components: generating valid OTP codes programmatically, completing the full login flow once, and saving the authenticated browser context for reuse. This maintains security while eliminating repetitive MFA prompts.

Enterprise impact: One financial services client reduced test execution time by 68% after implementing session reuse, while actually improving security by eliminating shared test accounts.

GitHub MFA Example - A Real-World Implementation

GitHub's TOTP-based MFA serves as an ideal example because it uses standard authentication protocols common across enterprise applications. The implementation requires the TOTP secret key (normally shared via QR code) to generate valid codes programmatically.

At 2:15 in the tutorial video, you'll see how to extract this secret during initial setup. Once obtained, libraries like speakeasy can generate time-based codes matching those from authenticator apps. This allows your tests to complete MFA challenges without manual intervention.

Secret Key Security - Storing TOTP Credentials Safely

The TOTP secret is as sensitive as a password - it can generate valid authentication codes. Never commit this value to source control or log it in test output. Instead, use environment variables injected via your CI/CD system or a secrets manager like HashiCorp Vault.

For teams, consider rotating these secrets periodically just like you would with service account passwords. The video shows how to configure dotenv for local development while keeping secrets out of version control.

Session Reuse Mechanics in Playwright

Playwright's browser contexts maintain separate session states. After authenticating, we save this context to disk using storageState(). Subsequent tests load this state before running, starting already authenticated. This persists cookies, local storage, and other artifacts that maintain the session.

The key advantage? Your test logic focuses on functionality rather than repetitive authentication. Setup tests handle login once, while all other tests assume an authenticated state - just like real user flows.

Running the Setup Test - Step-by-Step

The setup test follows a specific sequence: launch browser → navigate to login → enter credentials → generate OTP → complete MFA → save session state. Run this with npx playwright test --headed initially to verify the flow works.

Once validated, the setup can run headless in your CI pipeline. Store the resulting state file as a build artifact for downstream tests. The video demonstrates the complete flow from initial authentication to session reuse.

Parallel Execution Considerations

Parallel test execution requires special handling since multiple workers might try to refresh the same session simultaneously. Either configure your setup test to run with a single worker, or use separate test accounts for parallel pipelines.

For large test suites, consider running the setup once at pipeline start, then distributing the session file to all parallel nodes. This ensures consistent authentication across all test workers.

Security Implications - What's Actually Happening

This approach doesn't bypass or weaken MFA - it completes the full authentication challenge once, then reuses the resulting session. This matches real user behavior where you authenticate once per work session rather than for every action.

The session remains subject to the application's normal timeout policies. If the session expires, tests will need to reauthenticate - which you can handle by rerunning the setup test when detecting login redirects.

Watch the Full Tutorial

See the complete implementation in action, including how to extract the TOTP secret key (at 2:15) and configure session reuse across your test suite. The video demonstrates both the initial authentication flow and subsequent tests running with persisted sessions.

Playwright MFA automation tutorial showing OTP handling

Key Takeaways

MFA doesn't have to break your test automation. By treating your tests like real users - authenticating once per session rather than per action - you can maintain security while achieving true hands-off execution.

In summary: Extract the TOTP secret once, store it securely, authenticate properly in your setup test, then reuse that authenticated session across all subsequent tests. This eliminates MFA interruptions while keeping your systems secure.

Frequently Asked Questions

Common questions about Playwright MFA automation

MFA breaks automation because test pipelines can't pause for manual OTP entry. Playwright tests running in CI/CD environments can't access physical devices to retrieve codes.

The solution is to authenticate once with a valid OTP, then securely reuse the authenticated session across all subsequent tests. This maintains security while enabling uninterrupted test execution.

  • Manual code entry breaks CI/CD automation flows
  • Headless environments can't receive SMS or push notifications
  • Session reuse mirrors real user behavior more accurately

No security is compromised. The method completes the full MFA challenge once with a valid OTP, just like a human would. Playwright then saves the authenticated browser session state.

Future tests reuse this session without bypassing MFA. This mirrors real user behavior where you authenticate once per session rather than solving MFA repeatedly for every action.

  • Full MFA challenge completed during initial authentication
  • Session reuse follows application's normal timeout policies
  • Eliminates the need for shared test accounts with MFA disabled

This approach works with Time-based One-Time Password (TOTP) systems like Google Authenticator, Microsoft Authenticator, or Authy. These generate temporary codes from a shared secret key.

The method doesn't work with SMS-based OTP or push notification MFA systems that require device interaction. For those systems, you may need to explore alternative authentication methods or test-specific accounts.

  • Works with TOTP (authenticator app) MFA
  • Requires access to the TOTP secret key
  • Doesn't work with SMS or push notification MFA

The TOTP secret key should be stored in environment variables, not in code. Use a secrets manager like AWS Secrets Manager, HashiCorp Vault, or GitHub Secrets.

Never commit the key to version control or log it in test output. Rotate the key periodically as you would with any credential. The video shows how to use dotenv for local development while keeping secrets out of your repository.

  • Store in environment variables or secrets manager
  • Never commit to version control
  • Rotate periodically like any sensitive credential

Parallel execution requires special handling. Either run the setup test with a single worker or use multiple test accounts. Parallel tests using the same authenticated session may collide.

The setup project should run once before parallel test execution begins. Some teams generate separate session files per parallel node, each using different test accounts to avoid contention.

  • Run setup with single worker or multiple accounts
  • Session files can't be shared across parallel workers
  • Consider separate test accounts for each parallel node

Session duration depends on the application's security policies. Most web applications maintain sessions for several hours to days. You'll need to reauthenticate when the session expires.

Monitor for 401 errors or login redirects in your tests to know when reauthentication is required. Some teams schedule the setup test to run periodically to maintain fresh sessions.

  • Depends on application session timeout
  • Typically several hours to days
  • Watch for 401 errors or login redirects

TOTP codes are time-based and typically refresh every 30 seconds. The setup test generates a fresh code when authenticating. Once authenticated, session reuse doesn't require new OTPs until the session expires.

The temporary nature of OTP codes is why session reuse is essential for stable automation. Trying to generate new codes for every test would be unreliable and unnecessary.

  • OTP codes refresh every 30 seconds
  • Only needed during initial authentication
  • Session persistence eliminates need for repeated codes

GrowwStacks builds enterprise-grade test automation solutions that handle complex authentication flows including MFA. Our team can implement secure session reuse patterns across your Playwright test suite.

We integrate these solutions with your CI/CD pipeline and configure proper secret management. Our implementations have helped clients reduce test execution time by up to 68% while improving security.

  • Custom Playwright MFA automation implementations
  • CI/CD integration with your existing pipeline
  • Enterprise-grade secret management solutions

Stop Letting MFA Break Your Test Automation

Manual MFA handling costs your team hours each week and makes true CI/CD impossible. GrowwStacks can implement secure session reuse in your Playwright tests in as little as 2 days.