Skip to contentSkip to navigationSkip to topbar
On this page

Python Flask Quickstart for Twilio Two-factor Authentication


(warning)

Warning

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(link takes you to an external page).

Adding Two-factor Authentication to your application is the easiest way to increase security and trust in your product without unnecessarily burdening your users. This quickstart guides you through building a Python(link takes you to an external page) and Flask(link takes you to an external page) application that restricts access to a URL. Four Two-factor Authentication channels are demoed: SMS, Voice, Soft Tokens and Push Notifications.

Ready to protect your toy app's users from nefarious balaclava wearing hackers? Dive in!


Sign Into - or Sign Up For - a Twilio Account

sign-into---or-sign-up-for---a-twilio-account page anchor

Create a new Twilio account (you can sign up for a free Twilio trial), or sign into an existing Twilio account(link takes you to an external page).

Create a New Account Security Application

create-a-new-account-security-application page anchor

Once logged in, visit the Authy Console(link takes you to an external page). Click on the red 'Create New Application' (or big red plus ('+') if you already created one) to create a new Authy application then name it something memorable.

Authy create new application.

You'll automatically be transported to the Settings page next. Click the eyeball icon to reveal your Production API Key.

Account Security API Key.

Copy your Production API Key to a safe place, you will use it during application setup.


Setup Authy on Your Device

setup-authy-on-your-device page anchor

This Two-factor Authentication demos two channels which require an installed Authy Client to test: Soft Tokens and Push Notifications. While SMS and Voice channels will work without the client, to try out all four authentication channels download and install Authy Client for Desktop or Mobile:


Clone and Setup the Application

clone-and-setup-the-application page anchor

Clone our repository locally(link takes you to an external page), then enter the directory. Install all of the necessary python modules:

pipenv install

or

pip -r requirements.txt

Next, open the file .env.example. There, edit the ACCOUNT_SECURITY_API_KEY, pasting in the API Key from the above step (in the console), and save the file as .env.

Add Your Application API Key

add-your-application-api-key page anchor

Enter the API Key from the Account Security console and optionally change the port.

1
SECRET_KEY=[create_a_key]
2
3
DATABASE_URI=
4
5
# You can get/create one here :
6
# https://www.twilio.com/console/authy/applications
7
ACCOUNT_SECURITY_API_KEY='ENTER_SECRET_HERE'
8

Once you have added your API Key, you are ready to run! Launch Flask with:

./manage.py runserver

If your API Key is correct, you should get a message your new app is running!


Try the Python/Flask Two-Factor Demo

try-the-pythonflask-two-factor-demo page anchor

With your phone (optionally with the Authy client installed) nearby, open a new browser tab and navigate to http://localhost:5000/register/(link takes you to an external page)

Enter your information and invent a password, then hit 'Register'. Your information is passed to Twilio (you will be able to see your user immediately in the console(link takes you to an external page)), and the application is returned a user_id.

Now visit http://localhost:5000/login/(link takes you to an external page) and login. You'll be presented with a happy screen:

Two Factor Authentication Demo.

If your phone has the Authy Client installed, you can immediately enter a Soft Token from the client to Verify. Additionally, you can try a Push Notification by pushing the labeled button.

If you do not have the Authy Client installed, the SMS and Voice channels will also work in providing a token. To try different channels, you can logout to start the process again.

Two-Factor Authentication Channels

two-factor-authentication-channels page anchor
1
import flask
2
3
from authy.api import AuthyApiClient
4
from flask_login import login_required, login_user, logout_user, current_user
5
6
from . import app, login_manager, db
7
# from .database import db_session
8
from .decorators import twofa_required
9
from .forms import (
10
LoginForm,
11
RegistrationForm,
12
TokenVerificationForm,
13
PhoneVerificationForm,
14
TokenPhoneValidationForm,
15
)
16
from .models import User
17
18
19
authy_api = AuthyApiClient(app.config.get('ACCOUNT_SECURITY_API_KEY'))
20
21
22
@app.route('/protected')
23
@login_required
24
@twofa_required
25
def protected():
26
return flask.render_template('protected.html')
27
28
29
@app.route('/login', methods=['GET', 'POST'])
30
def login():
31
form = LoginForm()
32
if form.validate_on_submit():
33
login_user(form.user, remember=True)
34
form.user.is_authenticated = True
35
db.session.add(form.user)
36
db.session.commit()
37
next = flask.request.args.get('next')
38
return flask.redirect(next or flask.url_for('protected'))
39
return flask.render_template('login.html', form=form)
40
41
42
@app.route("/logout", methods=["GET"])
43
@login_required
44
def logout():
45
current_user.is_authenticated = False
46
db.session.add(current_user)
47
db.session.commit()
48
flask.session['authy'] = False
49
flask.session['is_verified'] = False
50
logout_user()
51
return flask.redirect('/login')
52
53
54
@app.route('/', methods=['GET', 'POST'])
55
def index():
56
return flask.redirect('/login')
57
58
59
login_manager.unauthorized_handler(index)
60
61
62
@app.route('/register', methods=['GET', 'POST'])
63
def register():
64
form = RegistrationForm()
65
if form.validate_on_submit():
66
authy_user = authy_api.users.create(
67
form.email.data,
68
form.phone_number.data,
69
form.country_code.data,
70
)
71
if authy_user.ok():
72
user = User(
73
form.username.data,
74
form.email.data,
75
form.password.data,
76
authy_user.id,
77
is_authenticated=True
78
)
79
user.authy_id = authy_user.id
80
db.session.add(user)
81
db.session.commit()
82
login_user(user, remember=True)
83
return flask.redirect('/protected')
84
else:
85
form.errors['non_field'] = []
86
for key, value in authy_user.errors().items():
87
form.errors['non_field'].append(
88
'{key}: {value}'.format(key=key, value=value)
89
)
90
return flask.render_template('register.html', form=form)
91
92
93
@app.route('/2fa', methods=['GET', 'POST'])
94
@login_required
95
def twofa():
96
form = TokenVerificationForm(current_user.authy_id)
97
if form.validate_on_submit():
98
flask.session['authy'] = True
99
return flask.redirect('/protected')
100
return flask.render_template('2fa.html', form=form)
101
102
103
@app.route('/token/sms', methods=['POST'])
104
@login_required
105
def token_sms():
106
sms = authy_api.users.request_sms(current_user.authy_id, {'force': True})
107
if sms.ok():
108
return flask.Response('SMS request successful', status=200)
109
else:
110
return flask.Response('SMS request failed', status=503)
111
112
113
@app.route('/token/voice', methods=['POST'])
114
@login_required
115
def token_voice():
116
call = authy_api.users.request_call(current_user.authy_id, {'force': True})
117
if call.ok():
118
return flask.Response('Call request successful', status=200)
119
else:
120
return flask.Response('Call request failed', status=503)
121
122
123
@app.route('/token/onetouch', methods=['POST'])
124
@login_required
125
def token_onetouch():
126
details = {
127
'Authy ID': current_user.authy_id,
128
'Username': current_user.username,
129
'Reason': 'Demo by Account Security'
130
}
131
132
hidden_details = {
133
'test': 'This is a'
134
}
135
136
response = authy_api.one_touch.send_request(
137
int(current_user.authy_id),
138
message='Login requested for Account Security account.',
139
seconds_to_expire=120,
140
details=details,
141
hidden_details=hidden_details
142
)
143
if response.ok():
144
flask.session['onetouch_uuid'] = response.get_uuid()
145
return flask.Response('OneTouch request successfull', status=200)
146
else:
147
return flask.Response('OneTouch request failed', status=503)
148
149
150
@app.route('/onetouch-status', methods=['POST'])
151
@login_required
152
def onetouch_status():
153
uuid = flask.session['onetouch_uuid']
154
approval_status = authy_api.one_touch.get_approval_status(uuid)
155
if approval_status.ok():
156
if approval_status['approval_request']['status'] == 'approved':
157
flask.session['authy'] = True
158
return flask.Response(
159
approval_status['approval_request']['status'],
160
status=200
161
)
162
else:
163
return flask.Response(approval_status.errros(), status=503)
164
165
166
######################
167
# Phone Verification #
168
######################
169
170
@app.route('/verification', methods=['GET', 'POST'])
171
def phone_verification():
172
form = PhoneVerificationForm()
173
if form.validate_on_submit():
174
flask.session['phone_number'] = form.phone_number.data
175
flask.session['country_code'] = form.country_code.data
176
authy_api.phones.verification_start(
177
form.phone_number.data,
178
form.country_code.data,
179
via=form.via.data
180
)
181
return flask.redirect('/verification/token')
182
return flask.render_template('phone_verification.html', form=form)
183
184
185
@app.route('/verification/token', methods=['GET', 'POST'])
186
def token_validation():
187
form = TokenPhoneValidationForm()
188
if form.validate_on_submit():
189
verification = authy_api.phones.verification_check(
190
flask.session['phone_number'],
191
flask.session['country_code'],
192
form.token.data
193
)
194
if verification.ok():
195
flask.session['is_verified'] = True
196
return flask.redirect('/verified')
197
else:
198
form.errors['non_field'] = []
199
for error_msg in verification.errors().values():
200
form.errors['non_field'].append(error_msg)
201
return flask.render_template('token_validation.html', form=form)
202
203
204
@app.route('/verified')
205
def verified():
206
if not flask.session.get('is_verified'):
207
return flask.redirect('/verification')
208
return flask.render_template('verified.html')
209

And there you go, Two-factor Authentication is on and your Flask app is protected!


Now that you are keeping the hackers out of this demo app using Two-factor Authentication, you can find all of the detailed descriptions for options and API calls in our Two-factor Authentication API Reference. If you're also building a registration flow, also check out our Phone Verification product and the Verification Quickstart which uses this codebase.

For additional guides and tutorials on account security and other products, in Python and in our other languages, take a look at the Docs.

Need some help?

Terms of service

Copyright © 2024 Twilio Inc.