Skip to content

Request Validator

Tom edited this page Jul 10, 2017 · 2 revisions

An important part of any secure Twilio application is correctly performing request validation. For a complete description of how request validation works, see the Twilio security documentation. The basic idea is that Twilio builds a string based on the parameters sent to your server and then creates a hash of this string using your account's AuthToken (a shared secret). Twilio sends this hash to your server as a header in its request. You can then build the same string and create the same hash as Twilio did, and compare yours to the one Twilio sent to determine the authenticity of the request.

The RequestValidator class simplifies this process:

# First, instantiate a RequestValidator object with your account's AuthToken.
validator = Twilio::Security::RequestValidator.new(@auth_token)

# Then gather the data required to validate the request. The following works in
# sinatra, and something similar should work in any rack-based environment.

# Build the URI for this request, including query string params if any.
uri = request.original_url

# Collect all parameters passed from Twilio.
params = env['rack.request.form_hash']
# If GET, use rack.request.query_hash instead:
# params = env['rack.request.query_hash']

# Grab the signature from the HTTP header.
signature = env['HTTP_X_TWILIO_SIGNATURE']

# Finally, call the validator's #validate method.
validator.validate uri, params, signature #=> true if the request is from Twilio
Clone this wiki locally