In this guide we'll cover how to secure your Flask application by validating incoming requests to your Twilio webhooks are, in fact, from Twilio.
With a few lines of code, we'll write a custom decorator for our Flask app that uses the Twilio Python SDK's validator utility. We can then use that decorator on our Flask views which accept Twilio webhooks to confirm that incoming requests genuinely originated from Twilio.
Let's get started!
The Twilio Python SDK includes a RequestValidator
class we can use to validate incoming requests.
We could include our request validation code as part of our Flask views, but this is a perfect opportunity to write a Python decorator. This way we can reuse our validation logic across all our views which accept incoming requests from Twilio.
Confirm incoming requests to your Flask views are genuine with this custom decorator.
1from flask import abort, Flask, request2from functools import wraps3from twilio.request_validator import RequestValidator45import os678app = Flask(__name__)91011def validate_twilio_request(f):12"""Validates that incoming requests genuinely originated from Twilio"""13@wraps(f)14def decorated_function(*args, **kwargs):15# Create an instance of the RequestValidator class16validator = RequestValidator(os.environ.get('TWILIO_AUTH_TOKEN'))1718# Validate the request using its URL, POST data,19# and X-TWILIO-SIGNATURE header20request_valid = validator.validate(21request.url,22request.form,23request.headers.get('X-TWILIO-SIGNATURE', ''))2425# Continue processing the request if it's valid, return a 403 error if26# it's not27if request_valid:28return f(*args, **kwargs)29else:30return abort(403)31return decorated_function32
To validate an incoming request genuinely originated from Twilio, we first need to create an instance of the RequestValidator
class using our Twilio auth token. After that we call its validate
method, passing in the request's URL, payload, and the value of the request's X-TWILIO-SIGNATURE
header.
That method will return True if the request is valid or False if it isn't. Our decorator then either continues processing the view or returns a 403 HTTP response for inauthentic requests.
If you are passing query string parameters in the URLs used in the webhooks you are validating, you may need to take extra care to encode or decode the URL so that validation passes. Some web frameworks like Flask will sometimes automatically unescape the query string part of the request URL, causing validation to fail.
Now we're ready to apply our decorator to any view in our Flask application that handles incoming requests from Twilio.
Apply a custom Twilio request validation decorator to a Flask view used for Twilio webhooks.
1from flask import Flask, request2from twilio.twiml.voice_response import VoiceResponse, MessagingResponse345app = Flask(__name__)678@app.route('/voice', methods=['POST'])9@validate_twilio_request10def incoming_call():11"""Twilio Voice URL - receives incoming calls from Twilio"""12# Create a new TwiML response13resp = VoiceResponse()1415# <Say> a message to the caller16from_number = request.values['From']17body = """18Thanks for calling!1920Your phone number is {0}. I got your call because of Twilio's webhook.2122Goodbye!""".format(' '.join(from_number))23resp.say(body)2425# Return the TwiML26return str(resp)272829@app.route('/message', methods=['POST'])30@validate_twilio_request31def incoming_message():32"""Twilio Messaging URL - receives incoming messages from Twilio"""33# Create a new TwiML response34resp = MessagingResponse()3536# <Message> a text back to the person who texted us37body = "Your text to me was {0} characters long. Webhooks are neat :)" \38.format(len(request.values['Body']))39resp.message(body)4041# Return the TwiML42return str(resp)434445if __name__ == '__main__':46app.run(debug=True)47
To use the decorator with an existing view, just put @validate_twilio_request
above the view's definition. In this sample application, we use our decorator with two views: one that handles incoming phone calls and another that handles incoming text messages.
If your Twilio webhook URLs start with https\://
instead of http\://
, your request validator may fail locally when you use Ngrok or in production if your stack terminates SSL connections upstream from your app. This is because the request URL that your Flask application sees does not match the URL Twilio used to reach your application.
To fix this for local development with Ngrok, use http\://
for your webhook instead of https\://
. To fix this in your production app, your decorator will need to reconstruct the request's original URL using request headers like X-Original-Host
and X-Forwarded-Proto
, if available.
If you write tests for your Flask views those tests may fail for views where you use your Twilio request validation decorator. Any requests your test suite sends to those views will fail the decorator's validation check.
To fix this problem we recommend adding an extra check in your decorator, like so, telling it to only reject incoming requests if your app is running in production.
Use this version of the custom Flask decorator if you test your Flask views.
1from flask import abort, current_app, request2from functools import wraps3from twilio.request_validator import RequestValidator45import os678def validate_twilio_request(f):9"""Validates that incoming requests genuinely originated from Twilio"""10@wraps(f)11def decorated_function(*args, **kwargs):12# Create an instance of the RequestValidator class13validator = RequestValidator(os.environ.get('TWILIO_AUTH_TOKEN'))1415# Validate the request using its URL, POST data,16# and X-TWILIO-SIGNATURE header17request_valid = validator.validate(18request.url,19request.form,20request.headers.get('X-TWILIO-SIGNATURE', ''))2122# Continue processing the request if it's valid (or if DEBUG is True)23# and return a 403 error if it's not24if request_valid or current_app.debug:25return f(*args, **kwargs)26else:27return abort(403)28return decorated_function29
It's a great idea to run automated testing against your webhooks to ensure that their signatures are secure. The following Python code can test your unique endpoints against both valid and invalid signatures.
To make this test work for you, you'll need to:
HTTPDigestAuth
to HTTPBasicAuth
This sample test will test the validity of your webhook signature with HTTP Basic or Digest authentication.
1# Download the twilio-python library from twilio.com/docs/python/install2from twilio.request_validator import RequestValidator3from requests.auth import HTTPDigestAuth4from requests.auth import HTTPBasicAuth5import requests6import urllib7import os89# Your Auth Token from twilio.com/user/account saved as an environment variable10# Remember never to hard code your auth token in code, browser Javascript, or distribute it in mobile apps11auth_token = os.environ.get('TWILIO_AUTH_TOKEN')12validator = RequestValidator(auth_token)1314# Replace this URL with your unique URL15url = 'https://mycompany.com/myapp'16# User credentials if required by your web server. Change to 'HTTPBasicAuth' if needed17auth = HTTPDigestAuth('username', 'password')1819params = {20'CallSid': 'CA1234567890ABCDE',21'Caller': '+12349013030',22'Digits': '1234',23'From': '+12349013030',24'To': '+18005551212'25}2627def test_url(method, url, params, valid):28if method == "GET":29url = url + '?' + urllib.parse.urlencode(params)30params = {}3132if valid:33signature = validator.compute_signature(url, params)34else:35signature = validator.compute_signature("http://invalid.com", params)3637headers = {'X-Twilio-Signature': signature}38response = requests.request(method, url, headers=headers, data=params, auth=auth)39print('HTTP {0} with {1} signature returned {2}'.format(method, 'valid' if valid else 'invalid', response.status_code))404142test_url('GET', url, params, True)43test_url('GET', url, params, False)44test_url('POST', url, params, True)45test_url('POST', url, params, False)
Validating requests to your Twilio webhooks is a great first step for securing your Twilio application. We recommend reading over our full security documentation for more advice on protecting your app, and the Anti-Fraud Developer's Guide in particular.
To learn more about securing your Flask application in general, check out the security considerations page in the official Flask docs.