Create a gist now

Instantly share code, notes, and snippets.

What would you like to do?
A utility for signing an url using OAuth in a way that's convenient for debugging
require 'oauth_util.rb'
require 'net/http'
o =
o.consumer_key = 'examplek9SGJUTUpocjZ5QjBJmQ9WVdrOVVFNHdSR2x1TkhFbWNHbzlNQS0tJnM9Y29uc3VtkZXJzZWNyZXQmeD0yYg--';
o.consumer_secret = 'exampled88d4109c63e778dsadcdd5c1875814977';
url = '*';
parsed_url = URI.parse( url )
Net::HTTP.start( ) { | http |
req = "#{ parsed_url.path }?#{ o.sign(parsed_url).query_string }"
response = http.request(req)
print response.read_body
# A utility for signing an url using OAuth in a way that's convenient for debugging
# Note: the standard Ruby OAuth lib is here
# License:
# Usage: see example.rb below
require 'uri'
require 'cgi'
require 'openssl'
require 'base64'
class OauthUtil
attr_accessor :consumer_key, :consumer_secret, :token, :token_secret, :req_method,
:sig_method, :oauth_version, :callback_url, :params, :req_url, :base_str
def initialize
@consumer_key = ''
@consumer_secret = ''
@token = ''
@token_secret = ''
@req_method = 'GET'
@sig_method = 'HMAC-SHA1'
@oauth_version = '1.0'
@callback_url = ''
# openssl::random_bytes returns non-word chars, which need to be removed. using alt method to get length
# ref
def nonce 5 ) { rand(256) }.pack('C*').unpack('H*').first
def percent_encode( string )
# ref
return URI.escape( string,"[^#{URI::PATTERN::UNRESERVED}]") ).gsub('*', '%2A')
# @ref
def signature
key = percent_encode( @consumer_secret ) + '&' + percent_encode( @token_secret )
# ref:
digest = 'sha1' )
hmac = OpenSSL::HMAC.digest( digest, key, @base_str )
# ref
Base64.encode64( hmac ).chomp.gsub( /\n/, '' )
# sort (very important as it affects the signature), concat, and percent encode
# @ref
# @ref
# @ref
def query_string
pairs = []
@params.sort.each { | key, val |
pairs.push( "#{ percent_encode( key ) }=#{ percent_encode( val.to_s ) }" )
pairs.join '&'
# organize params & create signature
def sign( parsed_url )
@params = {
'oauth_consumer_key' => @consumer_key,
'oauth_nonce' => nonce,
'oauth_signature_method' => @sig_method,
'oauth_timestamp' =>,
'oauth_version' => @oauth_version
# if url has query, merge key/values into params obj overwriting defaults
if parsed_url.query
@params.merge! CGI.parse( parsed_url.query )
# @ref
@req_url = parsed_url.scheme + '://' + + parsed_url.path
# create base str. make it an object attr for ez debugging
# ref
@base_str = [
percent_encode( req_url ),
# normalization is just x-www-form-urlencoded
percent_encode( query_string )
].join( '&' )
# add signature
@params[ 'oauth_signature' ] = signature
return self

tylr commented Aug 25, 2010

I'm interested in using this because the OAuth gem is horrid, and this turned up in google. I get either an error stating "no oauth_token parameter found" or when I add the param "Invalid signature. Expected signature base string: GET&http%3A%2F%2Fapi"

Any tips or advice?

I got

  Please provide valid credentials

mhookey commented May 16, 2012

Suggested fix to ensure single url params aren't pushed to arrays (otherwise seems to have challenges when using params such as count=x&format=json) ... I'm no guru so maybe I was using it incorrectly at first..

# if url has query, merge key/values into params obj overwriting defaults
if parsed_url.query
  CGI.parse( parsed_url.query ).each do |k,v|
    if v.is_a?(Array) && v.count == 1
      @params[k] = v.first
      @params[k] = v

Has anyone tested this recently? I've just tried to use this code, having only substituted my own consumer key and secret and I get OST_OAUTH_SIGNATURE_INVALID_ERROR, "Please provide valid credentials".


  1. Apply change described by mhookey above to sign method of oauth_util.rb
  2. If you're coming from the YDN BOSS example.rb, change "urlurl = url + ..." (line 8) to "url = url + ..."

@tylr yeah, no oauth_token is being sent at all

datnt commented Nov 14, 2013

@asfarley , and @tylr

I had applied the above code and success, please refer to my detailed document here:

P/S: Note that, the oauth_util.rb does not support to get access token, it only support for sending request to yahoo API, after you had received the access_token, and access_token_secret

Zeokat commented Mar 7, 2014

For Zeokat deal with OAuth is always painfull, thanks for the code.

wvidana commented Apr 28, 2014

Dealing with oauth_token:

  • first send a request for tokens (your API provider should tell you how)
  • edit oauth_lib.rb, in the method sign (line 64) add 'oauth_token' => 'your token' to the hashtab, between oauth_timestamp and oauth_version (it should be ordered in alphabetical order)
  • In your main program initialize the o.token and o.token_secret variables with your values

Has anyone gotten this to work with Twitter's API? I've made all the updates outlined in the comments and still get 215 bad authentication data errors.

gxbe commented Sep 18, 2014

If you're using JRUBY then there's an easier option. This should get you started.

require 'java'
require 'lib/commons-codec-1.9.jar'
require 'lib/signpost-core-'

import 'org.apache.commons.codec.binary.Base64'
import 'oauth.signpost.basic.DefaultOAuthConsumer'


class YahooContacts
def initialize(consumer_key, consumer_secret, token, token_secret)
@consumer_key, @consumer_secret, @token, @token_secret = consumer_key, consumer_secret, token, token_secret
def get_guid
consumer =, @consumer_secret)
url ="")
request = url.open_connection
consumer.set_token_with_secret(TEST_TOKEN, TEST_TOKEN_SECRET)

Line 44 in oauth_util.rb should be changed to

digest = 'sha1' )

Because you will get a message saying "Digest::Digest is deprecated; Use Digest"

samjewell commented May 15, 2017

The API I'm working with requires the Auth params to be added to the header, as per the option in Postman:

request["authorization"] = 'OAuth oauth_consumer_key=\"MyKey\",oauth_token=\"MyToken\",oauth_signature_method=\"HMAC-SHA1\",oauth_timestamp=………etcetc

Did anyone manage to modify this script to also add that authorization header to the request?

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment