Skip to contentSkip to navigationSkip to topbar
Rate this page:
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.


_43
<?php
_43
_43
namespace App\Http\Middleware;
_43
_43
use Closure;
_43
use Illuminate\Http\Response;
_43
use Twilio\Security\RequestValidator;
_43
_43
class TwilioRequestValidator
_43
{
_43
/**
_43
* Handle an incoming request.
_43
*
_43
* @param \Illuminate\Http\Request $request
_43
* @param \Closure $next
_43
* @return mixed
_43
*/
_43
public function handle($request, Closure $next)
_43
{
_43
// Be sure TWILIO_AUTH_TOKEN is set in your .env file.
_43
// You can get your authentication token in your twilio console https://www.twilio.com/console
_43
$requestValidator = new RequestValidator(env('TWILIO_AUTH_TOKEN'));
_43
_43
$requestData = $request->toArray();
_43
_43
// Switch to the body content if this is a JSON request.
_43
if (array_key_exists('bodySHA256', $requestData)) {
_43
$requestData = $request->getContent();
_43
}
_43
_43
$isValid = $requestValidator->validate(
_43
$request->header('X-Twilio-Signature'),
_43
$request->fullUrl(),
_43
$requestData
_43
);
_43
_43
if ($isValid) {
_43
return $next($request);
_43
} else {
_43
return new Response('You are not Twilio :(', 403);
_43
}
_43
}
_43
}


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:


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

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.


_29
<?php
_29
_29
use Illuminate\Http\Request;
_29
use Twilio\TwiML\MessagingResponse;
_29
use Twilio\TwiML\VoiceResponse;
_29
_29
// Note: $app was changed for $router since Lumen 5.5.0
_29
// Reference: https://lumen.laravel.com/docs/5.5/upgrade#upgrade-5.5.0
_29
_29
$router->post('voice', ['middleware' => 'TwilioRequestValidator',
_29
function() {
_29
$twiml = new VoiceResponse();
_29
$twiml->say('Hello World!');
_29
_29
return response($twiml)->header('Content-Type', 'text/xml');
_29
}
_29
]);
_29
_29
$router->post('message', ['middleware' => 'TwilioRequestValidator',
_29
function(Request $request) {
_29
$bodyLength = strlen($request->input('Body'));
_29
_29
$twiml = new MessagingResponse();
_29
$twiml->message("Your text to me was $bodyLength characters long. ".
_29
"Webhooks are neat :)");
_29
_29
return response($twiml)->header('Content-Type', 'text/xml');
_29
}
_29
]);


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.


_40
<?php
_40
_40
namespace App\Http\Middleware;
_40
_40
use Closure;
_40
use Illuminate\Http\Response;
_40
use Twilio\Security\RequestValidator;
_40
_40
class TwilioRequestValidator
_40
{
_40
/**
_40
* Handle an incoming request.
_40
*
_40
* @param \Illuminate\Http\Request $request
_40
* @param \Closure $next
_40
* @return mixed
_40
*/
_40
public function handle($request, Closure $next)
_40
{
_40
if (env('APP_ENV') === 'test') {
_40
return $next($request);
_40
}
_40
_40
// Be sure TWILIO_AUTH_TOKEN is set in your .env file.
_40
// You can get your authentication token in your twilio console https://www.twilio.com/console
_40
$requestValidator = new RequestValidator(env('TWILIO_AUTH_TOKEN'));
_40
_40
$isValid = $requestValidator->validate(
_40
$request->header('X-Twilio-Signature'),
_40
$request->fullUrl(),
_40
$request->toArray()
_40
);
_40
_40
if ($isValid) {
_40
return $next($request);
_40
} else {
_40
return new Response('You are not Twilio :(', 403);
_40
}
_40
}
_40
}


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).


Rate this page: