OAuth helps your app let users log in using other services safely. It avoids asking for passwords directly.
OAuth integration basics in 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.
provider :google_oauth2, 'GOOGLE_CLIENT_ID', 'GOOGLE_CLIENT_SECRET'
provider :facebook, 'FACEBOOK_APP_ID', 'FACEBOOK_APP_SECRET'
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.
# 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
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.
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.