Integrate Google Sign-In

(1) Add this gem.

gem 'omniauth-google-oauth2'

(2) Add this route to get oauth callback.

get 'auth/:provider/callback', to: 'authentication#oauth2callback'

You can use :provider if you are using multiple oauth providers, such as Facebook and Google. Or you can hardcode to "google_oauth2".

(3) Create an initializer - omniauth.rb

Rails.application.config.middleware.use OmniAuth::Builder do
  provider :google_oauth2, 
  '2141xxxxxxxx-scuxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxsk8u.apps.googleusercontent.com', 
  'xxxxxxxxxxxxxxxxxxxxxxx', 
  scope: 'email, profile', 
  hd: 'calvin.my',
  prompt: 'select_account'
end

In this initializer, you can enter your oauth 2.0 ID and password which is created in Google Developer API Console (Remember to whitelist the callback URL or IP).

Hosted Domain (HD): If you set the hosted domain option, then only accounts from selected domains are allowed. E.g.


Scope: Most of the case, the application only requires email and profile permission. You can request for other permissions as needed. The full list is available here.

(4) Create your sign-in button in your view.

<a href="/auth/google_oauth2">Click Me</a>

(5) Handle the callback response. Usually, you will revalidate the id_token returned to your callback. If it is valid then you can redirect to the page after sign-in.

def oauth2callback
  id_token = request.env['omniauth.auth']['extra']['id_token']

  response = HTTParty.get("https://www.googleapis.com/oauth2/v3/tokeninfo?id_token=#{id_token}")

  if response.parsed_response['aud'] == '2141xxxxxxxx-scuxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxsk8u.apps.googleusercontent.com' &&
     response.parsed_response['email'] == request.env['omniauth.auth']['info']['email']
    // Success
    // name = request.env['omniauth.auth']['info']['name']
    // email = request.env['omniauth.auth']['info']['email']
    // image = request.env['omniauth.auth']['info']['image']
    redirect_to home_path and return
  end
  redirect_to sign_in_path
end

(6) Runs your app and clicks on the link to try.


AI Summary
Chrome On-device AI 2024-07-20 06:35:14

Share Article