Skip to content
This repository was archived by the owner on Nov 25, 2021. It is now read-only.

OmniAuth: Overview

professor edited this page Sep 19, 2011 · 94 revisions

Devise 1.2 supports integration with OmniAuth. This wiki page will cover the basics to have this integration working using an OAuth provider as example.

Facebook example

The first step then is to add OmniAuth OAuth to our application, this can be done in our Gemfile:

gem "oa-oauth", :require => "omniauth/oauth"

With Rails 3.0.3, use this in your Gemfile instead if rails is having trouble loading oauth core:

gem "omniauth"

Next, you need to declare the provider in your config/initializers/devise.rb:

config.omniauth :facebook, "APP_ID", "APP_SECRET"

If you run into an OpenSSL error like this:

OpenSSL::SSL::SSLError (SSL_connect returned=1 errno=0 state=SSLv3 read server certificate B: certificate verify failed):

Then you need to explicitly tell omniauth where to locate your ca_certificates file. This can be done with the following (depending on the OS you are running on):

config.omniauth :facebook, "APP_ID", "APP_SECRET",
      {:client_options => {:ssl => {:ca_path => '/etc/ssl/certs'}}} 

If your app is running on Heroku (and you have been pulling your hair out for hours), the config section needs to look like this:

config.omniauth :facebook, "APP_ID", "APP_SECRET",
      {:scope => 'email, offline_access', :client_options => {:ssl => {:ca_file => '/usr/lib/ssl/certs/ca-certificates.crt'}}} 

A deeper discussion of this error can be found here: https://github.com/intridea/omniauth/issues/260

And make your model (e.g. app/models/user.rb) omniauthable:

devise :omniauthable

Add next method to model:

def self.find_for_facebook_oauth(access_token, signed_in_resource=nil)
  data = access_token['extra']['user_hash']
  if user = User.find_by_email(data["email"])
    user
  else # Create a user with a stub password. 
    User.create(:email => data["email"], :password => Devise.friendly_token[0,20]) 
  end
end

note: This is simply an example. your application must take precautions if using User.find_by_email to link an existing User with a facebook account.

Notice that Devise 1.2 only allows you to make one model omniauthable. If we have chosen a model named User and "devise_for :users" is already added to your config/routes.rb, Devise will create the following url methods:

  • user_omniauth_authorize_path(provider)
  • user_omniauth_callback_path(provider)

Note that devise does not create *_url method. While you will never use the second method directly, you only need to add the first one to your layouts in order to provide facebook authorization:

<%= link_to "Sign in with Facebook", user_omniauth_authorize_path(:facebook) %>

By clicking on this link, the user will be redirected to facebook. (If this link doesn't exist, try restarting the server.) After inserting his credentials, we will be redirected back to your application. However this will fail as we have not implemented the callback yet. To implement a callback, the first step is to go back to our config/routes.rb file and tell Devise in which controller we will implement Omniauth callbacks:

devise_for :users, :controllers => { :omniauth_callbacks => "users/omniauth_callbacks" }

Now we just add the file "app/controllers/users/omniauth_callbacks_controller.rb":

class Users::OmniauthCallbacksController < Devise::OmniauthCallbacksController
end

The callback should be implemented as an action with the same name as the provider. Here is an example action for our facebook provider that we could add to our controller:

class Users::OmniauthCallbacksController < Devise::OmniauthCallbacksController
  def facebook
    # You need to implement the method below in your model
    @user = User.find_for_facebook_oauth(env["omniauth.auth"], current_user)

    if @user.persisted?
      flash[:notice] = I18n.t "devise.omniauth_callbacks.success", :kind => "Facebook"
      sign_in_and_redirect @user, :event => :authentication
    else
      session["devise.facebook_data"] = env["omniauth.auth"]
      redirect_to new_user_registration_url
    end
  end
end

This action has a few aspects worth describing:

  1. All information retrieved from Facebook by OmniAuth is available as a hash at env["omniauth.auth"]. Check omniauth docs for more information.

  2. In case a valid user is given from our model, we should sign it in. Notice we set a flash message using one of Devise's default messages, but that is up to you. Next, we sign the user in and redirect it. We pass the :event => :authentication to the sign_in_and_redirect method to force all authentication callbacks to be called.

  3. In case the user is not persisted, we store the OmniAuth data in the session. Notice we store this data using "devise." as key namespace. This is useful because Devise removes all the data starting with "devise." from the session whenever a user signs in, so we get automatic session clean up. At the end, we redirect the user back to our registration form.

As of March, Omniauth now calls through to the app for dynamic configuration settings and you will need to define a route for /auth/:provider that results in a 404 so Omniauth knows how to proceed. The reasoning behind this can be found here: http://stackoverflow.com/questions/5531263/omniauth-doesnt-work-with-route-globbing-in-rails3 Inside your devise_scope :user routes block, add this:

get '/users/auth/:provider' => 'users/omniauth_callbacks#passthru'

And then add this method inside of the previously created Omniauth Callbacks Controller:

def passthru
  render :file => "#{Rails.root}/public/404.html", :status => 404, :layout => false
end

Notice that Devise RegistrationsController by default calls "User.new_with_session" before building a resource. This means that, if we need to copy data from session whenever a user is initialized before sign up, we just need to implement new_with_session in our model. Here is an example that copies the facebook email if available:

class User < ActiveRecord::Base
  def self.new_with_session(params, session)
    super.tap do |user|
      if data = session["devise.facebook_data"] && session["devise.facebook_data"]["extra"]["user_hash"]
        user.email = data["email"]
      end
    end
  end
end

Finally, if you want to allow your users to cancel sign up with Facebook, you can redirect them to "cancel_user_registration_path". This will remove all session data starting with "devise." and the new_with_session hook above will no longer be called.

Using OmniAuth without other authentications

If you are using ONLY omniauth authentication, you need your own sessions controller and define at least a named route called new_user_session. Below is an example of such routes (you don't need to include it if you are also using database or other authentication with omniauth):

devise_for :users, :controllers => { :omniauth_callbacks => "users/omniauth_callbacks" } do
  get 'sign_in', :to => 'users/sessions#new', :as => :new_user_session
  get 'sign_out', :to => 'users/sessions#destroy', :as => :destroy_user_session
end

OpenID and Google Apps examples

Add OmniAuth OpenID to your Gemfile:

gem 'oa-openid', :require => 'omniauth/openid'

In order to use following features, you have to require openid store in Devise initializer. For example:

require 'openid/store/filesystem'
  • OpenID

Add following code to Devise initializer

config.omniauth :open_id, OpenID::Store::Filesystem.new('/tmp')
config.omniauth :open_id, OpenID::Store::Filesystem.new('/tmp'), :name => 'google', :identifier => 'https://www.google.com/accounts/o8/id'

and use this to your view

link_to "sign in with yahoo", user_omniauth_authorize_path(:open_id, :openid_url => "http://yahoo.com")
link_to "sign in with google", user_omniauth_authorize_path(:google)
  • Google Apps

Devise initializer:

config.omniauth :google_apps, OpenID::Store::Filesystem.new('/tmp'), :domain => 'gmail.com'

View:

link_to 'GMail', user_omniauth_authorize_path(:google_apps)

And that is all you need! After you get your integration working, it's time to write some tests:

https://github.com/intridea/omniauth/wiki/Integration-Testing

Clone this wiki locally