</>

Technology

Scenario-Based

Difficulty

Advanced

Interview Question

How do you handle OTP or 2FA authentication in Selenium automation?

Answer

Handling OTP / 2FA in Selenium Automation

Two-Factor Authentication (2FA) and OTP are designed to require real-time human verification. Here are the professional approaches:

Approach 1 — Disable 2FA in Test Environment (Recommended)

Ask dev team to add a test bypass:

Java
// Test accounts have 2FA disabled in staging
// Or: test env config disables 2FA entirely
driver.get("https://staging.automateqa.online/login");
// Login normally — no OTP prompt appears

Approach 2 — TOTP Library (Google Authenticator Compatible)

For apps using Time-based OTP (TOTP), generate the OTP programmatically using the same seed:

XML
<!-- pom.xml -->
<dependency>
    <groupId>com.warrenstrange</groupId>
    <artifactId>googleauth</artifactId>
    <version>1.5.0</version>
</dependency>
Java
import com.warrenstrange.googleauth.GoogleAuthenticator;

public class OTPUtils {
    // Dev shares the test account's TOTP seed/secret key
    private static final String TEST_TOTP_SECRET = "JBSWY3DPEHPK3PXP";

    public static int generateOTP() {
        GoogleAuthenticator gAuth = new GoogleAuthenticator();
        return gAuth.getTotpPassword(TEST_TOTP_SECRET);
    }
}

// In test:
driver.findElement(By.id("username")).sendKeys("testuser@automateqa.online");
driver.findElement(By.id("password")).sendKeys("TestPass123");
driver.findElement(By.id("loginBtn")).click();

// OTP screen appears
int otp = OTPUtils.generateOTP();
driver.findElement(By.id("otpField")).sendKeys(String.valueOf(otp));
driver.findElement(By.id("verifyBtn")).click();

Approach 3 — Test Email API (Mailosaur / Mailhog)

For email-based OTP, read the OTP from a test inbox:

Java
// Use Mailosaur (test email service) to receive OTP email
MailosaurClient mailosaur = new MailosaurClient("YOUR_API_KEY");
Message email = mailosaur.messages().get("SERVER_ID",
    new SearchCriteria().withSentTo("testuser@abc.mailosaur.net"));

// Extract OTP from email body using regex
String otp = email.text().body().replaceAll(".*Your OTP is: (\\d{6}).*", "$1");
driver.findElement(By.id("otpField")).sendKeys(otp);

Approach 4 — SMS Mock / Test Phone Number

For SMS OTP:

  • Use Twilio test numbers or mock SMS gateway
  • Or ask dev team to accept a static test OTP (e.g., "000000") for test accounts

Approach 5 — Cookie/Session Injection (Skip Login Entirely)

Best when 2FA protects only the login step:

Java
// Step 1: Login via API (no UI, no 2FA in API test mode)
Response loginResponse = RestAssured.given()
    .header("X-Test-Mode", "true") // dev provides this header to bypass 2FA
    .body("{\"email\":\"test@automateqa.online\",\"password\":\"pass\"}")
    .post("/api/auth/login");

String sessionToken = loginResponse.getCookie("session");

// Step 2: Inject session into browser
driver.get("https://automateqa.online");
driver.manage().addCookie(new Cookie("session", sessionToken));
driver.navigate().refresh(); // authenticated, 2FA bypassed

Summary Table

2FA TypeApproach
Test env — any typeDisable 2FA via feature flag (ask dev)
TOTP / Google AuthTOTP library with shared secret key
Email OTPTest email API (Mailosaur, Mailhog)
SMS OTPTwilio test numbers / static test OTP
Session-basedAPI login + cookie injection

Follow AutomateQA

Related Topics