Menu

Rate this page:

Thanks for rating this page!

We are always striving to improve our documentation quality, and your feedback is valuable to us. How could this documentation serve you better?

Two-Factor Authentication with Authy, Node.js and Express

Download the Code

This Express.js sample application demonstrates how to build a login system that uses two factors of authentication to log in users. Head to the application's README.md to see how to run the application locally.

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 first logging the user into the app, and then validating their mobile device.

For the second factor, we will validate that the user has their mobile phone by either:

  • Sending them a OneTouch push notification to their mobile Authy app
  • Sending them a token through their mobile Authy app
  • Sending them a one-time token in a text message sent with Authy via Twilio.

See how VMware uses Authy 2FA to secure their enterprise mobility management solution.

Click here to start the tutorial!

Configuring Authy

If you haven't done so 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 initializer file.

Loading Code Sample...
      
      
      
      
      config.js

      Now that we've configured our Express app, let's take a look at how we register a user with Authy.

      Register a user with Authy

      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 that user's email, phone number and country code. We need to make sure this information is required when the user signs 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.

      Loading Code Sample...
          
          
          
          
          models/User.js
          See how to log a user in with OneTouch

          Log in with Authy OneTouch

          When a user attempts to log in to our website, a second form of identification is needed. Let's take a look at Authy's OneTouch verification first.

          OneTouch works like so:

          • We attempt to send a User a OneTouch Approval Request
          • If the user has OneTouch enabled, we will get a success message back
          • The user hits 'Approve' in their Authy app
          • Authy makes a POST request to our app with an 'Approved' status
          • We log the user in
          Loading Code Sample...
              
              
              
              
              api/sessions.js

              Log in with Authy OneTouch

              api/sessions.js
              How to send a OneTouch request

              Send the OneTouch 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. These can be messages, logos, 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:

              details = {
                message: "Request to send money to Jarod's vault",
                from: "Jarod",
                amount: "1,000,000",
                currency: "Galleons"
              }
              
              Loading Code Sample...
                  
                  
                  
                  
                  models/User.js

                  Send the OneTouch request

                  models/User.js

                  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.authyStatus attribute. It's important we reset this before we log the user in.

                  See how to register a callback endpoint

                  Configure the OneTouch callback

                  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.

                  Loading Code Sample...
                      
                      
                      
                      
                      api/sessions.js

                      Here in our callback, we look up the user using the authy_id sent with the Authy POST request. At this point we would ideally 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 authyStatus on the user. Now all our client-side code needs to do is check for user.authyStatus.approved before logging in the user.

                      Handle authentication asynchronously

                      Handle Two-Factor Asyncronously

                      Our user interface for this example is a single page application written using Backbone and jQuery.

                      We've already taken a look at what's happening on the server side, so let's step in front of the cameras now and see how our JavaScript is interacting with those server endpoints.

                      First we hijack the login form submitted and pass the data to our /session controller using Ajax. Depending on how that endpoint responds we will either ask the user for a token or await their OneTouch response.

                      If we expect a OneTouch response, we will begin polling /authy/status until we see that the OneTouch login was either approved or denied. Take a look at this controller and see what is happening.

                      Loading Code Sample...
                          
                          
                          
                          
                          public/app/views/Login.js

                          Handle Two-Factor in the browser

                          public/app/views/Login.js
                          Fall back to token if OneTouch fails

                          Fall back to Authy Token

                          Here is the endpoint that our javascript is polling. It is waiting for the user status to be either 'Approved' or 'Denied'. If the user has approved the OneTouch request, we will save their session as confirmed, which officially logs them in.

                          If the request was denied we render the /verify page and ask the user to log in with a Token.

                          Loading Code Sample...
                              
                              
                              
                              
                              api/sessions.js

                              Now let's take a look at how we handle two-factor with tokens.

                              Send a one-time token

                              Sending a 2FA 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.

                              If needed, we can call this method on the user instance multiple times. This is what happens every time the user clicks "Resend Code" on the web form.

                              Loading Code Sample...
                                  
                                  
                                  
                                  
                                  models/User.js
                                  How to validate the code

                                  Validate the Code

                                  Our Express route handler will grab the code submitted on the form in order to validate it. The connect middleware function executes before this handler and adds a user property to the request object that contains a Mongoose model instance representing the user associated with this session. We use verifyAuthyToken on the User model to check if the code submitted by the user is legit.

                                  Loading Code Sample...
                                      
                                      
                                      
                                      
                                      api/sessions.js

                                      That's it! We've just implemented two-factor authentication using three different methods and the latest in Authy technology.

                                      What's next?

                                      Where to next?

                                      If you're a Node.js developer working with Twilio, you might want to check out these other tutorials.

                                      Account Verification

                                      Increase the security of your login system by verifying a user's mobile phone.

                                      Server Notifications via SMS

                                      Faster than e-mail and less likely to get blocked, text messages are great for timed alerts and notifications. Learn how to send out SMS (and MMS) notifications to a list of server administrators.

                                      Did this help?

                                      Thanks for checking out this tutorial! If you have any feedback to share with us, we'd love to hear it. Connect with us on Twitter and let us know what you build!

                                      Jarod Reyes Jose Oliveros Agustin Camino Andrew Baker Kat King

                                      Need some help?

                                      We all do sometimes; code is hard. Get help now from our support team, or lean on the wisdom of the crowd browsing the Twilio tag on Stack Overflow.

                                      Loading Code Sample...