Hello Everyone, in this post will learn about how to automate two-factor authentication with Google authenticator using selenium.
What is two-factor authentication?
In security domain, there are generally three recognized types of authentication factors.
- Type 1 : Something you know (such as passwords, PIN)
- Type 2 : Something you have (such as tokens, keys, smart phones)
- Type 3 : Something you are (such as fingerprints, face ID)
In simple terms, Two-factor authentication, also commonly referred to as 2FA, means using any two of the above mentioned options together in the authentication process of an application.
Most commonly used 2FA methods are Type 1 and Type 2. For instance, using passwords and verification codes.
Two-factor authentication (2FA) is used to add an extra security layer to the system so that they are less prone to vulnerabilities.
What is Google Authenticator?
Google authenticator is a security application by Google used to generate Time-based One-time passwords (TOTP) to authenticate users to access the application.
Google Authenticator generates 2-Step verification codes on your phone.
What is two-step verification in Gmail?
2-Step verification (also known as two-factor authentication) provides stronger security for your Google Account.
After you set it up, you’ll sign in to your account in two steps using,
- Something you know
- Something you have
In our case, two-factor authentication (2FA) will be based on password and Google authenticator’s TOTP verification codes on your phone to authenticate your Google Account.
Pre-requisite :
- Valid Google Account (If you don’t have, please create one to proceed further)
This article is divided into three sections.
- Enable two-step verification in Gmail
- Google Authenticator App Setup
- Automate two-factor authentication (2FA) using Selenium
Enable two-step verification in Gmail Account
Step 1: Navigate to your google security settings https://myaccount.google.com/security
Step 2 : Click Security Tab
Step 3 : Click on 2-step Verification
Step 4 : Click Get Started
Step 5 : Enter your password and click Next
Step 6 : In the next screen, enter the following
- Select Country
- Enter Phone Number
- Select Radio button of your choice to get code
- Click Next
Step 7 : Enter the security code sent to your phone number and click Next
Step 8 : Device has been verified. Click Turn On to complete the 2-step verification setup process.
Two- Step verification method has been turned on and the phone number has been verified!!
Google Authenticator App Setup
Step 9 : Scroll down and Click Google Authenticator – Set Up
Step 10 : Choose your platform and click Next
Step 11 : Click Can’t scan it option to grab your security Key and Click Next
Step 12 : Copy the Security Key (Save this key we need it in later steps)
Note: Before clicking Next, Install Google Authenticator App on your device and enter the copied security key to connect with your gmail account.
Step 13 : Click Next
Step 14 : Enter the TOTP verification code generated in Authenticator App and Click Verify
So going forward, Gmail sign in will prompt for password and verification code.
Google Authenticator App has been setup successfully!!
Automate Two-factor authentication (2FA) using Selenium
If your test application is enabled with google’s two-factor authentication, you should get the time-based verification code (TOTP) from authenticator mobile app and sign in to your account every single time.
But, in an end-to-end testing, how can the test script grab the verification code without accessing the mobile application?
Answer is simple!!
You can implement the program that computes the Authenticator code inside your test script easily.
Step 1 : Navigate to https://mvnrepository.com/artifact/org.jboss.aerogear/aerogear-otp-java/1.0.0
Note: Example used in this article is written in JAVA-Gradle project!
Step 2 : Copy the external library code based on your project and paste it in your build file.
// https://mvnrepository.com/artifact/org.jboss.aerogear/aerogear-otp-java
compile group: 'org.jboss.aerogear', name: 'aerogear-otp-java', version: '1.0.0'
Step 2 : Create TOTPGenerator.java class and paste the below code
import org.jboss.aerogear.security.otp.Totp;
public class TOTPGenerator {
/**
* Method is used to get the TOTP based on the security token
* @return
*/
public static String getTwoFactorCode(){
//Replace with your security key copied from step 12
Totp totp = new Totp("nlyyriaxspwdomi7buvo32cuas6tz7aa"); // 2FA secret key
String twoFactorCode = totp.now(); //Generated 2FA code here
return twoFactorCode;
}
}
Sample Selenium Code that uses the generated 2FA code in test script,
import org.junit.Test;
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.chrome.ChromeDriver;
public class TwoFactorGmail {
public static void gmailSignIn(){
System.setProperty("webdriver.chrome.driver", "path of the exe file\\chromedriver.exe");
WebDriver driver = new ChromeDriver();
driver.manage().window().maximize();
driver.get("your application url which embeds gmail sign-in");
driver.findElement(By.id("identifierId")).sendKeys("letzdotesting@gmail.com");
driver.findElement(By.id("identifierNext")).click();
driver.findElement(By.name("password")).sendKeys("password");
driver.findElement(By.id("passwordNext")).click();
// OTP value is returned from getTwoFactor method
driver.findElement(By.id("totpPin")).sendKeys(TOTPGenerator.getTwoFactorCode());
driver.findElement(By.id("totpNext")).click();
}
}
Two-factor authentication with Google Authenticator using Selenium is done successfully!!
Please comment below if you have any questions or concerns.
Suggested Readings :
Top 40 Selenium Webdriver Interview Questions & Answers
2FA Authentication using Playwright
Know anyone who is learning Selenium? Help your friends by sharing this article on Facebook, Twitter, or Google Plus.
is there any API which reads OTP from OKTA
Hello Baskar,
Sorry, I’m not aware of any API which reads OTP from OKTA!
Code is not working for me. Please suggest me alternative thing it’s emergency. Import file aerogear is not there in my imports list how can i approach that.
Hello Kalyani,What kind of build management tool are you using. Try rebuilding the project if you don’t find dependencies. Please elaborate on your issue to understand further. Thanks!
Its not working for me showing illegal exception in this line:
driver.findElement(By.xpath(“//*[@id=\”center-v-and-h\”]/form/div/div/div[1]/input”)).sendKeys(TOTPGenerator.getTwoFactorCode());
Iam eclipse for selenium, in imports list areogear not showing
If you’re not using any build management tool as part of your framework, please use this link https://jar-download.com/artifacts/org.jboss.aerogear/aerogear-otp-java/1.0.0/source-code to download jar files manually
Hi Shobika,
I have implemented into my code, but still it is expecting to get the OTP from Google Authenticator App and enter the OTP while login.
Appreciated your help here.
Thanks,
Arup
Hello Arup,
Totp totp = new Totp(“Your 2F Authentication”); This line of code should have your 2F Authentication Key.
Hello, thank you for this excellent post. However, when trying to log, it appears that the connection is not secure, any suggestions to fix this problem?
Hello,
Try turning ‘Allow less secure apps’ option off in your gmail account.
Hi Shobika,
In TOTPGenerator.java , you mentioned about 2FA secret key. Can you tell me how II can get tis 2FA secret key?
Hello Madhu,
I have also provided steps to get the 2F Authentication key. Please refer Enable two factor authentication section step 1-12.
Hello,
Thank you for picking this topic..I tried and it works on my local machine however when I try to run through Jenkins I’m unable to succeed. Anyone in a similar situation?
I would appreciate your help in this.
I tried to automate 2FA successfully on my local machine but when I run the same on VM Linux machine through Jenkins it’s failing.. Any lead here?
Which step is failing?
It’s asking for Captcha.. I would appreciate your help
Hi Shobika,
Since I tried multiple times now google thinks it’s selenium and asks to enter the captcha.
Hi , i am trying to run the code but i am getting below error.
Exception in thread “main” java.lang.NoClassDefFoundError: org/jboss/aerogear/security/otp/Totp
at OTPGenerator.getTwoFactorCode(OTPGenerator.java:16)
at OTPGenerator.main(OTPGenerator.java:10)
Caused by: java.lang.ClassNotFoundException: org.jboss.aerogear.security.otp.Totp
at java.base/jdk.internal.loader.BuiltinClassLoader.loadClass(BuiltinClassLoader.java:606)
at java.base/jdk.internal.loader.ClassLoaders$AppClassLoader.loadClass(ClassLoaders.java:168)
at java.base/java.lang.ClassLoader.loadClass(ClassLoader.java:522)
… 2 more
Thanks a lot. it worked.
Hello, thank you for this thread, very useful.
One question, we have some corner test scenarios that aim to cover MFA change(move from OTP to Google Auth and vice versa). In these scenarios, storing the initial secret key is not enough, as with a new registration, a new key will be generated. So automating this can become a challenge. I’d be curious what your view is on the matter.
Thanks in advance
Thank you for the article it was vital , But only once i did get the otp then after it just prints totGoogle in console . I am not getting otp now
please do resolve
Can you please tell how to get the security code. In below line where is step 12 that can give us the security key.
Please help.
####
//Replace with your security key copied from step 12
Totp totp = new Totp(“nlyyriaxspwdomi7buvo32cuas6tz7aa”); // 2FA secret key
###
To run the automatoin on different systems, do we need to provide security key again & again?
Hello, I tried to implement the code but it is failing when it is pasting totp and says “wrong code” after pressed next button
nlyyriaxspwdomi7buvo32cuas6tz7aa how to take key