Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Creating Signature and Nonce for OAuth (Ruby)

I'm looking to access SmugMug's API from my application to grab users' albums and images (the users have been authenticated via ruby's OmniAuth).

According to SmugMug's OAuth API, OAuth requires six parameters.

I can get the token with OmniAuth, and the timestamp should be easy (Time.now.to_i right?). There are two things that I don't know how to generate -- the oauth_nonce and the oauth_signature.

According to the oauth docs, I generate the nonce via the timestamp, but how exactly would I do that? Does it need to be a certain length and limited to certain characters?

And of course the signature. How would I generate a HMAC-SHA1 sig with ruby? I know the oauth gem can do it, but I'd rather generate it myself to use with OmniAuth. Looking at the code, I'm having trouble deciphering how the oauth gem generates the sig.

Thank you for any help.

like image 956
kmurph79 Avatar asked Dec 24 '10 07:12

kmurph79


3 Answers

For the signature:

def sign( key, base_string )
  digest = OpenSSL::Digest::Digest.new( 'sha1' )
  hmac = OpenSSL::HMAC.digest( digest, key, base_string  )
  Base64.encode64( hmac ).chomp.gsub( /\n/, '' )
end#def

You don't have to generate the nonce from the timestamp, but it can make sense since the timestamp is obviously unique, so it makes a good starting input for any randomisation function.

I use this, (that I got from another question on here and modified)

def nonce
  rand(10 ** 30).to_s.rjust(30,'0')
end#def

but you can use anything that generates a unique string.

See this gist by erikeldridge on github and Beginner’s Guide to OAuth for more

Edit

I've since found there's a better way to generate random strings in the Ruby standard library, SecureRandom.

like image 107
ian Avatar answered Nov 13 '22 01:11

ian


A nonce can also be simply a large-ish, properly random number - for example, using Ruby's SecureRandom class (don't use 'rand'):

require 'securerandom'

...

nonce = SecureRandom.hex()

This generates a 16-byte random number in hex format.

like image 25
JohnK Avatar answered Nov 13 '22 02:11

JohnK


Why you don't just use the Oauth ruby gems to do that ?

like image 1
shingara Avatar answered Nov 13 '22 00:11

shingara