简体   繁体   中英

Rails: Twitter Omniauth gem 401 Unauthorized Error

I am using twitter omniauth gem in my web application. I stored my key and secret in my DB.

This is my middleware code

 Rails.application.config.middleware.use OmniAuth::Builder do

 provider :twitter, lambda { Site.config[:twitter][:key] },lambda{ Site.config[:twitter][:secret] }

 end

This returns unauthorized error.

But when i specify my key and secret directly in the middleware it works.

(ie)

 Rails.application.config.middleware.use OmniAuth::Builder do

 provider :twitter, "consumer_key" , "consumer_secret"

 end

What is wrong with my first approach ?

You need to use Setup Phase

provider :twitter, :setup => true

And then in controller:

def setup
  request.env['omniauth.strategy'].options[:consumer_key] = Site.config[:twitter][:key]
  request.env['omniauth.strategy'].options[:consumer_secret] = Site.config[:twitter][:secret]
  render :text => "Setup complete.", :status => 404
end

Routes:

match '/auth/:provider/setup' => 'sessions#setup' # for example

You can add your consumer_key and consumer secret in the development.rb and production.rb

# twitter api credential
  config.twitt_consumer_key = 'xxxxxxxxxxxxxxxxx'
  config.twitt_consumer_secret = 'xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx'

And then you can use it

provider :twitter, Rails.application.config.twitt_consumer_key, Rails.application.config.twitt_consumer_secret

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