Skip to content

Instantly share code, notes, and snippets.

@alanstevens
Last active December 24, 2015 12:19
Show Gist options
  • Save alanstevens/6796524 to your computer and use it in GitHub Desktop.
Save alanstevens/6796524 to your computer and use it in GitHub Desktop.
Ruby method for building an OAuth 1.0 request signature This validates against http://oauth.googlecode.com/svn/code/javascript/example/signature.html
module OAuth
def self.build_signature oauth
request_params = oauth[:request_params]
request_params[:oauth_consumer_key] = oauth[:oauth_consumer_key]
request_params[:oauth_nonce] = oauth[:oauth_nonce]
request_params[:oauth_signature_method] = 'HMAC-SHA1'
request_params[:oauth_timestamp] = oauth[:oauth_timestamp]
request_params[:oauth_token] = oauth[:oauth_token]
request_params[:oauth_version] = '1.0'
pairs = []
request_params.sort.each do | key, val |
pairs.push( "#{ percent_encode( key.to_s ) }=#{ percent_encode( val.to_s ) }" )
end
base_string = pairs.join '&'
encoded_string = percent_encode(base_string)
encoded_url = percent_encode(oauth[:url])
http_method = oauth[:http_method]
signature_string = "#{http_method}&#{encoded_url}&#{encoded_string}"
signature_key = "#{oauth[:consumer_secret]}&#{oauth[:token_secret]}"
hash = OpenSSL::HMAC.digest('sha1', signature_key, signature_string)
Base64.strict_encode64 hash
end
def self.percent_encode( value )
# see: https://gist.github.com/alanstevens/6813382
# and: http://en.wikipedia.org/wiki/Percent-encoding
URI::escape(value, /[^a-zA-Z0-9\-\.\_\~]/)
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment