Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Keep getting OAuth::Unauthorized error when using oauth and twitter ruby gems

I am using the ruby twitter gem and oauth to gain access to users twitter accounts. In my code, I have:

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 

where token and secret have my actual token and secret inserted. When I click on the link to the @twitter_auth_url, I am taken to twitter and asked to grant access. I click allow and then twitter redirects me to my callback URL http://www.mydomain.com/twitter_callback/?oauth_token=fmy2aMvnjVgaFrz37bJ4JuB8r5xN79gsgDQRG4BNY which then hits this code:

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 

The twitter request token and secret are being set just fine. However I end up with an authorization error:

 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' 

The code is failing at this line:

oauth.authorize_from_request(session[:twitter_request_token], session[:twitter_request_secret]) 

when it tries to get an access token. You can see the source code of authorize_from_request here. I am not sure why this is happening. Anyone have ideas?

like image 870
Tony Avatar asked Aug 14 '09 21:08

Tony


1 Answers

A bit late to the party but just ran into the same issue myself. I tracked the issue down to the setup of my OAuth app in Twitter. I had initially not specified a callback URL as I was unsure of it.

Once I had setup my rails app I went back to find Twitter had assumed I was a desktop application as I hadn't specified a callback URL. Once I changed this to website and entered a callback URL I stopped getting 400s.

like image 161
George Palmer Avatar answered Sep 21 '22 01:09

George Palmer