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 + Javaimport 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);