Created
May 23, 2018 21:55
-
-
Save virtualstyle/fa67089188e89812041bb53e7974cbfa to your computer and use it in GitHub Desktop.
Creating HMAC auth header in ruby for use in HTTParty header
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
require 'base64' | |
def auth_header(path: nil, method: 'get', body: nil) | |
date = Time.zone.now.httpdate | |
# ORDERED list of headers in request to be signed | |
auth_headers = 'host date' | |
if ['put', 'post'].include? method.downcase | |
auth_headers += ' content-type content-length' | |
end | |
# The complete request, with headers in correct order, to be HMAC'd | |
dataToSign = "(request-target): #{method.downcase} #{@url}#{path}\n" + | |
"host: #{@host}\n" + | |
"date: #{date}"; | |
# If we're sending a body, content type and length are required | |
if ['put', 'post'].include? method.downcase | |
dataToSign += "\ncontent-type: application/json\n" + | |
"content-length: #{body.length}\n" + | |
body | |
end | |
# HMAC and base64 encode, then build the auth header | |
hmac = Base64.strict_encode64(OpenSSL::HMAC.digest(OpenSSL::Digest.new('sha256'), @api_secret, dataToSign)) | |
authorization = "Signature keyId=\"#{@api_key}\",algorithm=\"hmac-sha256\",headers=\"(request-target) #{auth_headers}\",signature=\"#{hmac}\"" | |
# Minimum required headers | |
headers = | |
{ | |
'Host' => @host, | |
'Date' => date | |
} | |
# Additional headers required when sending a request body | |
if ['put', 'post'].include? method.downcase | |
headers.merge!({ | |
'Content-Type' => 'application/json', | |
'Content-Length' => "#{body.length}" | |
}) | |
end | |
# Auth header has to be last, order matters to HMAC signing | |
headers.merge!({'Authorization' => authorization}) | |
end | |
# Working Curl CLI for reference/test | |
# exec 'curl -Iv -X GET -H "User-Agent:" -H "Accept:" -H "Date: ' + date + '" -H "Authorization: ' + authorization + '" ' + @url + 'groups' |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment