OmniAuth For Rails Application

4 Min. Read
Aug 13, 2019

Introduction

OmniAuth(Outh) is a standard protocol for authorising the website to use the user information of the particular social sites as facebook, google, github, etc without providing the actual password of the user to the application. For e.g when visiting the login page of certain application, there may be the option available as “Sign in with Facebook” or any other social sites. When a user clicks that option, the user is redirected to that social site where the user provides the login credentials. Afterward, the user gets redirected back to the index page of the previous app. This way the user avoided the necessity to fill up the long signup process.

How the process flows ?

  1. First of all, an application is registered with the intended provider (Facebook, Google, etc) where client _ id and client _ secret are obtained which gets configured in the application configuration file.

  2. Then, the application sends out a request to the provider(Facebook, Google) which includes the application’s client _ id and client _ secret.

  3. Provider asks the user if they’d like to authorize the application to use their info.

  4. Then, a provider sends back token to the application. The application sends a second request to the provider along with the token.

  5. The provider sends a response back with a user’s information which the application parses in hash form whch the application can understand.

OmniAuth with Facebook

In facebook developer site, create an app by clicking on to Add a New App Then, provide the necessary credentials. In Add a product section click on Facebook Login and then enter https://localhost:3000/ in Site URL options. After this, in the valid OAuth redirect URIs field, enter https://localhost:3000/auth/facebook/callback, which is the default callback endpoint for the omniauth-facebook.

Click Save Changes, and then on Dashboard option in the sidebar click on Settings and then Basic where you need to copy the APP ID and App Secret.

Add a gem file

1
gem 'omniauth-facebook'

Add a required additional field to users table

1
rails g migration AddColumnsToUsers provider:string, uid:string

where, the provider is the type of OAuth , and uid specifies the unique Id of the user.Then, run rails db:migrate

Add OmniAuth Configuration to initializer

In config/initializers/devise.rb add:

1
config.omniauth :facebook, ENV['FACEBOOK_KEY'],ENV['FACEBOOK_SECRET']

FACEBOOK _ KEY and FACEBOOK _ SECRET are obtained from the previous time of creating app in facebook.

Enable a Route for Omniauth

In config/routes.rb configure to create a router for Omniauth to send its authentication data to :

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

Enable Omniauth for User Model

In user.rb add the following : ruby devise :omniauthable, :omniauth_providers => [:facebook]

And add, the from_omniauth method

1
2
3
4
5
6
7
8
9
 devise :omniauthable, :omniauth_providers => [:facebook]

 def self.from_omniautha(auth)
  where(provider: auth.provider, uid: auth.uid).first_or_create do |user|
  user.email = auth.info.email
  user.password = Devise.friendly_token[0,20]
  end
 end

Add a Controller to Handle the Callback

In app/controllers/users/omniauthable_callbacks_controller.rb , write the code to handle the Omniauth Callback

1
2
3
4
5
6
class Users::OmniauthCallbacksController < Devise::OmniauthCallBacksController
  def facebook
    @user = User.from_omniauth(request.env["omniauth.auth"])
    sign_in_and_redirect @user
    end
   end

Now, the application is ready to sign in using the facebook credentials.

OmniAuth with Google

Similar to the facebook-oauth, we need to register our app in the google developer account https://console.developers.google.com. However, application must be hosted on authorized domain such as https://mustang.ideabreed.net/. The process may feels to be difficult in comparison to the process of registering app in facebook.

Guide to register app in the google and configuration of the omniauth-google-oauth2

  • Go to the link https://console.developers.google.com.Complete the login process, you will be redirect to dashboard.
  • In the sidebar, click to credentials options after that a dropdown menu named ‘create credentials’ appears where you need to select OAuth client ID
  • Go to the dashboard page again where you need to provide the necessary credentials including the link of your app hosted in authorized domain.
  • Then you will be provided the app _ id , app _ secret which you need to later configure in config/initializers/devise.rb once you install the omniauth-google_oauth gem
  • As in oauth-facebook, add gem 'omniauth-google-oauth2' in gemfile, then run bundle.

Add OmniAuth Configuration to initializer

In config/initializers/devise.rb :

1
config.omniauth :google_oauth2, ENV['APP_KEY'],ENV['APP_SECRET']

Enable Omniauth for User Model

In user.rb add the following :

1
devise :omniauthable, :omniauth_providers => [:facebook, :google_oauth2]

And add, the required field to create from obtained data from the google-provider in from_omniauth method.

1
2
3
4
5
6
7
8
 devise :omniauthable, :omniauth_providers => [:facebook, :google_oauth2]

 def self.from_omniautha(auth)
  where(provider: auth.provider, uid: auth.uid).first_or_create do |user|
  user.email = auth.info.email
  user.password = Devise.friendly_token[0,20]
  end
 end

Add a Controller to Handle the Callback

In app/controllers/users/omniauthable_callbacks_controller.rb , write the following code to handle the Omniauth Callback

1
2
3
4
5
6
class Users::OmniauthCallbacksController < Devise::OmniauthCallBacksController
  def google_oauth2
    @user = User.from_omniauth(request.env["omniauth.auth"])
    sign_in_and_redirect @user
   end
end

In this way you are able to login via google account credentials.

OmniAuth with Twitter

In comparison to the above two process of registering the app , it is much difficult to register in twitter as it tries to understand the information about the app in the descriptive form clarifying the usecase of app, listing the sectors who are able to access the app, purpose of registering the app, etc which you need to answer thoroughly as instructed by them.

Once registered, you get the Customer _ Api _ Key, Customer _ Secret _ Key, Authorise _ Key, Authorise_Secret which you need to configure in your configuration file. And the rest of the process is similar to above mentions methods.