views:

1137

answers:

3

Devise, the authentication gem for Ruby based 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.

A: 

Hey, do you solve the problem? I'm looking for the same solution

23tux
I actually didn't. I'm temporarily using a version of mbleigh's twitter_auth gem instead.
Michael Waxman
+2  A: 
# 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') ) %>
Carlos A. Cabrera
Quick question... is oauthable compatible with 1.0 (for rails 2.x) or do you need 1.1 (rails 3)?
Michael Waxman
It seems OAuth support was added to 1.1 so you may need to be on Rails 3.
Carlos A. Cabrera
Note: this only works for Oauth2 (Facebook, Git), and not Twitter (Oauth 1.0).
Michael Waxman
Michael I actually got Twitter OAuth working just fine.
Carlos A. Cabrera
Strange all i get is: authenticate! is not declared in the :twitter_oauth strategy
PanosJee
A: 

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 ) %>
Yasser