Created
April 28, 2020 18:53
-
-
Save kenjij/e4d649572e6292efabbe3e411daa168b to your computer and use it in GitHub Desktop.
[Twilio] Validate Signature of Request (in pure Ruby)
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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