Automating gmail login [During oAuth] gets blocked

2019-03-04 17:16发布

问题:

This code works to login to gmail

public void login(User user) {
    WebDriverWait wait = new WebDriverWait(driver, 60);
    WebElement emailTextBox = wait.until(
            ExpectedConditions.visibilityOfElementLocated(By.id("identifierId")));
    emailTextBox.sendKeys(user.email);

    WebElement nextButton = wait.until(
            ExpectedConditions.visibilityOfElementLocated(By.xpath("//span[contains(text(), 'Next')]")));
    nextButton.click();

    WebElement passwordTextBox = wait.until(
            ExpectedConditions.visibilityOfElementLocated(By.xpath("//input[@type='password']")));
    passwordTextBox.sendKeys(user.password);

    nextButton = wait.until(
            ExpectedConditions.visibilityOfElementLocated(By.xpath("//span[contains(text(), 'Next')]")));
    nextButton.click();
}

Problem

We have a web application under test where users can login with google (oAuth2), however gmail traps automation script with a user verification (reset password or captcha or phone number).

Q:

Is there any way to avoid gmail user verification ?

(I am not asking to solve google verification challenge, in normal browser run by user manually this verification challenge doesn't get triggered (most of times), but with selenium it sometimes happens and fails my tests.)

Update 19.08.2018

This is a dead end, bypassing google verification is not trivial, upon searching more I found that service virtualization is the correct way to solve this issue, possibly Hoverfly.

回答1:

Using cookies solved my issue

public HomePage googleAutoLogin(String cookieKey, String cookieValue) {
    Calendar cal = Calendar.getInstance();
    Date today = cal.getTime();
    cal.add(Calendar.HOUR, 1);
    Date afterOneHour = cal.getTime();

    driver.manage().deleteAllCookies();

    Cookie cookie = new Cookie.Builder(cookieKey, cookieValue)
            .domain("qreflect.com")
            .path("/")
            .expiresOn(afterOneHour)
            .isHttpOnly(true)
            .build();

    driver.manage().addCookie(cookie);
    driver.navigate().refresh();
    logger.log(Level.INFO, "Finished adding cookie");

    return this;
}

you have to login manually once then inspect to get cookies related to you app session, store them somewhere and pass key, value to this method to get logged in.