【问题标题】:Encoding a GET using OAuth in Ruby Twitter API在 Ruby Twitter API 中使用 OAuth 对 GET 进行编码
【发布时间】:2012-01-14 14:00:55
【问题描述】:

我正在尝试编写简单的 Ruby on Rails Web 应用程序,该应用程序通过 oAuth 登录 Twitter 并获取用户的关注者列表,不使用现有的 oAuth 库。使用他们在https://dev.twitter.com/docs/auth/oauth 的指南,我设法让登录正常工作,因此有了后续的 outh_token 和 oauth_token_secret。但是,当尝试对登录用户的关注者的 GET 请求进行编码时,我不断收到 401“此方法需要身份验证”。

使用我的代码及其示例数据,我可以看到我正在正确生成 oauth_signature。我可能错误地生成了 signature_base_string,但是在登录时看到它可以正常工作,我看不出第二次怎么会出错。方法是类的一部分,因此消费者密钥和秘密显然是类变量。

相关代码如下。 'followees' 中的 HTTP GET 的输出给出了 401。我希望这是一件非常明显的事情,我只是因为看了太久而错过了!我知道我将正确的值作为参数传递给函数。谢谢。

  def followees(auth_token, auth_token_secret, user_id)
    method = 'GET'
    base_uri = 'https://api.twitter.com/1/friends/ids.json'
    params = {
      'cursor' => '-1',
      'oauth_consumer_key' => @@consumer_key,
      'oauth_nonce' => generate_nonce, #not shown, no need!
      'oauth_signature_method' => 'HMAC-SHA1',
      'oauth_token' => auth_token,
      'oauth_timestamp' => Time.now.to_i.to_s,
      'oauth_version' => '1.0',
      'user_id' => user_id
    }
    signature_base_string = signature_base_string(method, base_uri, params)
    params['oauth_signature'] = url_encode(sign(@@consumer_secret + '&' + auth_token_secret, signature_base_string))
    header = header(params)
    base_uri += '?cursor=-1&user_id=' + user_id
    url = URI.parse(base_uri)
    http = Net::HTTP.new(url.host, 443)
    http.use_ssl = true
    resp, data = http.get(url.path, { 'Authorization' => header })
  end

  def signature_base_string(method, uri, params)
    encoded_params = params.sort.collect{ |k, v| url_encode("#{k}=#{v}") }.join("%26")
    method + '&' + url_encode(uri) + '&' + encoded_params
  end

  def url_encode(string)
    CGI::escape(string)
  end

  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 header(params)
    header = "OAuth "
    params.each do |k, v|
      header += "#{k}=\"#{v}\", "
    end
    header.slice(0..-3)
  end

【问题讨论】:

    标签: ruby-on-rails ruby oauth twitter


    【解决方案1】:

    想通了。需要休息一下才能退后一步!基本上,followees 的最后一行不包括 GET 数据,所以

    resp, data = http.get(url.path, { 'Authorization' => header })
    

    应该是

    resp, data = http.get(url.to_s, { 'Authorization' => header })
    

    我已经复制了 POST 的代码,因此这里只使用了 url.path。

    【讨论】:

      猜你喜欢
      • 2011-08-12
      • 2011-11-15
      • 2013-12-15
      • 2018-04-16
      • 2014-03-14
      • 1970-01-01
      • 2014-04-14
      • 1970-01-01
      • 2017-07-11
      相关资源
      最近更新 更多