/GoogleAuthenticatorClient

A sample to enable two factor authentication to an android app using Google Authenticator.

Primary LanguageKotlin

GoogleAuthenticatorClient

A sample to enable two factor authentication to an android app using Google Authenticator.

This project uses https://github.com/wstrange/GoogleAuth library.

Screenshots

Explanation

The following code creates a new set of credentials for a user. No user name is provided to the API and it is a responsibility of the caller to save it for later use during the authorisation phase.

GoogleAuthenticator gAuth = new GoogleAuthenticator();
final GoogleAuthenticatorKey key = gAuth.createCredentials();

The user should be given the value of the shared secret, returned by

key.getKey()

so that the new account can be configured into its token device. A convenience method is provided to easily encode the secret key and the account information into a QRcode.

When a user wishes to log in, he will provide the TOTP password generated by his device. By default, a TOTP password is a 6 digit integer that changes every 30 seconds. Both the password length and its validity can be changed. However, many token devices such as Google Authenticator use the default values specified by the TOTP standard and they do not allow for any customization.

The following code checks the validity of the specified password against the provided Base32-encoded secretKey:

GoogleAuthenticator gAuth = new GoogleAuthenticator();
boolean isCodeValid = gAuth.authorize(secretKey, password);

Since TOTP passwords are time-based, it is essential that the clock of both the server and the client are synchronised within the tolerance used by the library. The tolerance is set by default to a window of size 3 and can be overridden when configuring a GoogleAuthenticator instance.