πŸ’‘ If you like this website, please share it with your friends and network! πŸš€
Back to All Scenarios
Scenario 76 of 100
Authentication
Advanced

Handling MFA & OTP Authentication in Automation

πŸ”‘Scenario Overview

Handling MFA & OTP Authentication in Automation

Key Takeaways & Cheat Sheet

  • βœ“Bypass login screens entirely in testing environments using mock flags
  • βœ“Extract MFA verification codes using secure backend API database checks
  • βœ“Integrate TOTP libraries (like Google Authenticator java library) inside the test code
  • βœ“Maintain session cookies in your driver to avoid MFA screens completely

Short Direct Answer

SMS/Email OTP is highly brittle to automate. The best strategies are: ask development to disable MFA in QA/Testing environments, query the database or an internal API directly to retrieve the code, use a virtual OTP generator library (like standard Google TOTP libraries) if you have the secret key, or save and reuse session cookies to bypass login entirely.

⚠️ Senior Warning (Red Flag)

Never attempt to automate OTP delivery over SMS or email using physical mobile or browser loops. It introduces massive network delay and dependency on third-party carriers.

πŸ’‘ STAR Deep Dive Explanation & Pro Tip

Generating 2FA codes programmatically using secret keys is highly reliable and avoids the latency and flakiness of waiting for SMS or email deliveries.

SeleniumAutomation.java
Selenium 4 + Java
import com.warrenstrange.googleauth.GoogleAuthenticator;

// βœ… Solution: Generate TOTP code programmatically using the 2FA secret key
public String getTwoFactorCode(String secretKey) {
    GoogleAuthenticator gAuth = new GoogleAuthenticator();
    int code = gAuth.getTotpOneTimePassword(secretKey);
    return String.format("%06d", code); // Format as 6-digit string
}

// Usage in login flow:
// String otp = getTwoFactorCode("JBSWY3DPEHPK3PXP");
// driver.findElement(By.id("otp-input")).sendKeys(otp);