Authentication
This guide covers adding user authentication with OmniAuth and its
:developer strategy. It assumes you have already followed the
Rails Setup guide and have a running
Dockerized Rails app.
Authentication with OmniAuth
There are a lot of ways to handle authentication in Rails. The two most popular gems are OmniAuth and Devise.
We recommend starting with OmniAuth because its :developer strategy lets
you get going very quickly, and you can
integrate it with Devise
or a service like Auth0 or
Frontegg later if you choose.
Add the relevant gems to your Gemfile and re-run bundle install:
# Gemfile
gem "omniauth"
gem "omniauth-rails_csrf_protection"After installing, you will need to restart your Rails server. You can use
just app-restart for a quick restart, or touch a file to restart just the
web process:
touch tmp/restart.txt
Next, create an OmniAuth initializer:
# config/initializers/omniauth.rb
Rails.application.config.middleware.use OmniAuth::Builder do
provider :developer if Rails.env.development?
endAdd the routes for the login page and the provider callback:
# config/routes.rb
get "/auth/:provider/callback", to: "sessions#create"
get "/login", to: "sessions#new"Then add a sessions controller and a simple login view:
# app/controllers/sessions_controller.rb
class SessionsController < ApplicationController
def new
render :new
end
def create
user_info = request.env["omniauth.auth"]
raise user_info # Your own session management should be placed here.
session[:user_info] = user_info.to_hash
redirect_to root_path
end
end-# app/views/sessions/new.html.haml
- if Rails.env.development?
= form_tag("/auth/developer", method: "post", data: { turbo: false }) do
%button.btn{ type: "submit" }
Login with DeveloperVisit http://localhost:3000/login, click
the button, and enter any name and email. Because of the raise user_info
line, the app will throw an error and show you exactly where it stopped.
When you are ready for sign-in to actually work, delete or comment out the
raise user_info line and integrate session[:user_info] into your app.
That deliberate raise user_info is a great chance to inspect the
signed-in user in your browser. See the
Error Handling guide for setting up
Web Console and BetterErrors, which let you read the stack trace
and poke at live state right on the error page.