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 Aplication' (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:
_10pipenv install
or
_10pip -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.
_10# You can get/create one here :_10# https://www.twilio.com/console/authy/applications_10ACCOUNT_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!
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 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.
_119from authy.api import AuthyApiClient_119from django.conf import settings_119from django.contrib.auth import login_119from django.contrib.auth.decorators import login_required_119from django.http import HttpResponse_119from django.shortcuts import render, redirect_119_119_119from .decorators import twofa_required_119from .forms import RegistrationForm, TokenVerificationForm_119from .models import TwoFAUser_119_119_119authy_api = AuthyApiClient(settings.ACCOUNT_SECURITY_API_KEY)_119_119_119def 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_119def 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_119def 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_119def 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_119def 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_119def 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_119def 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.