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.
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:
$app->routeMiddleware([ 'TwilioRequestValidator' => App\Http\Middleware\TwilioRequestValidator::class, ]);
Then you must add the middleware to each route as shown here.
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 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.
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.