Skip to contentSkip to navigationSkip to topbar
On this page

Secure your PHP/Lumen app by validating incoming Twilio requests


In this guide we'll cover how to secure your Lumen(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 middleware for our Lumen app that uses the Twilio PHP SDK's(link takes you to an external page) RequestValidator(link takes you to an external page) utility. We can then use that middleware on our Lumen routes which accept Twilio webhooks to confirm that incoming requests genuinely originated from Twilio.

Let's get started!


Create custom middleware

create-custom-middleware page anchor

The Twilio PHP SDK includes a RequestValidator utility which we can use to validate incoming requests.

We could include our request validation code as part of each Lumen route, but this is a perfect opportunity to write Lumen middleware. This way we can reuse our validation logic across all our routes which accept incoming requests from Twilio.

To validate an incoming request genuinely originated from Twilio, we need to call the $requestValidator->validate(...). That method will return true if the request is valid or false if it isn't. Our middleware then either continues processing the view or returns a 403 HTTP response for unauthorized requests.

Create Lumen middleware to handle and validate requests

create-lumen-middleware-to-handle-and-validate-requests page anchor

Use Twilio SDK RequestValidator to validate webhook requests.

1
<?php
2
3
namespace App\Http\Middleware;
4
5
use Closure;
6
use Illuminate\Http\Response;
7
use Twilio\Security\RequestValidator;
8
9
class TwilioRequestValidator
10
{
11
/**
12
* Handle an incoming request.
13
*
14
* @param \Illuminate\Http\Request $request
15
* @param \Closure $next
16
* @return mixed
17
*/
18
public function handle($request, Closure $next)
19
{
20
// Be sure TWILIO_AUTH_TOKEN is set in your .env file.
21
// You can get your authentication token in your twilio console https://www.twilio.com/console
22
$requestValidator = new RequestValidator(env('TWILIO_AUTH_TOKEN'));
23
24
$requestData = $request->toArray();
25
26
// Switch to the body content if this is a JSON request.
27
if (array_key_exists('bodySHA256', $requestData)) {
28
$requestData = $request->getContent();
29
}
30
31
$isValid = $requestValidator->validate(
32
$request->header('X-Twilio-Signature'),
33
$request->fullUrl(),
34
$requestData
35
);
36
37
if ($isValid) {
38
return $next($request);
39
} else {
40
return new Response('You are not Twilio :(', 403);
41
}
42
}
43
}
44

Apply the request validation middleware to webhooks

apply-the-request-validation-middleware-to-webhooks page anchor

Apply a custom Twilio request validation middleware to all Lumen routes used for Twilio webhooks.

To use the middleware with your routes, first, you must add the middleware to bootstrap/app.php in the Register Middleware section:

1
$app->routeMiddleware([
2
'TwilioRequestValidator' => App\Http\Middleware\TwilioRequestValidator::class,
3
]);

Then you must add the middleware to each route as shown here.

Create Lumen routes to handle Twilio requests.

create-lumen-routes-to-handle-twilio-requests page anchor

Creates a route for /voice and /message to handle the respective webhooks.

1
<?php
2
3
use Illuminate\Http\Request;
4
use Twilio\TwiML\MessagingResponse;
5
use Twilio\TwiML\VoiceResponse;
6
7
// Note: $app was changed for $router since Lumen 5.5.0
8
// Reference: https://lumen.laravel.com/docs/5.5/upgrade#upgrade-5.5.0
9
10
$router->post('voice', ['middleware' => 'TwilioRequestValidator',
11
function() {
12
$twiml = new VoiceResponse();
13
$twiml->say('Hello World!');
14
15
return response($twiml)->header('Content-Type', 'text/xml');
16
}
17
]);
18
19
$router->post('message', ['middleware' => 'TwilioRequestValidator',
20
function(Request $request) {
21
$bodyLength = strlen($request->input('Body'));
22
23
$twiml = new MessagingResponse();
24
$twiml->message("Your text to me was $bodyLength characters long. ".
25
"Webhooks are neat :)");
26
27
return response($twiml)->header('Content-Type', 'text/xml');
28
}
29
]);
30

Use a tunnel for your local development environment in order to use live Twilio webhooks

use-a-tunnel-for-your-local-development-environment-in-order-to-use-live-twilio-webhooks page anchor

If your Twilio webhook URLs start with https:// instead of http://, your request validator may fail locally when you use ngrok(link takes you to an external page) or in production if your stack terminates SSL connections upstream from your app. This is because the request URL that your Express application sees does not match the URL Twilio used to reach your application.

To fix this for local development with ngrok, use ngrok http 3000 to accept requests on your webhooks instead of ngrok https 3000.


Disable request validation during testing

disable-request-validation-during-testing page anchor

If you write tests for your Lumen routes those tests may fail for routes where you use your Twilio request validation middleware. Any requests your test suite sends to those routes will fail the middleware validation check.

To fix this problem we recommend adding an extra check in your middleware, like shown here, telling it to only reject incoming requests if your app is running in production.

Disable Twilio request validation when testing

disable-twilio-request-validation-when-testing page anchor

Use APP_ENV environment variable to disable request validation.

1
<?php
2
3
namespace App\Http\Middleware;
4
5
use Closure;
6
use Illuminate\Http\Response;
7
use Twilio\Security\RequestValidator;
8
9
class TwilioRequestValidator
10
{
11
/**
12
* Handle an incoming request.
13
*
14
* @param \Illuminate\Http\Request $request
15
* @param \Closure $next
16
* @return mixed
17
*/
18
public function handle($request, Closure $next)
19
{
20
if (env('APP_ENV') === 'test') {
21
return $next($request);
22
}
23
24
// Be sure TWILIO_AUTH_TOKEN is set in your .env file.
25
// You can get your authentication token in your twilio console https://www.twilio.com/console
26
$requestValidator = new RequestValidator(env('TWILIO_AUTH_TOKEN'));
27
28
$isValid = $requestValidator->validate(
29
$request->header('X-Twilio-Signature'),
30
$request->fullUrl(),
31
$request->toArray()
32
);
33
34
if ($isValid) {
35
return $next($request);
36
} else {
37
return new Response('You are not Twilio :(', 403);
38
}
39
}
40
}
41

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.

Learn more about setting up your PHP development environment.

To learn more about securing your Lumen application in general, check out the security considerations page in the official Lumen docs(link takes you to an external page).

Need some help?

Terms of service

Copyright © 2024 Twilio Inc.