Skip to contentSkip to navigationSkip to topbar
Rate this page:
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 Aplication' (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:


_10
pipenv install

or


_10
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.


_10
# You can get/create one here :
_10
# https://www.twilio.com/console/authy/applications
_10
ACCOUNT_SECURITY_API_KEY='ENTER_SECRET_HERE'

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


_10
./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 simply 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

_119
from authy.api import AuthyApiClient
_119
from django.conf import settings
_119
from django.contrib.auth import login
_119
from django.contrib.auth.decorators import login_required
_119
from django.http import HttpResponse
_119
from django.shortcuts import render, redirect
_119
_119
_119
from .decorators import twofa_required
_119
from .forms import RegistrationForm, TokenVerificationForm
_119
from .models import TwoFAUser
_119
_119
_119
authy_api = AuthyApiClient(settings.ACCOUNT_SECURITY_API_KEY)
_119
_119
_119
def register(request):
_119
if request.method == 'POST':
_119
form = RegistrationForm(request.POST)
_119
if form.is_valid():
_119
authy_user = authy_api.users.create(
_119
form.cleaned_data['email'],
_119
form.cleaned_data['phone_number'],
_119
form.cleaned_data['country_code'],
_119
)
_119
if authy_user.ok():
_119
twofa_user = TwoFAUser.objects.create_user(
_119
form.cleaned_data['username'],
_119
form.cleaned_data['email'],
_119
authy_user.id,
_119
form.cleaned_data['password']
_119
)
_119
login(request, twofa_user)
_119
return redirect('2fa')
_119
else:
_119
for key, value in authy_user.errors().items():
_119
form.add_error(
_119
None,
_119
'{key}: {value}'.format(key=key, value=value)
_119
)
_119
else:
_119
form = RegistrationForm()
_119
return render(request, 'register.html', {'form': form})
_119
_119
_119
@login_required
_119
def twofa(request):
_119
if request.method == 'POST':
_119
form = TokenVerificationForm(request.POST)
_119
if form.is_valid(request.user.authy_id):
_119
request.session['authy'] = True
_119
return redirect('protected')
_119
else:
_119
form = TokenVerificationForm()
_119
return render(request, '2fa.html', {'form': form})
_119
_119
_119
@login_required
_119
def token_sms(request):
_119
sms = authy_api.users.request_sms(request.user.authy_id, {'force': True})
_119
if sms.ok():
_119
return HttpResponse('SMS request successful', status=200)
_119
else:
_119
return HttpResponse('SMS request failed', status=503)
_119
_119
_119
@login_required
_119
def token_voice(request):
_119
call = authy_api.users.request_call(request.user.authy_id, {'force': True})
_119
if call.ok():
_119
return HttpResponse('Call request successfull', status=200)
_119
else:
_119
return HttpResponse('Call request failed', status=503)
_119
_119
_119
@login_required
_119
def token_onetouch(request):
_119
details = {
_119
'Authy ID': request.user.authy_id,
_119
'Username': request.user.username,
_119
'Reason': 'Demo by Account Security'
_119
}
_119
_119
hidden_details = {
_119
'test': 'This is a'
_119
}
_119
_119
response = authy_api.one_touch.send_request(
_119
int(request.user.authy_id),
_119
message='Login requested for Account Security account.',
_119
seconds_to_expire=120,
_119
details=details,
_119
hidden_details=hidden_details
_119
)
_119
if response.ok():
_119
request.session['onetouch_uuid'] = response.get_uuid()
_119
return HttpResponse('OneTouch request successfull', status=200)
_119
else:
_119
return HttpResponse('OneTouch request failed', status=503)
_119
_119
_119
@login_required
_119
def onetouch_status(request):
_119
uuid = request.session['onetouch_uuid']
_119
approval_status = authy_api.one_touch.get_approval_status(uuid)
_119
if approval_status.ok():
_119
if approval_status['approval_request']['status'] == 'approved':
_119
request.session['authy'] = True
_119
return HttpResponse(
_119
approval_status['approval_request']['status'],
_119
status=200
_119
)
_119
else:
_119
return HttpResponse(approval_status.errros(), status=503)
_119
_119
_119
@twofa_required
_119
def protected(request):
_119
return render(request, 'protected.html')

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.


Rate this page: