Two Factor Authentication (2FA) helps keep you user accounts secure by validating two "factors" of identity. Most login systems only validate something your user knows, like a password. You can make it harder for evildoers to compromise a user account by also validating something a user has, like a mobile phone.
In this tutorial, we will show you how to validate both of these factors in a simple token-based login system. To make everything a bit simpler, we'll also be using Twilio-powered Authy. Authy helps handle all the moving parts associated with 2FA, including sending one-time passwords via text message to your users. Scroll down this page to get started!
Learn to implement two-factor authentication (2FA) in your web app with Twilio-powered Authy. 2FA helps further secure your users' data by validating more than just a password. This tutorial will show you the code to make it happen.Start Tutorial
This PHPLaravel sample application is an example of typical login flow. To run this sample app yourself, download the code and follow the instructions on GitHub.
Adding two-factor authentication (2FA) to your web application increases the security of your user's data. Multi-factor authentication determines the identity of a user by validating once by logging into the app, and second by validating their mobile device.
For the second factor, we will validate that the user has their mobile phone by either:
Let's get started! Click the right arrow above to move to the next step of the tutorial.
If you haven't already, now is the time to sign up for Authy. Create your first application, naming it whatever you wish. After you create your application, your "production" API key will be visible on your dashboard:
Once we have an Authy API key, we store it in this .env file.
Now that we've configured our Rails app, let's take a look at how we register a user with Authy.
When a new User is created we also register the User with Authy.
All Authy needs to get a user set up for your application is the email, phone number and country code. In order to do two-factor authentication, we need to make sure we ask for these things at the point of sign up.
Once we register the User with Authy we get an
id back that we will
store as the user's
authyId. This is very important since it's how we
will verify the identity of our User with Authy.
When a User attempts to log in to our website, we will ask them for a second form of identification. Let's take a look at Authy's OneTouch verification first.
OneTouch works like so:
In the next steps we'll look at how we handle cases where the User does not have OneTouch, or denies the login request.
When our User logs in we immediately attempt to verify their identity with OneTouch. We will fallback gracefully if they don't have a OneTouch device, but we don't know until we try.
Authy lets us pass details with our OneTouch request, including a message,
a logo and any other details we want to send. We could easily send any
number of details by appending
details['some_detail']. You could imagine a
scenario where we send a OneTouch request to approve a money transfer:
$params = array( 'message' => "Request to send money to Jarod's vault", 'details[From]' => "Jarod", 'details[Amount]' => "1,000,000", 'details[Currency]' => "Galleons", )
Note: We need some way to check the status of the user's two-factor process, in this case we do so by updating the
$user->authy_status attribute. It's important we reset this before we log the user in.
In order for our app to know what the User did after we sent the OneTouch request, we need to register a callback endpoint with Authy.
Here in our callback, we look up the user using the
authy_id sent with the Authy POST request. Ideally at this point we would probably use a websocket to let our client know that we received a response from Authy. However for this version we're going to keep it simple and just update the
authy_status on the User. Then all our client-side code needs to do is check for the user status as 'Approved' before logging her in.
Let's take a look at the client-side code that will be handling this.
In order for two-factor authentication to be seamless, it is best done asynchronously so that the user doesn't even know it's happening.
First we hijack the login form submit and pass the data to our
controller using Ajax. Depending on how that endpoint responds we will
either ask the User for token or await their OneTouch response.
If we expect a OneTouch response, we will begin polling
we either see OneTouch login was either approved or denied. Let's take a
look at this controller and see what is happening.
user status to be either 'Approved' or 'Denied'. If the User has approved
the OneTouch request, will log them in using Laravel's built in
If the request was denied we will ask the User to log in with a Token.
Once there is an Authy user ID associated with our user model, we can request that an SMS verification token be sent out to the user's phone. Authy supports token validation in their mobile app as well, so if our user has the app it will default to sending a push notification instead of an SMS.
We can call this method on the user instance multiple times if needed, which is what happens every time the user clicks "Resend Code" on the web form we are about to look at!
Back in our controller, we grab the 2nd-factor token that was submitted by the user. Before we decide what to do with this token we check to see if the User is part of a validated
Session. Once we get the all clear we then check that token by calling
verifyToken() on the User model.
This is a great opportunity to dive-in to the verifyToken() function.
Authy makes it very simple for us to validate the code our user submitted. All we need to do is check with Authy that the code they sent was the same code they entered in our form. To do this our User model simply passes it's
authy_id and the
$token to Authy.
And voilah, we have a User who is valid over two-factors of authentication.
That's it! We've just implemented two-factor auth using three different methods and the latest in Authy technology.
If you're a PHP developer working with Twilio, you might want to check out these other tutorials.
Measure the effectiveness of different marketing campaigns with unique phone numbers.
Faster than e-mail and less likely to get blocked, text messages are great for timely alerts and notifications. Learn how to send out SMS (and MMS) notifications to a list of server administrators.
Thanks for checking out this tutorial! If you have any feedback to share with us, we'd love to hear it. Tweet @twilio to let us know what you think.