Skip to contentSkip to navigationSkip to topbar
On this page

Python Django 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 Django(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
# You can get/create one here :
2
# https://www.twilio.com/console/authy/applications
3
ACCOUNT_SECURITY_API_KEY='ENTER_SECRET_HERE'

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

./manage.py runserver

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


Try the Python/Django Two-Factor Demo

try-the-pythondjango-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:8000/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:8000/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
from authy.api import AuthyApiClient
2
from django.conf import settings
3
from django.contrib.auth import login
4
from django.contrib.auth.decorators import login_required
5
from django.http import HttpResponse
6
from django.shortcuts import render, redirect
7
8
9
from .decorators import twofa_required
10
from .forms import RegistrationForm, TokenVerificationForm
11
from .models import TwoFAUser
12
13
14
authy_api = AuthyApiClient(settings.ACCOUNT_SECURITY_API_KEY)
15
16
17
def register(request):
18
if request.method == 'POST':
19
form = RegistrationForm(request.POST)
20
if form.is_valid():
21
authy_user = authy_api.users.create(
22
form.cleaned_data['email'],
23
form.cleaned_data['phone_number'],
24
form.cleaned_data['country_code'],
25
)
26
if authy_user.ok():
27
twofa_user = TwoFAUser.objects.create_user(
28
form.cleaned_data['username'],
29
form.cleaned_data['email'],
30
authy_user.id,
31
form.cleaned_data['password']
32
)
33
login(request, twofa_user)
34
return redirect('2fa')
35
else:
36
for key, value in authy_user.errors().items():
37
form.add_error(
38
None,
39
'{key}: {value}'.format(key=key, value=value)
40
)
41
else:
42
form = RegistrationForm()
43
return render(request, 'register.html', {'form': form})
44
45
46
@login_required
47
def twofa(request):
48
if request.method == 'POST':
49
form = TokenVerificationForm(request.POST)
50
if form.is_valid(request.user.authy_id):
51
request.session['authy'] = True
52
return redirect('protected')
53
else:
54
form = TokenVerificationForm()
55
return render(request, '2fa.html', {'form': form})
56
57
58
@login_required
59
def token_sms(request):
60
sms = authy_api.users.request_sms(request.user.authy_id, {'force': True})
61
if sms.ok():
62
return HttpResponse('SMS request successful', status=200)
63
else:
64
return HttpResponse('SMS request failed', status=503)
65
66
67
@login_required
68
def token_voice(request):
69
call = authy_api.users.request_call(request.user.authy_id, {'force': True})
70
if call.ok():
71
return HttpResponse('Call request successfull', status=200)
72
else:
73
return HttpResponse('Call request failed', status=503)
74
75
76
@login_required
77
def token_onetouch(request):
78
details = {
79
'Authy ID': request.user.authy_id,
80
'Username': request.user.username,
81
'Reason': 'Demo by Account Security'
82
}
83
84
hidden_details = {
85
'test': 'This is a'
86
}
87
88
response = authy_api.one_touch.send_request(
89
int(request.user.authy_id),
90
message='Login requested for Account Security account.',
91
seconds_to_expire=120,
92
details=details,
93
hidden_details=hidden_details
94
)
95
if response.ok():
96
request.session['onetouch_uuid'] = response.get_uuid()
97
return HttpResponse('OneTouch request successfull', status=200)
98
else:
99
return HttpResponse('OneTouch request failed', status=503)
100
101
102
@login_required
103
def onetouch_status(request):
104
uuid = request.session['onetouch_uuid']
105
approval_status = authy_api.one_touch.get_approval_status(uuid)
106
if approval_status.ok():
107
if approval_status['approval_request']['status'] == 'approved':
108
request.session['authy'] = True
109
return HttpResponse(
110
approval_status['approval_request']['status'],
111
status=200
112
)
113
else:
114
return HttpResponse(approval_status.errros(), status=503)
115
116
117
@twofa_required
118
def protected(request):
119
return render(request, 'protected.html')
120

And there you go, Two-factor Authentication is on and your Django 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.