Skip to content

Instantly share code, notes, and snippets.

@kenjij
Created April 28, 2020 18:53
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save kenjij/e4d649572e6292efabbe3e411daa168b to your computer and use it in GitHub Desktop.
Save kenjij/e4d649572e6292efabbe3e411daa168b to your computer and use it in GitHub Desktop.
[Twilio] Validate Signature of Request (in pure Ruby)
require 'base64'
require 'openssl'
# See: https://www.twilio.com/docs/usage/security#validating-requests
#
# Example of AWS API Gateway (HTTP) + Lambda
def is_twilio_request_valid?(event)
# Create a string that is your URL with the full query string
url = "https://#{event['headers']['host']}#{event['rawPath']}"
# Sort the list of POST variables by the parameter name
body = event['body']
body = Base64.decode64(body) if event['isBase64Encoded']
h = URI.decode_www_form(body).to_h
a = h.keys.sort.map { |k| "#{k}#{h[k]}" }
# Append each POST variable, name and value, to the string with no delimiters
str = "#{url}#{a.join}"
# Hash the resulting string using HMAC-SHA1, using your AuthToken Primary as the key
key = ENV['TWILIO_AUTHTOKEN_PRIMARY']
sig = Base64.strict_encode64(OpenSSL::HMAC.digest('sha1', key, str))
event['headers']['x-twilio-signature'] == sig
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment