Google Login in Rails 7 with devise


Google login can present a handy and seamless authentication choice in your customers. On this complete information, we’ll stroll you thru the steps to combine Google login into your Rails 7 app, permitting customers to authenticate utilizing their Google accounts.

I am assuming that you have already got put in and applied devise gem in your rails app. If not test this text.

Let’s get began!

Step 1: Add Required Gems

In your Rails app’s Gemfile, be sure to have the next gems:

gem 'omniauth-google-oauth2'
gem "omniauth-rails_csrf_protection"
Enter fullscreen mode

Exit fullscreen mode

Then, run the next command to put in the gems:

bundle set up
Enter fullscreen mode

Exit fullscreen mode

Step 2: Configure Devise Mannequin

Add the next code in your devise mannequin (i will be utilizing Person):

# fashions/consumer.rb
:omniauthable, omniauth_providers: [:google_oauth2]
Enter fullscreen mode

Exit fullscreen mode

Now we have to add two fields uid and supplier in our devise mannequin (in my case Person).

  1. uid (Person ID): It shops a novel identifier related to the consumer’s account from the OAuth supplier (on this case, Google). Every consumer has a definite uid assigned by the supplier, which permits your utility to uniquely establish them.

  2. supplier: It signifies the identify of the OAuth supplier getting used for authentication (e.g., “google_oauth2”). This area helps differentiate between completely different authentication strategies and permits your utility to deal with a number of authentication suppliers if wanted.

Generate the migration:

rails g migration AddFieldsToUser
Enter fullscreen mode

Exit fullscreen mode

Add the under code in your migration:

def change
  change_table :customers, bulk: true do |t|
    t.string :supplier
    t.string :uid
Enter fullscreen mode

Exit fullscreen mode

Run rails db:migrate so as to add these fields to your desk.

Now, add the under code in your devise mannequin. Mine in consumer.rb:

def self.from_google(u)
    create_with(uid: u[:uid], supplier: 'google',
                password: Devise.friendly_token[0, 20]).find_or_create_by!(electronic mail: u[:email])
Enter fullscreen mode

Exit fullscreen mode

Step 3: Configure Controller

Create a customers/omniauth_callbacks_controller.rb file contained in the controllers listing and paste the under code:

# app/controllers/customers/omniauth_callbacks_controller.rb
class Customers::OmniauthCallbacksController < Devise::OmniauthCallbacksController
   def google_oauth2
     consumer = Person.from_google(from_google_params)

     if consumer.current?
       flash[:notice] = t 'devise.omniauth_callbacks.success', variety: 'Google'
       sign_in_and_redirect consumer, occasion: :authentication
       flash[:alert] = t 'devise.omniauth_callbacks.failure', variety: 'Google', motive: "#{auth.data.electronic mail} just isn't approved."
       redirect_to new_user_session_path

    def from_google_params
      @from_google_params ||= {
        uid: auth.uid,
        electronic mail: auth.data.electronic mail

    def auth
      @auth ||= request.env['omniauth.auth']
Enter fullscreen mode

Exit fullscreen mode

Step 4: Add Routes

Open config/routes.rb and the routes:

# config/routes.rb
devise_for :consumer,
      controllers: {
         omniauth_callbacks: 'customers/omniauth_callbacks'
Enter fullscreen mode

Exit fullscreen mode

Step 5: Set Up a Google API Console Challenge

Go to the Google API Console and create a brand new venture as under:

Google API Console

How to create a new project

You may give any identify to your venture. I named it Google Login.

After coming into the identify click on Create.

After which go into your google login venture. There might be a dropdown within the navbar (i’ve confirmed it within the first image), you should utilize it to vary your venture.

  1. Go to OAuth consent display
  2. Select consumer sort Exterior
  3. Click on Create
  4. Fill all of the fields
  5. Scroll down and click on Save and proceed.

Subsequent observe the under steps:

Create Credentials

  1. Choose Software Sort Internet utility
  2. Enter any identify
  3. Go to your console/terminal and sort the command rails routes | grep /callback. Copy the URL…
  4. Go to your browser and click on on Add URI button
  5. Paste the copied url in URL area corresponding to http://localhost:3000/consumer/auth/google_oauth2/callback
  6. Click on Create

After getting created the venture, a popup will show your shopper ID and shopper secret. Ensure to avoid wasting this info for future use.

Now that you’ve got obtained your shopper ID and shopper secret, let’s proceed with the configuration of Google login in your Rails app.

Step 6: Implement Google Login

Open up config/initializers/devise.rb file and paste the under code:

# config/initializers/devise.rb

config.omniauth :google_oauth2, 'GOOGLE_OAUTH_CLIENT_ID', 'GOOGLE_OAUTH_CLIENT_SECRET'
Enter fullscreen mode

Exit fullscreen mode

My file appears like this:

# config/initializers/devise.rb

# ==> OmniAuth
# Add a brand new OmniAuth supplier. Examine the wiki for extra info on setting
# up in your fashions and hooks.
# config.omniauth :github, 'APP_ID', 'APP_SECRET', scope: 'consumer,public_repo'
config.omniauth :google_oauth2, 'GOOGLE_OAUTH_CLIENT_ID', 'GOOGLE_OAUTH_CLIENT_SECRET'

Enter fullscreen mode

Exit fullscreen mode

Now simply add the login button in any of your views.

<%= button_to 'Login with Google', user_google_oauth2_omniauth_authorize_path, methodology: :publish, :knowledge => {turbo: "false"} %>
Enter fullscreen mode

Exit fullscreen mode

Congratulations! 🎉 You may have efficiently added Google login to your Rails 7 app.

You’ll be able to test the gem’s repo right here.

Thanks for studying! 🙂


Leave a Reply

Your email address will not be published. Required fields are marked *