401 未经授权来自 Twitter API,在 Ruby 中使用 oauth gem

401 unauthorized from Twitter API with oauth gem in Ruby

这是我第一次使用 Twitter API。 我正在使用以下工具:

我从 Twitter 获得了密钥和秘密。

我从 example on Twitter 复制并粘贴到 Ruby。

=begin
code taken directly from the example at 
https://dev.twitter.com/oauth/overview/single-user
=end

require 'oauth'
consumer_key, \
  consumer_secret = [
    'CONSUMER_KEY', 
    'CONSUMER_SECRET'
].map { |key| ENV[key] }
raise "Some key undefined." unless [consumer_key, consumer_secret].all?

# Exchange your oauth_token and oauth_token_secret for an AccessToken instance.
def prepare_access_token(oauth_token, oauth_token_secret)
    consumer = OAuth::Consumer.new("APIKey", "APISecret", { :site => "https://api.twitter.com", :scheme => :header })

    # now create the access token object from passed values
    token_hash = { :oauth_token => oauth_token, :oauth_token_secret => oauth_token_secret }
    access_token = OAuth::AccessToken.from_hash(consumer, token_hash )

    return access_token
end

# Exchange our oauth_token and oauth_token secret for the AccessToken instance.
access_token = prepare_access_token(consumer_key, consumer_secret)
p access_token

# use the access token as an agent to get the home timeline
response = access_token.request(:get, "https://api.twitter.com/1.1/statuses/home_timeline.json")
p response

=begin   

|| #<OAuth::AccessToken:0x000000021ed938 
@token="redacted", @secret="redacted", 
@consumer=#<OAuth::Consumer:0x000000021edb68 
@key="APIKey", 
@secret="APISecret", @options={:signature_method=>"HMAC-SHA1", 
:request_token_path=>"/oauth/request_token", 
:authorize_path=>"/oauth/authorize", 
:access_token_path=>"/oauth/access_token", 
:proxy=>nil, :scheme=>:header, 
:http_method=>:post, :oauth_version=>"1.0", 
:site=>"https://api.twitter.com"}>, 
@params={:oauth_token=>"redacted", :oauth_token_secret=>"redacted"}>
|| #<Net::HTTPUnauthorized 401 Authorization Required readbody=true>
=end

我尝试了什么:

感谢从这里开始的建议。

更新 OAuth Tool on Twitter Developer returns curl 执行的预期结果:

curl --get 'https://api.twitter.com/1.1/statuses/home_timeline.json' --header 'Authorization: OAuth oauth_consumer_key="redacted", oauth_nonce="redacted", oauth_signature="redacted", oauth_signature_method="HMAC-SHA1", oauth_timestamp="1463742270", oauth_token="redacted", oauth_version="1.0"' --verbose

返回预期数据。

[{"created_at":"Fri May 20 11:05:21 +0000 2016","id":733614584754515968,"id_str":
"733614584754515968","text":"Three Skills Every New Programmer Should Learn https://t. co/1p9AxO5JPg via @sitepointdotcom","truncated":false,"entities":{"hashtags":[],"symbols" (truncated)…

在这一行中,您应该将 "APIKey" 和 "APISecret" 替换为您从 CONSUMER_* 环境变量中提取的内容。

consumer = OAuth::Consumer.new("APIKey", "APISecret", { :site => "https://api.twitter.com", :scheme => :header })

来自 Twitter 的示例代码对我来说效果很好。错误的消费者密钥肯定会给你 401。