0

Login With Google Account Using Devise and Omniauth

This article shows you how to allow users to login using Devise and their Google accounts.Instead of using our own login system, we can use third party authentication services such as Facebook or Google. Using these services can be more sure and they also provide a better overall user experience.

Devise Installation

Add to your Gemfile

gem "devise"

Then bundle install

Next, you need to run the generator:

$ rails generate devise:install

Generate a devise model by running

$ rails generate devise MODEL_NAME

If your model name is User you will replace MODEL_NAME with User

Then run rake db:migrate

OmniAuth Google OAuth2 Installation

Add to your Gemfile

 gem "omniauth-google-oauth2"

Then bundle install

Define your application id and secret in config/initializers/devise.rb

config.omniauth :google_oauth2, "GOOGLE_CLIENT_ID", "GOOGLE_CLIENT_SECRET", { }

You can get your GOOGLE_CLIENT_ID and GOOGLE_CLIENT_SECRET by setup Google API

  • Go to https://console.developers.google.com
  • Select your project.
  • Click 'Enable and manage APIs'.
  • Make sure "Contacts API" and "Google+ API" are on.
  • Go to Credentials, then select the "OAuth consent screen" tab on top, and provide an 'EMAIL ADDRESS' and a 'PRODUCT NAME'

Then add the following to config/routes.rb so the callback routes are defined.

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

Make sure your model is omniauthable. Generally this is /app/models/user.rb

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

Setup callbacks controller

class Users::OmniauthCallbacksController < Devise::OmniauthCallbacksController
  def google_oauth2
      @user = User.from_omniauth(request.env["omniauth.auth"])
      if @user.persisted?
        flash[:notice] = I18n.t "devise.omniauth_callbacks.success", :kind => "Google"
        sign_in_and_redirect @user, :event => :authentication
      else
        session["devise.google_data"] = request.env["omniauth.auth"]
        redirect_to new_user_registration_url
      end
  end
end

In your model app/models/user.rb

def self.from_omniauth(access_token)
  data = access_token.info
  user = User.where(:email => data["email"]).first

  unless user
    password = Devise.friendly_token[0,20]
    user = User.create(name: data["name"], email: data["email"],
      password: password, password_confirmation: password
    )
  end
  user
end

For your views you can login using:

<%= link_to "Sign in with Google", user_omniauth_authorize_path(:google_oauth2) %>

Get more information about omniauth-google-oauth2 here:


All rights reserved

Viblo
Hãy đăng ký một tài khoản Viblo để nhận được nhiều bài viết thú vị hơn.
Đăng kí