Creating Signature and Nonce for OAuth (Ruby)

倾然丶 夕夏残阳落幕 提交于 2019-11-30 11:10:06

问题


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.


回答1:


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.




回答2:


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.




回答3:


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



来源:https://stackoverflow.com/questions/4524911/creating-signature-and-nonce-for-oauth-ruby

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!