Devise Omniauth Dynamic Providers

My current project www.viewshound.com requires different users to have different scopes for their Facebook authentication. Warden supports dynamic providers out of the box. To get it working with Devise was pretty easy, just a couple of minor changes were needed especially to support Facebook.

First up was creating the new route. As I’m using a controller called Omniauth and not Session, the :to attribute is different. The other thing to note is I’m matching /users/auth/facebook/setup, not /auth/facebook/setup like in the Warden documentation.

routes.rb

Next we create the new setup action for Warden to call. The docs use consumer_key and consumer_secret, but facebook expects client_id and client_secret, so be sure to use those instead. This is where I make changes to the scope based on the current user if they are signed in or not. So a user can re-authenticate with Facebook to get more permissions for their account if they wish.

omniauth_controller.rb

Finally change the devise.rb initializer to support the new setup.

devise.rb

Restart your application and you should be good to go.

  • hbdev

    I have followed the same procedure, But I am getting request.env[‘omniauth.strategy’] nil. Please can you guide me where I am doing wrong ? And please let me know what other info you need to trace it.

    • Sorry for not replying sooner. Not sure why your omniauth.strategy is nil. Have you setup omniauth properly in your devise initializer?

  • Is there a way to do this and set the full_host attribute for the strategy during setup?

  • Thought I’d found a solution here but getting this error:

    actionpack-3.1.3/lib/action_dispatch/routing/mapper.rb:181:in `default_controller_and_action’: missing :action (ArgumentError)

    Any ideas?

  • Nevermind. It was a typo: I had ‘users/omniauth_setups/facebook’ in my routes not ‘users/omniauth_setups#facebook’

    Thanks for the great solution! Works!

  • enderahmetyurt

    why is request.env[‘omniauth.strategy’] nil?

    • Hates

      Sadly I don’t know why.

      • enderahmetyurt

        Ok np. I could handle it but you wrote “config.omniauth :facebook, nil,nil, :setup => true”. It is not working without any id and secret_key. How do your apps work?

  • Will Tungpagasit

    for those using Devise 3, devise_for no longer takes a block in your routes.rb, so you’ll need to use devise_scope. The code above would be (note: user is singular after devise_scope):

    devise_for :users, :controllers => { :omniauth_callbacks => “omniauth” }, :skip => [:sessions]
    devise_scope :user do
    match ‘/users/auth/facebook/setup’, :to => ‘omniauth#setup’
    end