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?

SMS Two-Factor Authentication with Python and Flask

This Flask application example demonstrates how to implement an SMS two-factor authentication using Twilio.

To follow along with this tutorial yourself, please clone the repo from GitHub and follow the instructions there on starting the local server.

Adding two-factor authentication (2FA) to your web application increases the security of your user's data. Multi-factor authentication with Twilio will help you determine a user's identity in two steps:

  1. First we validate the user with an email and password
  2. Second we validate the user using his or her mobile device, by sending a one-time verification code

Once our user enters the verification code, we know they have received the SMS and are indeed who they say they are. This tutorial will walk you through a standard SMS implementation.


        For a more advanced - and more secure - integration using Authy One-Touch, checkout this tutorial.

        Let's get started!

        Generate a Verification Code

        Once our user logs in we need to send them the one-time verification code.

        To generate our verification code we use random.randrange which can take a range as an argument. Let's send them a 6-digit verification code, somewhere between 100000 and 999999.


              Generate a Verification Code


              Next, let's take a look at how we would send this in an SMS with Twilio.

              Send the Verification Code

              Send a Verification Code

              The Twilio Python helper library allows us to easily send an SMS.

              First we have to create an instance of a Twilio Rest Client with our credentials. Then all we have to do, to be able to send an SMS using the REST API, is to call client.messages.create() with the necessary parameters.

              You can find the necessary credentials in the Twilio Console.


                    Send a Verification Code


                    Now that we know how to generate the verification code and send it, let's now look at how to kick off the signup process.

                    Register a User

                    Register a User

                    When a user signs up for your website, this controller creates the user and sends them the generated verification code.

                    In order to do two-factor authentication we need to make sure we ask for the user's phone number.

                    Let's see how to implement the send_confirmation_code function.


                          Flask route for signup form


                          Now let's take a closer at how to proceed with the 2-step verification.

                          Let's Put It All Together!

                          Putting It All Together

                          Using the building blocks we've created in the previous steps we can now put it all together.

                          Note that we are using the Flask-Session extension for the storage of the generated code instead of putting it in the user session. User sessions in Flask are not the proper area to store sensitive information, and secrets can be extracted from the browser console. At a minimum, if you're going to store the validation code on the client side, use encrypted sessions with something like It's Dangerous, or use a server side solution like we're demonstrating here.


                                Send the confirmation code and save in the session


                                And now, a drumroll for the second step of the two-step authentication implementation...

                                Implement the 2-Step Verification

                                Implementing the 2-Step Verification

                                When the user receives an SMS with the verification code it's on us to ensure the given code is valid.

                                This validation is achieved by comparing the user's session verification code with the verification code the user inputs on the form.

                                If the validation was successful the application allows the user to have access to the protected content we shielded in this process. Otherwise, the application will prompt for the verification code once again.


                                      That's it! We've just implemented SMS Two-Factor Authentication that you can now use in your applications!

                                      Where to next?

                                      Where to next?

                                      If you're a Python developer working with Twilio, you're going to want to eventually check out these other excellent tutorials:

                                      Automated Survey

                                      Instantly collect structured data from your users with a survey conducted over a voice call or SMS text messages.

                                      Click to Call

                                      Click-to-call enables your company to convert web traffic into phone calls with the click of a button. Learn how to implement it in minutes.

                                      Did this help?

                                      Thanks for checking out this tutorial! If you have any feedback to share with us, please reach out on Twitter... we'd love to hear your thoughts, and know what you're building!

                                      Jose Oliveros Ricky Holtz Agustin Camino David Prothero Samuel Mendes Paul Kamp Andrew Baker Kat King
                                      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 browsing the Twilio tag on Stack Overflow.