Hello fellow Rubyist, I see you have your shiny new Twilio application written, perhaps a Rails app or Sinatra, like in our Ruby quickstart guide. Before you hit that deploy button, you need to stop and ask yourself a couple of questions about that app. Do your webhooks expose sensitive data when they receive a request? Do they change data within your system? If your answer to either of those questions is yes, then you should be making sure that your app only responds to requests that come from Twilio.

You can do this using Twilio’s request validation. Twilio will cryptographically sign all requests that it makes to your application. We create a signature using your callback URL, the request parameters and your auth token then add an HTTP header, X-Twilio-Signature, containing that signature. On your server, you can follow the same process to create the signature and check if it matches, if it doesn’t the request can be rejected. There are more details available in the security documentation.

Until recently, if you wanted to secure your endpoints using the twilio-ruby gem you could use the Twilio::Util::RequestValidator class. The gem documentation has an example of how to do this, but you have to adapt that to your web framework of choice. If only there was a simple, one line way to add request validation to your app.

Middleware to the Rescue

Rack is an interface for web applications in Ruby and is the foundation on which most of the popular Ruby web frameworks including Rails, Sinatra and even Camping. Further to this, Rack provides support for middleware, filters that can intercept a request and alter the response from a web application.

Middleware is an ideal place to validate our incoming requests from Twilio and other platforms have been using them to simplify that job for quite a while now. For example, Node.js developers have had request validation with middleware for the Express framework since the start of the year. And now I’m pleased to tell you that, with version 3.12.0 of the twilio-ruby gem, there is an easy to use Rack middleware that you can drop into your apps in order to validate that your incoming requests are from Twilio.

So, let’s see how easy it is to put this new middleware to work in a Rack application application.

An Example Application

To show how easy it is to use this middleware, let’s put together a very quick application using Sinatra.

First we need to install the gems that we’ll need.