Search code examples
deviseomniauthomniauth-google-oauth2

Using Omniauth both for login with Devise as well as for accessing API's


In our application, we allow the user to access their data at different providers (Google Calendar, Microsoft Outlook, Facebook timeline, etc.) through the available API's, using Omniauth. For this we have an omniauth.rb with all the necessary configs, like:

Rails.application.config.middleware.use OmniAuth::Builder do
  provider :facebook, ENV['FACEBOOK_KEY'], ENV['FACEBOOK_SECRET'], scope: 'email,user_posts,user_status,public_profile,manage_pages,instagram_basic'
  provider :google_oauth2, ENV['GOOGLE_CLIENT_ID'], ENV['GOOGLE_CLIENT_SECRET'],
          name: 'google', 
          scope: 'email, profile, calendar.readonly',
          access_type: 'offline', 
          prompt: 'select_account consent'
  # etc...
end

Now we like to add login with Google as an alternative way to log in. Since we use Devise for our user session management, we'd like to use Devise's Omniauth features to implement login with an OAuth provider like Google. However, as soon as we make our model "omniauthable", the existing Omniauth functionality stops working throwing an No route matches [GET] "/auth/facebook" when trying to add an oauth account to access an API.

What is the correct way of combining the use of Omniauth in both Devise and in our own plain vanilla OAuth flow?


Solution

  • I found the answer myself: it's a matter of not using the thin wrapper of functionality that Devise adds to OmniAuth, but instead taking care of the OmniAuth routing yourself. I have described this approach here in the Devise Wiki.