Step-by-Step Guide to Implement OAuth2 Authentication in Rails Apps

Implementing OAuth2 authentication in a Rails application can significantly enhance your app’s security and user experience. This step-by-step guide walks you through the process of integrating OAuth2 into your Rails app, enabling users to authenticate via third-party providers such as Google, Facebook, or GitHub.

Prerequisites

  • Ruby on Rails installed (version 6 or higher recommended)
  • Bundler installed
  • Access to a third-party OAuth provider (e.g., Google Developer Console)
  • Basic understanding of Rails routing and controllers

Step 1: Add Required Gems

  • Open your Gemfile and add:

gem ‘omniauth’

gem ‘omniauth-oauth2’

gem ‘omniauth-google-oauth2’ # or your provider of choice

  • Run bundle install to install the gems:

bundle install

Step 2: Configure OAuth Provider

Register your application with your OAuth provider to obtain client ID and secret. For example, with Google:

Navigate to Google Developer Console, create a new project, and enable the OAuth 2.0 API. Then, create OAuth credentials and set the authorized redirect URI to:

http://localhost:3000/auth/google_oauth2/callback

Step 3: Create an Initializer for OmniAuth

Create a new file at config/initializers/omniauth.rb and add:

Rails.application.config.middleware.use OmniAuth::Builder do

provider :google_oauth2, ‘GOOGLE_CLIENT_ID’, ‘GOOGLE_CLIENT_SECRET’, { scope: ’email, profile’ }

end

Step 4: Add Routes

In config/routes.rb, add:

get ‘/auth/:provider/callback’, to: ‘sessions#create’

get ‘/auth/failure’, to: redirect(‘/’)

Step 5: Create Sessions Controller

Generate a controller:

rails generate controller Sessions

Implement Callback Action

In app/controllers/sessions_controller.rb, add:

class SessionsController < ApplicationController

def create

auth_hash = request.env[‘omniauth.auth’]

# Find or create user based on auth_hash info

user = User.find_or_create_by(uid: auth_hash[‘uid’], provider: auth_hash[‘provider’]) do |u|

u.email = auth_hash[‘info’][’email’]

u.name = auth_hash[‘info’][‘name’]

end

# Save user ID in session

session[:user_id] = user.id

redirect_to root_path, notice: ‘Signed in successfully.’

end

end

In your view, add a link to initiate OAuth:

Sign in with Google

Step 7: Handle User Sessions

Implement user login/logout logic as needed, including current_user helper methods.

Conclusion

Integrating OAuth2 authentication in your Rails app enhances security and user convenience. By following these steps, you enable users to authenticate via popular providers effortlessly. Remember to test your implementation thoroughly and ensure your OAuth credentials are kept secure.