Rate this page:

Two-Factor Authentication with Authy, Python and Flask

As of November 2022, Twilio no longer provides support for Authy SMS/Voice-only customers. Customers who were also using Authy TOTP or Push prior to March 1, 2023 are still supported. The Authy API is now closed to new customers and will be fully deprecated in the future.

For new development, we encourage you to use the Verify v2 API.

Existing customers will not be impacted at this time until Authy API has reached End of Life. For more information about migration, see Migrating from Authy to Verify for SMS.

This Flask 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 then a second time with their mobile device using Authy.

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 or
  • Sending them a token through their mobile 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.

Click here to start the tutorial!

Configuring Authy

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 our .env file, which helps us set the environment variables for our app.

You'll also want to set a callback URL for your application in the OneTouch section of the Authy dashboard. See the project README for more details.

Loading Code Sample...

        Environment Variable Settings


        Now that we've configured our Flask app, let's take a look at how we 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 call this helper function, which handles storing the user in the database as well as registering the user with Authy.

        In order to get a user set up for your application you will need their email, phone number and country code. We have fields for each of these on our sign up form.

        Once we register the user with Authy we can get the user's Authy id off the response. This is very important — it's how we will verify the identity of our user with Authy.

        Loading Code Sample...

              Create and Register a User with Authy


              Next up, let's take a look at the login.

              Log in with OneTouch

              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 so:

              • We attempt to send a OneTouch Approval Request to the user
              • 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...

                    Log in with Authy OneTouch

                    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, but we don't know until we try.

                    Authy lets us pass extra 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] to our POST request. You could imagine a scenario where we send a OneTouch request to approve a money transfer:

                    data = {
                        'api_key': client.api_key,
                        'message': "Request to send money to Jarod's vault",
                        'details[Request From]': 'Jarod',
                        'details[Amount Requested]': '1,000,000',
                        'details[Currency]': 'Galleons'
                    Loading Code Sample...

                          Send the OneTouch Request


                          Once we send the request we update our user's authy_status based on the response. This lets us know which method Authy will try first to verify this request with our user. 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.

                          Note: In order to verify that the request is coming from Authy we've written a decorator, @verify_authy_request, that will halt the request if we cannot verify that it actually came from Authy.

                          Here in our callback, we look up the user using the authy_id sent with the Authy POST request. In a production application we might use a websocket to let our client know that we received a response from Authy. For this version, we keep it simple and update the authy_status on the user. Our client-side code will check that field before completing the login.

                          Loading Code Sample...

                                Update user status using Authy Callback


                                Let's take a look at that client-side code now.

                                How Unsuccessful OneTouch Callbacks are disabled

                                Disabling Unsuccessful Callbacks

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

                                Action: We will disable the OneTouch callback after 3 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 2FA asynchronously

                                Handle Two-Factor Asynchronously

                                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.

                                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 submit and pass the data to our sessions/create controller using Ajax. Depending on how that endpoint responds, we will either wait for a OneTouch response or ask the user to enter a token.

                                If we expect a OneTouch response, we will begin polling /login/status until we see the OneTouch login was either approved or denied.

                                Loading Code Sample...

                                      Handle Two-Factor Asynchronously


                                      Now let's see how to handle the case where we receive a denied OneTouch response.

                                      How to handle exceptions

                                      Fall back to a Token

                                      This is the endpoint that our javascript is polling. It is waiting for the user's authy_status to be either approved or denied. If the user approves the OneTouch request, our JavaScript code from the previous step will redirect their browser to their account screen.

                                      If the OneTouch request was denied, we will ask the user to log in with a token instead.

                                      Loading Code Sample...

                                            Handle Login Status


                                            Now let's see how to send a token to the user.

                                            Send a token

                                            Send a Token

                                            This view is responsible for sending the token and then validating the code that our user enters.

                                            In the case where our user already has the Authy app but is not enabled for OneTouch, this same method will trigger a push notification that will be sent to their phone with a code inside the Authy app.

                                            The user will see a verification form.

                                            A POST request to this view validates the code our user enters. First, we grab the User model by the ID we stored in the session. Next, we use the Authy API to validate the code our user entered against the one Authy sent them.

                                            If the two match, our login process is complete! We mark the user's authy_status as approved and thank them for using two-factor authentication.

                                            Loading Code Sample...

                                                  Verify users via Authy Token


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

                                                  What's next?

                                                  Where to next?

                                                  If you're a Python developer working with Twilio, you might enjoy these other tutorials:

                                                  SMS and MMS Notifications

                                                  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.

                                                  Call Tracking

                                                  Call Tracking helps you measure the effectiveness of different marketing campaigns. By assigning a unique phone number to different advertisements, you can track which ones have the best call rates and get some data about the callers themselves.

                                                  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!

                                                  Andrew Baker Kelley Robinson Kat King Alejandro Vivanco David Baldassari 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.

                                                  Loading Code Sample...

                                                        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!