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.
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 and Django 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!
Create a new Twilio account (you can sign up for a free Twilio trial), or sign into an existing Twilio account.
Once logged in, visit the Authy Console. 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.
You'll automatically be transported to the Settings page next. Click the eyeball icon to reveal your Production API Key.
Copy your Production API Key to a safe place, you will use it during application setup.
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 our repository locally, 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
.
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/applications3ACCOUNT_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!
With your phone (optionally with the Authy client installed) nearby, open a new browser tab and navigate to http://localhost:8000/register/
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), and the application is returned a user_id
.
Now visit http://localhost:8000/login/ and login. You'll be presented with a happy screen:
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.
1from authy.api import AuthyApiClient2from django.conf import settings3from django.contrib.auth import login4from django.contrib.auth.decorators import login_required5from django.http import HttpResponse6from django.shortcuts import render, redirect789from .decorators import twofa_required10from .forms import RegistrationForm, TokenVerificationForm11from .models import TwoFAUser121314authy_api = AuthyApiClient(settings.ACCOUNT_SECURITY_API_KEY)151617def register(request):18if request.method == 'POST':19form = RegistrationForm(request.POST)20if form.is_valid():21authy_user = authy_api.users.create(22form.cleaned_data['email'],23form.cleaned_data['phone_number'],24form.cleaned_data['country_code'],25)26if authy_user.ok():27twofa_user = TwoFAUser.objects.create_user(28form.cleaned_data['username'],29form.cleaned_data['email'],30authy_user.id,31form.cleaned_data['password']32)33login(request, twofa_user)34return redirect('2fa')35else:36for key, value in authy_user.errors().items():37form.add_error(38None,39'{key}: {value}'.format(key=key, value=value)40)41else:42form = RegistrationForm()43return render(request, 'register.html', {'form': form})444546@login_required47def twofa(request):48if request.method == 'POST':49form = TokenVerificationForm(request.POST)50if form.is_valid(request.user.authy_id):51request.session['authy'] = True52return redirect('protected')53else:54form = TokenVerificationForm()55return render(request, '2fa.html', {'form': form})565758@login_required59def token_sms(request):60sms = authy_api.users.request_sms(request.user.authy_id, {'force': True})61if sms.ok():62return HttpResponse('SMS request successful', status=200)63else:64return HttpResponse('SMS request failed', status=503)656667@login_required68def token_voice(request):69call = authy_api.users.request_call(request.user.authy_id, {'force': True})70if call.ok():71return HttpResponse('Call request successfull', status=200)72else:73return HttpResponse('Call request failed', status=503)747576@login_required77def token_onetouch(request):78details = {79'Authy ID': request.user.authy_id,80'Username': request.user.username,81'Reason': 'Demo by Account Security'82}8384hidden_details = {85'test': 'This is a'86}8788response = authy_api.one_touch.send_request(89int(request.user.authy_id),90message='Login requested for Account Security account.',91seconds_to_expire=120,92details=details,93hidden_details=hidden_details94)95if response.ok():96request.session['onetouch_uuid'] = response.get_uuid()97return HttpResponse('OneTouch request successfull', status=200)98else:99return HttpResponse('OneTouch request failed', status=503)100101102@login_required103def onetouch_status(request):104uuid = request.session['onetouch_uuid']105approval_status = authy_api.one_touch.get_approval_status(uuid)106if approval_status.ok():107if approval_status['approval_request']['status'] == 'approved':108request.session['authy'] = True109return HttpResponse(110approval_status['approval_request']['status'],111status=200112)113else:114return HttpResponse(approval_status.errros(), status=503)115116117@twofa_required118def protected(request):119return 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.