DEV Community

Ivana
Ivana

Posted on • Originally published at Medium on

Google Authentication

OmniAuth is a gem for Rails that lets you use multiple authentication providers alongside the more traditional username/password setup. It supports many authentication providers: Facebook, LinkedIn, GitHub full list can be found here.

Here’s how OmniAuth works from the user’s standpoint:

  1. User tries to access a page on yoursite that requires them to be logged in. They are redirected to the login screen.
  2. The login screen offers the options of creating an account or logging in with Google.
  3. The user clicks Log in with Google. This momentarily sends the user to yoursite.com/auth/google , which quickly redirects to the Google sign-in page.
  4. If the user is not already signed in to Google, they sign in normally. More likely, they are already signed in, so Google simply asks if it’s okay to let yoursite.com access the user’s information. The user agrees.
  5. They are (hopefully quickly) redirected to yoursite.com/auth/google/callback and, from there, to the page they initially tried to access.

Installation

Add to your Gemfile:

Then bundle instal

Go to https://console.developers.google.com and login with your google account. Click on select a project

Click on Credentials and click on the “OAuth consent screen” tab to set up You require the client ID and client secret for your rails app

Middleware

Add the middleware to the project in config/initializers/omniauth.rb.

You can now visit the url:/auth/google_oauth2 to assess the google authentication.

Routes

Routes for Google authentication, expect callback from server

get '/auth/:provider/callback' => 'sessions#omniauth'

Controller

Uid ensures its unique instance that we haven’t had before.

Migration

In the migration add:

Connect with Me on Twitter or LinkedIn

Originally published at https://ivanadokic.github.io on April 13, 2020.

Top comments (0)