How can I automate two-factor authentication using Selenium Python?

In this article, I’m going to explain how to sign in a web site that protected with Two-factor authentication in End to End Testing usingĀ Selenium online training.

A type of Two-factor authentication

This article handle Two-factor authentication of type that getting OTP (One Time Passwaord) using “Authenticator” mobile app, such as “Google Authenticator”, or “Microsoft Authenticator” or etc.

screen shot of GoogleAuthenticator mobile app

Two-factor authentication of type that sends authentication code by SMS or e-mail is not handled in this article.

Is it hard to sign in to 2FA site in End-to-End testing?

When sign in a web site that protected with Two-factor authentication, you should get “Authenticator code” (a.k.a “OTP”) from an Authenticator mobile app in your own mobile device, and enter it to the sign in form.

But, in an End to End testing, how can the test program get “Authenticator code” without accessing to an Authenticator mobile app?

Is there no way except disabling Two-factor authentication feature of an account for testing?

The idea is simple!

Don’t worry, your test code can do it.

You can implement the program that computes the Authenticator code inside test program, easily.

It’s like putting an “authenticator” mobile app in the test program.

How to compute 2FA code?

I wrote two sample codes. One is C # and the other is Java.

In C#, you can compute 2FA code with the library “otp.net -&nbspThis website is for sale! -&nbspotp Resources and Information.“.

using OtpNet;

var otpKeyStr = “6jm7n6xwitpjooh7ihewyyzeux7aqmw2”; // <- this 2FA secret key.

var otpKeyBytes = Base32Encoding.ToBytes(otpKeyStr);

var totp = new Totp(otpKeyBytes);

var twoFactorCode = totp.ComputeTotp(); // <- got 2FA coed at this time!

In Java, you can compute 2FA code with the library “aerogear-otp-java”.

import org.jboss.aerogear.security.otp.Totp;

String otpKeyStr = “6jm7n6xwitpjooh7ihewyyzeux7aqmw2”; // <- this 2FA secret key.

Totp totp = new Totp(otpKeyStr);

String twoFactorCode = totp.now(); // <- got 2FA coed at this time!

I am grateful to the contributors of those libraries.

Full set of sample code by C#

You can get a full set of C# sample code from the following GitHub repository.

sample-by-jsakamoto/Selenium-E2ETest-for-OTP2FAAuth

movie

This repository also include the sample web site app for test target.

The sample web site app is also provided as a Docker image in following repository.

Docker Hub

Conclusion

There is no need to be afraid ofĀ Selenium online training IndiaĀ End-to-End testing of 2FA website.

You can easily implement the test program that getting 2FA code inside itself with very usefull libraris.