简体   繁体   中英

Twitter gem authentication error (using omniauth-twitter token/secret)

I am trying to use the Twitter API through the Twitter gem and authenticate the call with the oauth token/secret of an logged on Twitter user previously authorised via omniauth-twitter.

Authentication for the Twitter user through omniauth-twitter is working fine. Storing the user's token and secret in a model the data is available to the controller through the current_twitter_user.

The following configuration (application only authentication) is working fine

Twitter.configure do |config|
  config.consumer_key = YOUR_CONSUMER_KEY
  config.consumer_secret = YOUR_CONSUMER_SECRET
  config.oauth_token = YOUR_OAUTH_TOKEN
  config.oauth_token_secret = YOUR_OAUTH_TOKEN_SECRET
end

Twitter.search("something")

Next I wanted to use the authenticated user's oauth_token and oauth_token_secret.

Following documentation for the Twitter gem I changed the twitter initializer to:

 Twitter.configure do |config|
   config.consumer_key = YOUR_CONSUMER_KEY
   config.consumer_secret = YOUR_CONSUMER_SECRET
 end

Then I created an action which includes the following code for test purposes:

if current_twitter_user

  tw_client = Twitter::Client.new(
    :oauth_token        => current_twitter_user.token,
    :oauth_token_secret => current_twitter_user.secret
  )

  @first_result = tw_client.search("something").results.first.text

end

The Twitter search call raises an "Twitter::Error::Unauthorized" exception. I checked token and secret provided by current_twitter_user and they seem good.

Any idea what I should be looking for or what I may be doing wrong? Help/ideas very much appreciated.

Many thanks, Eugen

Gems in use:

oauth (0.4.7) 
omniauth (1.1.4) 
omniauth-oauth (1.0.1) 
omniauth-twitter (0.0.16)
twitter (4.8.1) 

I finally identified the problem (after a night of sleep) - a silly configuration issue!

The Twitter gem picked up consumer key/secret pair from the twitter.rb initializer file while omniauth-twitter got it's pair through the environment (sorry, did not show this essential information in my question because that part 'worked').

I mixed up Twitter accounts and utilised two different Twitter applications on the consumer key part. Twitter and omniauth-twitter gems were on different applications. This approach doesn't (and shouldn't) work and causes authentication failure. I should have kept the consumer details DRY of course :)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM