Last active
February 28, 2023 14:58
-
-
Save diogocera/d6dc345ed414c0473001f31c3776415c to your computer and use it in GitHub Desktop.
Create OAuth1.0 authentication header string
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 OAuth1 | |
class << self | |
def oauth_header(uri:, method:, access_token:, access_secret:, consumer_key:, consumer_secret:) | |
header = { | |
'oauth_consumer_key' => consumer_key, | |
'oauth_token' => access_token, | |
'oauth_nonce' => generate_nonce, | |
'oauth_signature_method' => 'HMAC-SHA256', | |
'oauth_timestamp' => Time.now.to_i, | |
'oauth_version' => '1.0' | |
} | |
signature_base = signature_base_string(method.to_s.upcase, uri, header) | |
signing_key = signature_key_string(consumer_secret, access_secret) | |
header['oauth_signature'] = sign(signing_key, signature_base) | |
stringified_header(header) | |
end | |
private | |
def generate_nonce | |
ERB::Util.url_encode(SecureRandom.base64) | |
end | |
def signature_base_string(method, uri, params) | |
encoded_params = params.sort_by { |k, _| k }.map{ |k, v| "#{k}=#{v.to_s}" }.join("\&") | |
"#{method}\&#{ERB::Util.url_encode(uri)}\&#{ERB::Util.url_encode(encoded_params)}" | |
end | |
def signature_key_string(consumer_secret, access_secret) | |
"#{consumer_secret}\&#{access_secret}" | |
end | |
def sign(key, base_string) | |
ERB::Util.url_encode(Base64.strict_encode64(OpenSSL::HMAC.digest('sha256', key, base_string))) | |
end | |
def stringified_header(header) | |
stringified_header = header.sort_by { |k, _| k }.map{ |k, v| "#{k}=\"#{v.to_s}\"" }.join(",") | |
"OAuth #{stringified_header}" | |
end | |
end | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment