In this guide we'll cover how to secure your Lumen 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 RequestValidator
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!
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.
Use Twilio SDK RequestValidator to validate webhook requests.
1<?php23namespace App\Http\Middleware;45use Closure;6use Illuminate\Http\Response;7use Twilio\Security\RequestValidator;89class TwilioRequestValidator10{11/**12* Handle an incoming request.13*14* @param \Illuminate\Http\Request $request15* @param \Closure $next16* @return mixed17*/18public 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/console22$requestValidator = new RequestValidator(env('TWILIO_AUTH_TOKEN'));2324$requestData = $request->toArray();2526// Switch to the body content if this is a JSON request.27if (array_key_exists('bodySHA256', $requestData)) {28$requestData = $request->getContent();29}3031$isValid = $requestValidator->validate(32$request->header('X-Twilio-Signature'),33$request->fullUrl(),34$requestData35);3637if ($isValid) {38return $next($request);39} else {40return new Response('You are not Twilio :(', 403);41}42}43}44
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.
Creates a route for /voice and /message to handle the respective webhooks.
1<?php23use Illuminate\Http\Request;4use Twilio\TwiML\MessagingResponse;5use Twilio\TwiML\VoiceResponse;67// Note: $app was changed for $router since Lumen 5.5.08// Reference: https://lumen.laravel.com/docs/5.5/upgrade#upgrade-5.5.0910$router->post('voice', ['middleware' => 'TwilioRequestValidator',11function() {12$twiml = new VoiceResponse();13$twiml->say('Hello World!');1415return response($twiml)->header('Content-Type', 'text/xml');16}17]);1819$router->post('message', ['middleware' => 'TwilioRequestValidator',20function(Request $request) {21$bodyLength = strlen($request->input('Body'));2223$twiml = new MessagingResponse();24$twiml->message("Your text to me was $bodyLength characters long. ".25"Webhooks are neat :)");2627return response($twiml)->header('Content-Type', 'text/xml');28}29]);30
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 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
.
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.
Use APP_ENV environment variable to disable request validation.
1<?php23namespace App\Http\Middleware;45use Closure;6use Illuminate\Http\Response;7use Twilio\Security\RequestValidator;89class TwilioRequestValidator10{11/**12* Handle an incoming request.13*14* @param \Illuminate\Http\Request $request15* @param \Closure $next16* @return mixed17*/18public function handle($request, Closure $next)19{20if (env('APP_ENV') === 'test') {21return $next($request);22}2324// 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/console26$requestValidator = new RequestValidator(env('TWILIO_AUTH_TOKEN'));2728$isValid = $requestValidator->validate(29$request->header('X-Twilio-Signature'),30$request->fullUrl(),31$request->toArray()32);3334if ($isValid) {35return $next($request);36} else {37return 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.