Integrating Google SSO in Ruby on Rails

Total Blog Views: 206

Blog Status: publish

Created By: swaz_ahmed Created at: 06-24-2024

Tags: SSO Single Sign On

Integrating Single Sign-On (SSO) in Ruby on Rails

 

Introduction:

Single Sign-On (SSO) is an authentication process that allows a user to access multiple applications with one set of login credentials. Integrating SSO into your Ruby on Rails application can greatly enhance the user experience by providing seamless access across various services. In this blog post, we'll explore how to integrate SSO in a Rails application using the Devise and OmniAuth gems.

When and Why to use SSO? When you have multiple apps and you don’t want to burden your users to remember multiple account usernames and passwords(they need free mental space to remember their anniversaries) then one should use SSO. The growing complexity of your system should not be borne by the users, but by the system itself.

 

Prerequisites
Before we begin, ensure you have the following:

  • A Rails application (version 6 or higher recommended.
  • Basic knowledge of Ruby on Rails.
  • An OAuth provider account (e.g., Google, Facebook, GitHub).

 

Step-by-Step Integration Guide:

Step 1: Set Up Devise:

Devise is a flexible authentication solution for Rails based on Warden. First, add Devise to your Gemfile:

gem 'devise'

Run bundle install to install the gem.

Next, run the Devise installation generator:

rails generate devise:install

Follow the instructions provided by the generator to configure Devise in your application.

Generate a Devise model (e.g., User):

rails generate devise User

Run the migrations to update the database:

rails db:migrate

 

Step 2: Add OmniAuth:

OmniAuth is a library that standardizes multi-provider authentication for web applications. Add OmniAuth and OmniAuth provider gems to your Gemfile. For example, to add Google as a provider:

gem 'omniauth'
gem 'omniauth-google-oauth2'

Run bundle install to install the gems.

 

Step 3: Configure Devise with OmniAuth:

Update your Devise configuration to include OmniAuth. Open config/initializers/devise.rb and add the following:

  Devise.setup do |config|
    # Other configurations...
    config.omniauth :google_oauth2, "GOOGLE_CLIENT_ID", "GOOGLE_CLIENT_SECRET", {
      scope: 'userinfo.email, userinfo.profile'
    }
  end

Replace GOOGLE_CLIENT_ID and GOOGLE_CLIENT_SECRET with your actual Google OAuth credentials.

 

Step 4: Update the User Model 

Modify the User model to include OmniAuth support. Open app/models/user.rb and add the following:

 class User < ApplicationRecord
  devise :database_authenticatable, :registerable,
         :recoverable, :rememberable, :validatable,
         :omniauthable, omniauth_providers: [:google_oauth2]
  def self.from_omniauth(access_token)
    data = access_token.info
    user = User.where(email: data['email']).first
    unless user
      user = User.create(
        email: data['email'],
        password: Devise.friendly_token[0,20]
      )
    end
    user
  end
end

 

Step 5: Add Routes and Callbacks:

Add OmniAuth routes and callbacks in your config/routes.rb file:

 devise_for :users, controllers: {
  omniauth_callbacks: 'users/omniauth_callbacks'
}

Create a controller to handle OmniAuth callbacks. Generate a controller:

rails generate controller Users::OmniauthCallbacks 

Open the generated file app/controllers/users/omniauth_callbacks_controller.rb and add the following:

class Users::OmniauthCallbacksController < Devise::OmniauthCallbacksController
  def google_oauth2
    @user = User.from_omniauth(request.env['omniauth.auth'])
    if @user.persisted?
      sign_in_and_redirect @user, event: :authentication
      set_flash_message(:notice, :success, kind: 'Google') if is_navigational_format?
    else
      session['devise.google_data'] = request.env['omniauth.auth'].except(:extra)
      redirect_to new_user_registration_url, alert: @user.errors.full_messages.join("\n")
    end
  end
  def failure
    redirect_to root_path
  end
end 

 

Step 6: Add Sign-In Links:

Add links to your views to allow users to sign in using their SSO provider. For example, in app/views/devise/sessions/new.html.erb:

 

<%= link_to "Sign in with Google", user_google_oauth2_omniauth_authorize_path %> 

 

Step 7: Test the Integration:

Start your Rails server and navigate to the sign-in page. You should see an option to sign in with Google. Click the link and follow the prompts to authenticate via Google. If everything is set up correctly, you should be redirected back to your application and signed in as the authenticated user.

 

Conclusion:

 Integrating SSO into your Rails application enhances user experience and security by providing a streamlined and centralized authentication process. Using Devise and OmniAuth makes this integration straightforward and flexible, allowing you to support multiple OAuth providers with minimal configuration.


swaz_ahmed

I am swaz_ahmed blogger on shadbox. I am influencer,content writer,author and publisher. Feel free to ask me any question and suggestions.



Comments



Buy traffic for your website

About Shadbox

we have the “Get things executed” lifestyle at our place of work. There are not any excuses, no if’s or however’s in our dictionary. committed to navigating the ship of creativity to create cell answers, we resolve the real-lifestyles troubles of our clients and their clients. Our passion for work has won us many awards, year after 12 months.

Services

Downloads