Skip to content

Development OTP login

Fernando Pastor edited this page Jan 28, 2025 · 1 revision

OTP login

An OTP (One-Time Password) two-factor login is a security mechanism that enhances account protection.

After including your username and password, some applications require a one-time code (OTP) generated or sent to your device. The OTP is typically delivered via SMS, email, or a dedicated authentication app (like Google Authenticator). It is valid for a short time and must be entered after the primary password, adding an extra layer of security against unauthorized access.

TESTAR implements two possible features to perform an OTP login with 6 numerical digits.

TOTPGenerator

The org.testar.otp.TOTPGenerator feature allows TESTAR to generate a TOTP key every 30 seconds. To use this feature, the secret key of the TOTP mechanism is necessary. Typically, the Google or Microsoft mobile authenticators generate a QR image based on this secret key. In TESTAR, the alphanumerical key values are necessary.

The user can, for example, save this secret key into an environment variable to be used by TESTAR without requiring to be harcoded:

TOTPGenerator totpGenerator = new TOTPGenerator(System.getenv("TOTP_SECRET_KEY").toCharArray());
String otp = totpGenerator.generateTOTP();

ImapGmailReader

The org.testar.otp.ImapGmailReader feature allows TESTAR to connect to a Gmail account to read the last emails in the inbox. In Gmail, it is necessary to enable the Sign in with app passwords feature. An app password is a 16-digit passcode that can be used with TESTAR to read the email's information.

Then, the users can specify the last 'seconds' interval from which they expect to have received the OTP email and the regex pattern of the OTP code (typically 6 numerical digits).

Example with coded email and passcode saved in the environment variables:

ImapGmailReader realImapGmailReader = new ImapGmailReader("email@gmail.com", System.getenv("GMAIL_PASSCODE").toCharArray());
String otp = realImapGmailReader.readOtpNumber(60, "\\d{6}");

Example with coded email and passcode:

ImapGmailReader realImapGmailReader = new ImapGmailReader("email@gmail.com", "xxxx yyyy zzzz tttt".toCharArray());
String otp = realImapGmailReader.readOtpNumber(60, "\\d{6}");

Clone this wiki locally