0
0
Ruby on Railsframework~5 mins

OAuth integration basics in Ruby on Rails

Choose your learning style9 modes available
Introduction

OAuth helps your app let users log in using other services safely. It avoids asking for passwords directly.

You want users to sign in with Google, Facebook, or Twitter.
You want to access user data from another service with permission.
You want to avoid storing user passwords in your app.
You want to improve user experience by simplifying login.
You want to securely connect your app to external APIs.
Syntax
Ruby on Rails
gem 'omniauth'
gem 'omniauth-oauth2'

# In config/initializers/omniauth.rb
Rails.application.config.middleware.use OmniAuth::Builder do
  provider :provider_name, 'APP_ID', 'APP_SECRET'
end

Replace provider_name with the service like google_oauth2 or facebook.

APP_ID and APP_SECRET come from the service's developer console.

Examples
Set up Google OAuth with your app credentials.
Ruby on Rails
provider :google_oauth2, 'GOOGLE_CLIENT_ID', 'GOOGLE_CLIENT_SECRET'
Set up Facebook OAuth with your app credentials.
Ruby on Rails
provider :facebook, 'FACEBOOK_APP_ID', 'FACEBOOK_APP_SECRET'
Sample Program

This example shows how to set up GitHub OAuth in Rails. When users log in via GitHub, the app gets their info and creates or finds a user. Then it saves the user ID in the session and redirects to the homepage with a welcome message.

Ruby on Rails
# config/initializers/omniauth.rb
Rails.application.config.middleware.use OmniAuth::Builder do
  provider :github, 'GITHUB_CLIENT_ID', 'GITHUB_CLIENT_SECRET'
end

# app/controllers/sessions_controller.rb
class SessionsController < ApplicationController
  def create
    auth = request.env['omniauth.auth']
    user = User.find_or_create_by(uid: auth['uid'], provider: auth['provider']) do |u|
      u.name = auth['info']['name']
      u.email = auth['info']['email']
    end
    session[:user_id] = user.id
    redirect_to root_path, notice: "Logged in as #{user.name}"
  end

  def failure
    redirect_to root_path, alert: 'Authentication failed.'
  end
end

# config/routes.rb
Rails.application.routes.draw do
  get '/auth/:provider/callback', to: 'sessions#create'
  get '/auth/failure', to: 'sessions#failure'
end
OutputSuccess
Important Notes

Always keep your APP_SECRET private and never share it.

Test OAuth flows in development using localhost URLs registered in the provider settings.

Handle authentication failures gracefully to improve user experience.

Summary

OAuth lets users log in using other services without sharing passwords.

Use OmniAuth middleware in Rails to connect with OAuth providers.

Handle callbacks to create or find users and manage sessions.