Skip to contentSkip to navigationSkip to topbar
On this page

Secure your Flask App by Validating Incoming Twilio Requests


In this guide we'll cover how to secure your Flask(link takes you to an external page) 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!


Create a custom decorator

create-a-custom-decorator page anchor

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(link takes you to an external page). This way we can reuse our validation logic across all our views which accept incoming requests from Twilio.

Custom decorator for Flask apps to validate Twilio requests

custom-decorator-for-flask-apps-to-validate-twilio-requests page anchor

Confirm incoming requests to your Flask views are genuine with this custom decorator.

1
from flask import abort, Flask, request
2
from functools import wraps
3
from twilio.request_validator import RequestValidator
4
5
import os
6
7
8
app = Flask(__name__)
9
10
11
def validate_twilio_request(f):
12
"""Validates that incoming requests genuinely originated from Twilio"""
13
@wraps(f)
14
def decorated_function(*args, **kwargs):
15
# Create an instance of the RequestValidator class
16
validator = RequestValidator(os.environ.get('TWILIO_AUTH_TOKEN'))
17
18
# Validate the request using its URL, POST data,
19
# and X-TWILIO-SIGNATURE header
20
request_valid = validator.validate(
21
request.url,
22
request.form,
23
request.headers.get('X-TWILIO-SIGNATURE', ''))
24
25
# Continue processing the request if it's valid, return a 403 error if
26
# it's not
27
if request_valid:
28
return f(*args, **kwargs)
29
else:
30
return abort(403)
31
return decorated_function
32

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.

(warning)

Warning

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.


Use the Decorator with our Twilio Webhooks

use-the-decorator-with-our-twilio-webhooks page anchor

Now we're ready to apply our decorator to any view in our Flask application that handles incoming requests from Twilio.

Apply the request validation decorator to a Flask view

apply-the-request-validation-decorator-to-a-flask-view page anchor

Apply a custom Twilio request validation decorator to a Flask view used for Twilio webhooks.

1
from flask import Flask, request
2
from twilio.twiml.voice_response import VoiceResponse, MessagingResponse
3
4
5
app = Flask(__name__)
6
7
8
@app.route('/voice', methods=['POST'])
9
@validate_twilio_request
10
def incoming_call():
11
"""Twilio Voice URL - receives incoming calls from Twilio"""
12
# Create a new TwiML response
13
resp = VoiceResponse()
14
15
# <Say> a message to the caller
16
from_number = request.values['From']
17
body = """
18
Thanks for calling!
19
20
Your phone number is {0}. I got your call because of Twilio's webhook.
21
22
Goodbye!""".format(' '.join(from_number))
23
resp.say(body)
24
25
# Return the TwiML
26
return str(resp)
27
28
29
@app.route('/message', methods=['POST'])
30
@validate_twilio_request
31
def incoming_message():
32
"""Twilio Messaging URL - receives incoming messages from Twilio"""
33
# Create a new TwiML response
34
resp = MessagingResponse()
35
36
# <Message> a text back to the person who texted us
37
body = "Your text to me was {0} characters long. Webhooks are neat :)" \
38
.format(len(request.values['Body']))
39
resp.message(body)
40
41
# Return the TwiML
42
return str(resp)
43
44
45
if __name__ == '__main__':
46
app.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.

(warning)

Warning

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.


Disable Request Validation During Testing

disable-request-validation-during-testing page anchor

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.

An improved Flask request validation decorator, useful for testing

an-improved-flask-request-validation-decorator-useful-for-testing page anchor

Use this version of the custom Flask decorator if you test your Flask views.

1
from flask import abort, current_app, request
2
from functools import wraps
3
from twilio.request_validator import RequestValidator
4
5
import os
6
7
8
def validate_twilio_request(f):
9
"""Validates that incoming requests genuinely originated from Twilio"""
10
@wraps(f)
11
def decorated_function(*args, **kwargs):
12
# Create an instance of the RequestValidator class
13
validator = RequestValidator(os.environ.get('TWILIO_AUTH_TOKEN'))
14
15
# Validate the request using its URL, POST data,
16
# and X-TWILIO-SIGNATURE header
17
request_valid = validator.validate(
18
request.url,
19
request.form,
20
request.headers.get('X-TWILIO-SIGNATURE', ''))
21
22
# Continue processing the request if it's valid (or if DEBUG is True)
23
# and return a 403 error if it's not
24
if request_valid or current_app.debug:
25
return f(*args, **kwargs)
26
else:
27
return abort(403)
28
return decorated_function
29

Test the validity of your webhook signature

test-the-validity-of-your-webhook-signature page anchor
(information)

Info

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:

  1. Set your Auth Token(link takes you to an external page) as an environment variable
  2. Set the URL to the endpoint you want to test
  3. If testing BasicAuth, change HTTPDigestAuth to HTTPBasicAuth

Test the validity of your webhook signature

test-the-validity-of-your-webhook-signature-1 page anchor

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/install
2
from twilio.request_validator import RequestValidator
3
from requests.auth import HTTPDigestAuth
4
from requests.auth import HTTPBasicAuth
5
import requests
6
import urllib
7
import os
8
9
# Your Auth Token from twilio.com/user/account saved as an environment variable
10
# Remember never to hard code your auth token in code, browser Javascript, or distribute it in mobile apps
11
auth_token = os.environ.get('TWILIO_AUTH_TOKEN')
12
validator = RequestValidator(auth_token)
13
14
# Replace this URL with your unique URL
15
url = 'https://mycompany.com/myapp'
16
# User credentials if required by your web server. Change to 'HTTPBasicAuth' if needed
17
auth = HTTPDigestAuth('username', 'password')
18
19
params = {
20
'CallSid': 'CA1234567890ABCDE',
21
'Caller': '+12349013030',
22
'Digits': '1234',
23
'From': '+12349013030',
24
'To': '+18005551212'
25
}
26
27
def test_url(method, url, params, valid):
28
if method == "GET":
29
url = url + '?' + urllib.parse.urlencode(params)
30
params = {}
31
32
if valid:
33
signature = validator.compute_signature(url, params)
34
else:
35
signature = validator.compute_signature("http://invalid.com", params)
36
37
headers = {'X-Twilio-Signature': signature}
38
response = requests.request(method, url, headers=headers, data=params, auth=auth)
39
print('HTTP {0} with {1} signature returned {2}'.format(method, 'valid' if valid else 'invalid', response.status_code))
40
41
42
test_url('GET', url, params, True)
43
test_url('GET', url, params, False)
44
test_url('POST', url, params, True)
45
test_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(link takes you to an external page).

Need some help?

Terms of service

Copyright © 2024 Twilio Inc.