First, you'll need to add the OmniAuth gem and the Google OAuth2 gem to your Gemfile
. Add the following lines:
gem 'omniauth-google-oauth2'
After updating your Gemfile
, run:
bundle install
Next, go to the Google Cloud Console and create a new project. Then navigate to APIs & Services and create OAuth 2.0 credentials.
http://localhost:3000/auth/google_oauth2/callback
.To protect your Google OAuth credentials, store them in environment variables using a .env
file.
# .env GOOGLE_OAUTH_CLIENT_ID="your-client-id" GOOGLE_OAUTH_CLIENT_SECRET="your-client-secret"
Replace your-client-id
and your-client-secret
with the values you copied from Google Cloud Console.
Create or update the file config/initializers/omniauth.rb
with the following code to configure OmniAuth to use your Google OAuth credentials:
# config/initializers/omniauth.rb Rails.application.config.middleware.use OmniAuth::Builder do provider :google_oauth2, ENV['GOOGLE_OAUTH_CLIENT_ID'], ENV['GOOGLE_OAUTH_CLIENT_SECRET'], { scope: 'email,profile', prompt: 'select_account', } end
Next, update your config/routes.rb
file to add routes for OmniAuth callbacks:
# config/routes.rb Rails.application.routes.draw do get 'auth/:provider/callback', to: 'sessions#create' get 'auth/failure', to: redirect('/') delete 'logout', to: 'sessions#destroy' end
Now, create a SessionsController
to handle the callback from Google OAuth:
# app/controllers/sessions_controller.rb class SessionsController < ApplicationController def create user_info = request.env['omniauth.auth'] user = User.find_or_create_by(email: user_info['info']['email']) do |u| u.name = user_info['info']['name'] u.image = user_info['info']['image'] end session[:user_id] = user.id redirect_to root_path, notice: 'Signed in successfully' end def destroy session[:user_id] = nil redirect_to root_path, notice: 'Signed out successfully' end end
Finally, add login and logout links to your application views. You can use the following example for a basic implementation:
# app/views/layouts/application.html.erb <% if session[:user_id] %> Logged in as <%= User.find(session[:user_id]).name %> | <%= link_to 'Logout', logout_path, method: :delete %> <% else %> <%= link_to 'Login with Google', '/auth/google_oauth2' %> <% end %>
You have now successfully set up Google OmniAuth in your Rails application. You can log in and log out using Google credentials, and the user's data will be stored in your application session.
Remember to never commit your .env
file to version control. Instead, use services like Heroku or Docker to manage environment variables in production.