Twilio Authy – 2FA by Phone Call

Hi, welcome back. 🙂

This blog is a part of a blog series on Authy. I suggest you go through previous blogs of the series.

* Authy Two Factor Authentication in Grails with spring security core Part-1 (Configuration)

* Authy Two Factor Authentication in Grails with spring security core Part-2 (2FA by SMS)

In this blog, we are going to see, how to do 2FA (two-factor authentication) verification of the user by a phone call.

Step1 — Configurations

Do all configurations mentioned in my previous blog.

Step2 — Register a user

While registering a user on your application, register the user on Authy as well so that Authy can call the user on his phone.
Use com.authy.api.Users.createUser() method to register the user on Authy. This method takes 3 arguments, phone number, country code and email address.

AuthyApiClient authyClient = new AuthyApiClient("YOUR_API_KEY")
User authyUser = authyClient.getUsers().createUser(email, phoneNumber, countryCode)

Check whether the user is created successfully on Authy using authyUser.isOk() method or not.
If authyUser.isOk() returns true then the user is successfully created. Use authyUser.getId() to get Authy user id and save it in your local database (you will need this to send and verify security code).
If authyUser.isOk() returns false then something goes wrong on Authy. You can get the error using user.getError().

Step3 — Request to make a phone call for security code

Now you have successfully registered the user on your site and Authy. Now, whenever the user tries to login into the application, first ask him for his email address and password as usual. And if he successfully validated by spring security then request Authy to call the user on his registered phone number and provide the security code. Use com.authy.api.Users.requestCall() method for this, which takes Authy user id as an argument.

AuthyApiClient authyClient = new AuthyApiClient("YOUR_API_KEY")

Step4 — Verify security code

Now the user has got the security code. Navigate him a screen where he can enter that security code. Once user provided the security code validate that code using com.authy.api.Tokens.verify() method, which takes Authy user id and provided security code as arguments.

AuthyApiClient authyClient = new AuthyApiClient("YOUR_API_KEY")
Token token = authyClient.getTokens().verify(user.authyUserId, securityCode)

Now use token.isOk() method to check whether the code is valid or not. If valid then allow the user to access your site otherwise ask him to enter the correct security code.

That’s it.

I have created a sample application AuthyDemo using this. I have also deployed (demo application) the same on Heroku as well. Have a look and if you have any issue or question, let us know. 🙂