Menu

Expand
Rate this page:

Two-Factor Authentication with Authy, Ruby, and Rails

For new development, we encourage you to use the Verify API instead of the Authy API. The Verify API is an evolution of the Authy API with continued support for SMS, voice, and email one-time passcodes, an improved developer experience, and new features including:

  • Twilio helper libraries in JavaScript, Java, C#, Python, Ruby, PHP, and Go.
  • Access via the Twilio CLI.
  • Improved visibility and insights.
  • A push authentication SDK embeddable in your own application.

You are currently viewing the Authy API. New features and development will be added only to the Verify API. Check out the FAQ for more information and the migrating to Verify guide to get started.

This Ruby on Rails sample application is an example of a 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 users’ data. Multi-factor authentication validates the identity of a user with a two-stage process: first, that they can log into the app, and second that they their mobile device in their possession. This second phase is performed by:

  • Sending them a OneTouch push notification to the Authy app, or
  • Sending them aone-time token via the Authy app, or
  • 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.

Let’s get started!

Configuring Authy

If you haven’t already signed up for Authy, now is the time to to do so. 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 you have an Authy API key, register it as a environment variable.

        
        
        
        config/initializers/authy.rb

        Register Authy as 2FA provider

        config/initializers/authy.rb

        Let’s take a look at how you register a user with Authy.

        Register a user using Authy

        Register a user with Authy

        When a new user signs up for our website, we will call this route. This will save our new user to the database and will register the user with Authy.

        In order to set up your application, Authy only needs the user’s email, phone number and country code. In order to do a two-factor authentication, we need to make sure we ask for this information at sign-up.

        Once we register the user with Authy we get an Authy ID back. This is very important since it’s how we will verify the identity of the user with Authy.

              
              
              
              app/controllers/users_controller.rb

              Register a User with Authy

              app/controllers/users_controller.rb

              Having registered our user with Authy, we can use Authy’s OneTouch feature to log them in.

              See how to log a user in with Authy

              Log in with Authy OneTouch

              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 OneTouch verification first. OneTouch works like this:

              • 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.
              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 fall back gracefully if they don’t have a OneTouch device.

              Authy allows us to include extra information with our OneTouch request, including a message, a logo, and so on. Add extra information with details['some_detail']. Imagine a scenario where you send a OneTouch request to approve a money transfer. You’d set up details like:

              "message" => "Request to Send Money to Jarod's vault",
              "details['Request From']" => "Jarod",
              "details['Amount Request']" => "1,000,000",
              "details['Currency']" => "Galleons",
                    
                    
                    
                    app/controllers/sessions_controller.rb

                    Implement OneTouch Approval

                    app/controllers/sessions_controller.rb

                    Once we send the request we need to update our user’s authy_status based on the response. But first we have to register a OneTouch callback endpoint.

                    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.

                    In order to verify that a request is coming from Authy, we’ve written the helper method authenticate_request! that will halt the request if it appears the request isn’t coming from 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 use a websocket to let our client know that we received a response from Authy. However, we’re going to keep it simple and just update the authy_status on the User.

                          
                          
                          
                          app/controllers/authy_controller.rb

                          Configure OneTouch Callback

                          app/controllers/authy_controller.rb

                          Our application is now capable of using Authy for two-factor authentication. However, we are still missing an important part: the client-side code that will handle it.

                          How unsuccessful OneTouch callbacks are disabled

                          Disable unsuccessful callbacks

                          Scenario: The OneTouch callback URL provided by you is no longer active.

                          Action: We will disable the OneTouch callback after three consecutive HTTP error responses. We will also:

                          • Set the OneTouch callback URL to blank.
                          • Send an email notifying you that the OneTouch callback is disabled with details on how to enable the OneTouch callback.

                          How to enable OneTouch callback? You need to update the OneTouch callback endpoint, which will allow the OneTouch callback.

                          Visit the Twilio Console: Console > Authy > Applications > {ApplicationName} > Push Authentication > Webhooks > Endpoint/URL to update the Endpoint/URL with a valid OneTouch callback URL.

                          Handle authentication in the browser

                          Handle two-factor authentication in the browser

                          We’ve already seen what’s happening on the server side, so let’s step in front of the cameras and see how our JavaScript is interacting with those server endpoints.

                          When we expect a OneTouch response, we begin by polling /authy/status until we see an Authy status is not empty. Let’s take a look at this controller and see what is happening.

                                
                                
                                
                                app/assets/javascripts/sessions.js

                                Let’s take a closer look at how we check the login status on the server.

                                Confirm the login

                                Finish the 2FA step

                                If the value of authy_status is approved, the user will be redirected to the protected content, otherwise we’ll show the login form with a message that indicates the request was denied.

                                      
                                      
                                      
                                      app/controllers/authy_controller.rb

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

                                      Where next?

                                      Where next?

                                      If you’re a Ruby developer working with Twilio, you might enjoy these other tutorials:

                                      Masked Phone Numbers

                                      Protect your users’ privacy by anonymously connecting them with Twilio Voice and SMS. Learn how to create disposable phone numbers on-demand, so that two users can communicate without exchanging personal information.

                                      Call Tracking

                                      Use Twilio to track the effectiveness of your marketing campaigns.

                                      Did this help?

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

                                      Jarod Reyes Kelley Robinson David Prothero Kat King Andrew Baker Tony Smith Jose Oliveros Arnab Basu Anna Mason Chandan Manjunath
                                      Rate this page:

                                      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 by visiting Twilio's Stack Overflow Collective or browsing the Twilio tag on Stack Overflow.

                                            
                                            
                                            

                                            Thank you for your feedback!

                                            Please select the reason(s) for your feedback. The additional information you provide helps us improve our documentation:

                                            Sending your feedback...
                                            🎉 Thank you for your feedback!
                                            Something went wrong. Please try again.

                                            Thanks for your feedback!

                                            Refer us and get $10 in 3 simple steps!

                                            Step 1

                                            Get link

                                            Get a free personal referral link here

                                            Step 2

                                            Give $10

                                            Your user signs up and upgrade using link

                                            Step 3

                                            Get $10

                                            1,250 free SMSes
                                            OR 1,000 free voice mins
                                            OR 12,000 chats
                                            OR more