开发者

Twitter Oauth Strategy with Warden + Devise Authentication Gems for Ruby

Devise, the authentication gem for Ruby ba开发者_高级运维sed on Warden (another auth gem) does not support Twitter Oauth as an authentication strategy, BUT Warden does. There is a way to use the Warden Twitter Oauth strategy within Devise, but I cannot figure it out. I'm using the following block in the devise config file:

  config.warden do |manager|
       manager.oauth(:twitter) do |twitter|
          twitter.consumer_secret = <SECRET>
          twitter.consumer_key  = <KEY>
          twitter.options :site => 'http://twitter.com'
       end
       manager.default_strategies.unshift :twitter_oauth
  end

But I keep on getting all sorts of error messages. Does anyone know how to make this work? I'm assuming there is more to do here (configuring a new link/route to talk to Warden, maybe adding attributes to the Devise User model, etc.), but I can't figure out what they are. Please help.


# Needed gems. Add to your Gemfile if you are using Rails3.  
gem 'devise'
gem 'warden_oauth'

#models/user.rb
devise :token_authenticatable, :oauthable # <-- Must have these

#/config/initializers/devise.rb
require 'warden_oauth'
config.warden do |manager|
  manager.oauth(:twitter) do |twitter|
    twitter.consumer_secret = '<SECRET>'
    twitter.consumer_key  = '<CONSUMER KEY>'
    twitter.options :site => 'http://twitter.com'
  end
  manager.default_strategies(:scope => :user).unshift :twitter_oauth
end

Warden::OAuth.access_token_user_finder(:twitter) do |access_token|
  User.find_or_create_by(:token => access_token.token, :secret => access_token.secret).tap do |user|
    #... 
  end
end

# Link to "Login With Twitter" somewhere in your view
<%= link_to( "Login With Twitter", user_session_path(:warden_oauth_provider => 'twitter') ) %>


Omniauth makes this easy. There is a Railscast on using Omniauth with Devise (part 1, part 2).


This solution does work. You just have to make sure that you're calling a protected action when specifying :warden_oauth_provider => 'twitter', otherwise Rails will simply ignore it.

To use the example above, change the link to:

<%= link_to( "Login With Twitter", user_session_path(:warden_oauth_provider => 'twitter'), :method => :post ) %>


Try checking if you define a class or a module named Twitter (you can check this by running script/console then type Twitter), if you did, name it to something non-existent.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜