Last active
December 17, 2019 22:38
-
-
Save aliang/2cfea1dbd4ddc90cd3e5 to your computer and use it in GitHub Desktop.
Mandrill webhook verifier, in Ruby
This file contains 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
class MandrillSignatureVerifier | |
def initialize(key, url, params, signature) | |
@key = key | |
@url = url | |
@params = params | |
@signature = signature | |
end | |
# Return true if the signature matches | |
def verified? | |
sign == @signature | |
end | |
def sign | |
data = @url | |
data += @params.sort.join | |
Base64.strict_encode64( | |
OpenSSL::HMAC.digest( | |
OpenSSL::Digest.new('sha1'), @key, data | |
) | |
) | |
end | |
def self.verified?(key, url, params, signature) | |
self.new(key, url, params, signature).verify | |
end | |
def self.sign(key, url, params) | |
self.new(key, url, params, nil).sign | |
end | |
end |
This file contains 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
# And here's how you'd use it, general idea from https://gist.github.com/joost/6460736 in part | |
class WebhooksController < ActionController::Base | |
WEBHOOK_KEY = "some_key" # You could also use an API request to lookup the key | |
before_filter :verify_request_signature | |
# See: http://help.mandrill.com/entries/23704122-Authenticating-webhook-requests | |
def verify_request_signature | |
verifier = MandrillParser::SignatureVerifier.new(WEBHOOK_KEY, request.url, request.request_parameters, request.headers['X-Mandrill-Signature']) | |
head :unauthorized unless verifier.verify | |
end | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment