我正在使用 ruby twitter gem 和 oauth 来访问用户的 Twitter 帐户。在我的代码中,我有:
unless @user.twitter_authd?
oauth = Twitter::OAuth.new('token', 'secret')
session[:twitter_request_token] = oauth.request_token.token
session[:twitter_request_secret] = oauth.request_token.secret
@twitter_auth_url = oauth.request_token.authorize_url
end
其中令牌和秘密插入了我的实际令牌和秘密。当我单击指向@twitter_auth_url 的链接时,我被带到 twitter 并被要求授予访问权限。我单击允许,然后 twitter 将我重定向到我的回调 URL http://www.mydomain.com/twitter_callback/?oauth_token=fmy2aMvnjVgaFrz37bJ4JuB8r5xN79gsgDQRG4BNY然后点击此代码:
oauth = Twitter::OAuth.new('token', 'secret')
logger.info("session[:twitter_request_token] = #{session[:twitter_request_token]}")
logger.info("session[:twitter_request_secret] = #{session[:twitter_request_secret]}")
oauth.authorize_from_request(session[:twitter_request_token], session[:twitter_request_secret])
session[:twitter_request_token] = nil
session[:twitter_request_secret] = nil
@user.update_attributes({
:twitter_token => oauth.access_token.token,
:twitter_secret => oauth.access_token.secret,
})
redirect_to root_path
推特请求令牌和秘密设置得很好。但是我最终遇到授权错误:
OAuth::Unauthorized in MainController#twitter_callback
401 Unauthorized
RAILS_ROOT: /Users/TAmoyal/Desktop/RoR_Projects/mls
Application Trace | Framework Trace | Full Trace
/Library/Ruby/Gems/1.8/gems/oauth-0.3.4/lib/oauth/consumer.rb:167:in `token_request'
/Library/Ruby/Gems/1.8/gems/oauth-0.3.4/lib/oauth/tokens/request_token.rb:14:in `get_access_token'
/Library/Ruby/Gems/1.8/gems/erwaller-twitter-0.6.13.1/lib/twitter/oauth.rb:29:in `authorize_from_request'
/Users/TAmoyal/Desktop/RoR_Projects/mls/app/controllers/main_controller.rb:70:in `twitter_callback'
代码在这一行失败:
oauth.authorize_from_request(session[:twitter_request_token], session[:twitter_request_secret])
当它尝试获取访问令牌时。您可以在此处查看 authorize_from_request 的源代码。我不确定为什么会这样。有人有想法吗?