Twilio Authy – 2FA by SMS


Two-factor authentication also known as 2FA is a method in which user needs to pass through two authentication factor to access their account.

In this blog, we will see how to achieve 2FA using Authy in a grails application which is using spring security core.
What we are going to do —
1. First, authenticate a user by spring security core and then
2. Send him an SMS that contains a unique security code which he has to provide to access his account (via Authy).

In my previous blog (Twilio Authy Configuration in Grails/Gradle application), we have seen how to configure Twilio Authy in grails project. Now let’s see how to do 2FA (two-factor authentication) using Authy.

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 send him SMS.
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 — Send 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 send him a security code via SMS. Use com.authy.api.Users.requestSms() method to send the security code via SMS, 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. 🙂