尝试获取access_token时,OAuth-Ruby gem返回401

时间:2018-01-08 03:21:28

标签: ruby-on-rails ruby twitter oauth twitter-oauth

我尝试在我的应用上实施OAuth作为登录选项。大多数提供商都做得很好,但Twitter给我带来了很多麻烦。

我能够获得请求令牌并发送oauth_verifier。但是,在此之后,我无法使用oauth-ruby gem获得Twitter的授权回复。

我无法在我的设置中使用Devise或Omniauth。

这是我的代码的极简主义和注释版本:

# controllers/authorizations_controller.rb
# route: POST /auth/twitter
def create
    if params[:oauth_token].blank? # This gets hit as the first part of the process.  This entire block works as expected
      oauth = Oauth::Twitter.get_token
      session['oauth_token'] = oauth

      render json: { oauth_token: oauth.token } # The user authorizes and is redirected (to this same action)
    else # Once authorized, the oauth_token params is set and this gets executed
      Oauth::Twitter.new(params, session['oauth_token'])
    end
end
# models/oauth/twitter.rb
class Oauth::Twitter < Oauth::Base
  def self.get_token # This seems to work
    consumer.get_request_token(oauth_callback: 'http://localhost:3000') # This must be set to 'http://localhost:3000' per my frontend library
  end

  def initialize(params, request_token_hash)
    consumer = self.class.consumer

    request_token = OAuth::RequestToken.from_hash(consumer, request_token_hash) # This returns the expected RequestToken object
    request_token.get_access_token(oauth_verifier: params[:oauth_verifier]) # This is where the 401 is thrown.  params['oauth_verifier'] is confirmed to be set.
  end

  private

  def self.consumer
    OAuth::Consumer.new(
      Rails.application.secrets['TWITTER_KEY'],
      Rails.application.secrets['TWITTER_SECRET'], 
      :site => "https://api.twitter.com"
    )
  end
end

不幸的是,除了抛出的“401授权要求”之外,我没有获得更多信息。在使用相同OAuth gem的Twitter docs for sign-in via OAuth(更具体地,oauth/access_token端点)和a similar example之间,我无法看到我的错误所在。

0 个答案:

没有答案