Ruby API请求中的Yahoo Oauth - 签名无效

时间:2014-08-18 01:41:48

标签: ruby-on-rails ruby api oauth yahoo-api

我已经成功获得了访问令牌和访问权限。现在,我尝试使用OAuth信息发出API请求。

我跟随雅虎文档(不是很有帮助): https://developer.yahoo.com/oauth/guide/oauth-make-request.html https://developer.yahoo.com/oauth/guide/oauth-signing.html

另外,我试图密切关注这个例子: https://gist.github.com/cheenu/1469815

以下是代码:(为方便起见,我拆分了长网址)

require 'cgi'
require 'base64'
require 'openssl'

url = "http://fantasysports.yahooapis.com/fantasy/v2/game/nfl"
parameters = "format=json
  &realm=yahooapis.com
  &oauth_consumer_key=#{Rails.application.secrets.yhoo_consumer_key}
  &oauth_nonce=#{SecureRandom.hex}
  &oauth_signature_method=HMAC-SHA1
  &oauth_timestamp=#{Time.now.to_i}
  &oauth_token=#{ApiVar.final_oauth_token} #the access token
  &oauth_version=1.0"

base_string = 'GET&' + CGI.escape(url) + '&' + CGI.escape(parameters)

oauth_signature = CGI.escape(Base64.encode64("#{OpenSSL::HMAC.digest('sha1', ApiVar.final_oauth_secret + "&", base_string)}").chomp)

#ApiVar.final_oauth_secret is the access token secret - is that what I should be putting there?

testable_url = url + '?' + parameters + '&oauth_signature=' + oauth_signature
p testable_url
response = HTTParty.get(testable_url)

我的回复给了我" signature_invalid。"

我做错了什么?

谢谢!

2 个答案:

答案 0 :(得分:3)

    url = "http://fantasysports.yahooapis.com/fantasy/v2/league/{league-key}/players"
    parameters = "format=json&oauth_consumer_key=#{Rails.application.secrets.yhoo_consumer_key}&oauth_nonce=#{SecureRandom.hex}&oauth_signature_method=HMAC-SHA1&oauth_timestamp=#{Time.now.to_i}&oauth_token=#{ApiVar.final_oauth_token}&oauth_version=1.0&realm=yahooapis.com"
    base_string = 'GET&' + CGI.escape(url) + '&' + CGI.escape(parameters)
    secret = "#{Rails.application.secrets.yhoo_consumer_secret}&#{ApiVar.final_oauth_secret}"
    oauth_signature = CGI.escape(Base64.encode64("#{OpenSSL::HMAC.digest('sha1', secret, base_string)}").chomp)
    testable_url = url + '?' + parameters + '&oauth_signature=' + oauth_signature
    p testable_url
    response = HTTParty.get(testable_url)

#{Rails.application.secrets.yhoo_consumer_secret}&#{ApiVar.final_oauth_secret}" - correct secret key 

参数必须按字母顺序排序!此外,秘密密钥是雅虎消费者秘密加上最终的oauth秘密!

答案 1 :(得分:0)

我可以看到第一件有问题的事情是 paremeters 有很多你不想要的空白。请尝试以下方法:

parameters = "format=json" +
  "&realm=yahooapis.com" +
  "&oauth_consumer_key=#{Rails.application.secrets.yhoo_consumer_key}" +
  "&oauth_nonce=#{SecureRandom.hex}" +
  "&oauth_signature_method=HMAC-SHA1" +
  "&oauth_timestamp=#{Time.now.to_i}" +
  "&oauth_token=#{ApiVar.final_oauth_token}" +
  "&oauth_version=1.0"

另一个问题是,当您创建签名时,我不相信您的密钥需要添加&符号:

oauth_signature = CGI.escape(Base64.encode64("#{OpenSSL::HMAC.digest('sha1', ApiVar.final_oauth_secret, base_string)}").chomp)