Easy Two Factor Authentication (2FA) with Google Authenticator
With this API implementing two factor authentication (2FA) is easier than ever. Just in 5 minutes I’ll guide you how to generate and validate time-based one-time passwords (TOTP) for second factor authentication (2FA) in fast and secure manner.
1. First we download Google Authenticator app from App Store or Google Play.
I am using my iPhone SE, but of course Google Authenticator app is available for all iOS and Android devices:
2. OK, now we have Google Authenticator app installed, but we have no QR codes to assign it to because there is no account information for association with our app. So our next step would be to generate “secret” information and assign it to our account id. Subscribe to API and execute first /new/ endpoint. I will be using Postman to show how we run endpoints.
Create /new/ request in Postman and provide url and X-Rapidapi-Key (see details here https://rapidapi.com/chdan/api/google-authenticator/):
After successful execution of the /new/ endpoint you’ll see your new secret value:
3. Save this secret value, add “account” and “issuer” into our next /enroll/ endpoint. After successful execution of /enroll/ service you will have url link generated, so that your users could add this info to Google Authenticator app:
4. Now let’s open this url and scan the QR code:
Use “Scan a QR code” button in Google Authenticator:
5. Done! After we synced Google Authenticator app with your server’s secret, Google Authenticator starts generating time-based one-time passwords (TOTP):
6. Now we can validate one-time passwords (TOTP) on our end using /validate/ service:
“True” value indicates correct entry. After 60 seconds the same request would return “False” value.
So, how secure is generating “secret” in the cloud and not at our premises? Cloud developers know nothing about where and how you are using one-time passwords (TOTP) and also do not know the first factor. In addition TOTPs are by nature valid for a very short period of time (60 seconds). Generating “secret” in the cloud doesn’t bring you any specific risk, which you could have had avoided installing the software on premise. However, if you want to install packages locally feel free to use the following project: https://github.com/sonata-project/GoogleAuthenticator, which was basis for this API.
Why are one-time passwords (TOTP) valid even after TOTP disappeared in Google Authenticator app? Google Authenitcator shows one-time passwords for 30 seconds only and then it generates new TOTPs. We however assign 60 seconds validity of one-time codes on server side to give our users and systems additional 30 seconds to finish authentication process.