OAuth::Unauthorized 401 Authorization Required using OmniAuth-Twitter in Rails 3.2

Matteo picture Matteo · Sep 17, 2014 · Viewed 11.6k times · Source

I have implemented several different strategies found in StackOverFlow, but so far, none seem to affect the error being thrown:

OAuth::Unauthorized 401 Authorization Required

I am following Ryan Bates' RC #241 and get to the point where I click "Sign-in with Twitter" and I get the error. I went ahead and added the response route to the routes.rb file as listed here:

routes.rb:

match 'auth/twitter/callback', to: 'user#update'

thinking that the error might be caused from the callback function. Same error. A look at my dev.log shows this:

Started GET "/auth/twitter" for 127.0.0.1 at 2014-09-16 18:52:08 -0600
(twitter) Request phase initiated.

OAuth::Unauthorized (401 Authorization Required):
oauth (0.4.7) lib/oauth/consumer.rb:216:in `token_request'
oauth (0.4.7) lib/oauth/consumer.rb:136:in `get_request_token'
omniauth-oauth (1.0.1) lib/omniauth/strategies/oauth.rb:29:in `request_phase'
omniauth-twitter (1.0.1) lib/omniauth/strategies/twitter.rb:60:in `request_phase'
omniauth (1.2.2) lib/omniauth/strategy.rb:215:in `request_call'
omniauth (1.2.2) lib/omniauth/strategy.rb:183:in `call!'
omniauth (1.2.2) lib/omniauth/strategy.rb:164:in `call'
omniauth (1.2.2) lib/omniauth/builder.rb:59:in `call'
...
script/rails:6:in `require'
script/rails:6:in `<top (required)>'
-e:1:in `load'
-e:1:in `<main>'

So I know the issue is with the authentication with Twitter going out. Must be the KEY and SECRET, right?

Now, I have put the KEY and SECRET in as ENV[] variables, as direct strings to the environment/development.rb file, taken out the "ENV[]" variables, etc., as per suggestions found all over Stack.

My KEY and SECRET now reside in a custom configuration as discussed here...

config/initializers/social_media.rb:

TWITTER_CONFIG = YAML.load_file("#{::Rails.root}/config/twitter.yml")[::Rails.env]

The config/initializers/omniauth.rb file:

OmniAuth.config.logger = Rails.logger

Rails.application.config.middleware.use OmniAuth::Builder do
  provider :twitter, TWITTER_CONFIG['app_id'], TWITTER_CONFIG['secret']
end   

Any ideas on the ActionController: Exception caught OAuth::Unauthorized - 401 Authorization Required? This is probably a Noob error, but my Google-Fu is just Google-F'ed right now...

Answer

Matteo picture Matteo · Sep 17, 2014

After a night of tearing my hair out, I took at look at the callback URL on Twitter developer console.

Save yourselves some trouble and don't forget to set this. It's not mentioned directly in the RailsCast, although Ryan does briefly pass over it.

When you set the callback URL, don't just put //localhost:3000 it won't work. Instead use:

http://127.0.0.1:3000/