FusionAuth QuickStart for Ruby on Rails
On this page
This QuickStart explains how to add a login page and authentication to a website built with Ruby on Rails. You'll begin with a simple Rails app that allows visitors to edit a file. Then, you'll add authentication to the app with a FusionAuth instance. Finally, you'll extend the app to handle multiple independent users with user data provided by FusionAuth.
This tutorial should take between 5 and 15 minutes; less if you already have prerequisites like Docker installed.
Prerequisites#
This QuickStart requires:
If you use macOS or Windows, you need one of the following container management tools:
- Docker Desktop
- OrbStack (to use OrbStack for
docker composecommands after installation, rundocker context use orbstack) - Podman (in the commands below, replace
dockerwithpodman)
Create a Simple Rails App#
For this QuickStart, we'll use a Rails app that reads and writes data to a text file:
-
Install Rails:
$ gem install rails -v 8.1.4.1 -
Create a Rails app named
rails-quickstartand navigate into its folder:$ rails new rails-quickstart --minimal --skip-active-record$ cd rails-quickstartThe
--minimalflag leaves out the optional Rails frameworks, and--skip-active-recordleaves out the database, because the app stores its data in a text file. -
In the
app/controllersfolder, create a file namednotes_controller.rbwith the following contents:class NotesController < ApplicationController TARGET_FILE = Rails.root.join('note.txt') def show # Ensure the file exists so we don't crash File.write(TARGET_FILE, 'Hello! Edit this text.') unless File.exist?(TARGET_FILE) @content = File.read(TARGET_FILE) end def save File.write(TARGET_FILE, params[:content]) redirect_to root_path # Refresh the page to show updated content end end -
In the
app/viewsfolder, create a folder namednotes. In thenotesfolder, create a file namedshow.html.erbwith the following contents:<h1>Edit: note.txt</h1> <%= form_with url: '/save' do %> <%= text_area_tag :content, @content, style: 'width: 100%; height: 300px; padding: 10px' %> <br> <%= button_tag 'Save Changes', style: 'padding: 10px 20px; background: #007bff; color: white; border: none' %> <% end %>form_withadds a CSRF token to the form, because Rails rejects form submissions without one. -
Replace the contents of
config/routes.rbwith the following code, which connects the URLs to the controller:Rails.application.routes.draw do root 'notes#show' post 'save', to: 'notes#save' end -
Run the app:
$ bin/rails server -
Open the app at http://localhost:3000.
-
Replace the text area text with "Hello Rails", then click the Save Changes button.
-
In a file browser or terminal, look in the
rails-quickstartfolder. You should see a new file namednote.txt, with text content "Hello Rails". -
Congratulations, you have a working Rails app that lets you edit a local text file through your web browser. Press Ctrl+C on your keyboard to stop the Rails server.
Install and Run FusionAuth#
Before we can add authentication to our Rails app, we need a local FusionAuth instance:
-
Open your container management tool (listed in the prerequisites above).
-
From the
rails-quickstartfolder, clone the GitHub repository for the FusionAuth instance you'll use with this QuickStart:$ git clone https://github.com/FusionAuth/fusionauth-quickstart-app.git -
Navigate into the cloned directory:
$ cd fusionauth-quickstart-app -
To start a local instance of FusionAuth, run the following command (omit the
-dflag to see all Docker logs):$ docker compose up -d -
Wait until all networks, volumes, and containers show a green status of Healthy, Started, or Created. This may take a few minutes, depending on your network speed and cached dependencies.
-
Open http://localhost:9011/admin to access the FusionAuth Admin UI.
-
Log in with these credentials:
- username:
admin@example.com - password:
password
- username:
-
Navigate to Applications -> QuickStart App -> Edit -> OAuth . On this page, you can find your client ID, your client secret, and specify redirect and logout URLs. In the next part of this QuickStart, we'll use these values to connect our Rails app with FusionAuth.
-
Click the logout icon in the top right to log out of the Admin UI. We'll use a different user account to access our Rails app, and because FusionAuth supports SSO, we need to log out of our admin account before we can log in as a normal user.
Add FusionAuth to the Rails App#
Now that you have a working instance of FusionAuth and a working Rails app, let's use FusionAuth to add login to your Rails app:
-
Navigate out of the
fusionauth-quickstart-appfolder, back to therails-quickstartfolder that containsappandnote.txt:$ cd .. -
Create a file named
.envwith the following contents (we provided the same configuration for the local FusionAuth instance, and then viewed it in the Admin UI):FUSIONAUTH_CLIENT_ID=f0510a74-da7a-4101-a474-05e7f1d5ba7e FUSIONAUTH_CLIENT_SECRET=super-secret-secret-that-should-be-regenerated-for-production FUSIONAUTH_CALLBACK_URL=http://localhost:3000/oauth-callback -
Install the dependencies we'll need to authenticate with FusionAuth:
$ bundle add omniauth_openid_connect --version 0.8.0$ bundle add omniauth-rails_csrf_protection --version 2.0.1$ bundle add dotenv --version 3.2.0Most importantly, we're adding omniauth_openid_connect, which handles communication with our FusionAuth instance through OmniAuth. We're also adding omniauth-rails_csrf_protection, which checks the CSRF token when a user starts the login, and dotenv, which reads our configuration from the
.envfile we just created. -
In the
config/initializersfolder, create a file namedomniauth.rbwith the following contents:FUSIONAUTH_URL = 'http://localhost:9011' # the local FusionAuth instance uses http SWD.url_builder = URI::HTTP # only accept login requests for the app's own host OmniAuth.config.allowed_hosts = ['localhost'] # tell OmniAuth how to talk to FusionAuth Rails.application.config.middleware.use OmniAuth::Builder do provider :openid_connect, name: :fusionauth, issuer: FUSIONAUTH_URL, discovery: true, scope: [:openid], pkce: true, callback_path: '/oauth-callback', client_options: { identifier: ENV['FUSIONAUTH_CLIENT_ID'], secret: ENV['FUSIONAUTH_CLIENT_SECRET'], redirect_uri: ENV['FUSIONAUTH_CALLBACK_URL'], } endThe new code tells OmniAuth how to talk to FusionAuth:
SWD.url_builder = URI::HTTPlets OmniAuth fetch the discovery document over http, which the local FusionAuth instance uses.OmniAuth.config.allowed_hostsstops OmniAuth from building callback URLs for any host exceptlocalhost.provider :openid_connectuses the client Id, client secret, and PKCEAn extension to OAuth 2.0 that mitigates authorization code interception attacks using dynamic code verifiers and challenges., and finds the login and token endpoints in the OpenID Connect discovery document at/.well-known/openid-configuration. With PKCE, OmniAuth sends a code verifier when it exchanges the authorization code for tokens, so a stolen authorization code is useless on its own.
OmniAuth adds an
/auth/fusionauthroute, which sends the user to the FusionAuth login page. It also handles the/oauth-callbackroute: it exchanges the authorization code from FusionAuth for tokens, validates the ID tokenA JSON Web Token that contains information about the authenticated user., and passes the user's details to the app. -
Replace the contents of
app/controllers/application_controller.rbwith the following code:class ApplicationController < ActionController::Base allow_browser versions: :modern # require authentication to access before_action :require_login private def require_login redirect_to '/login' unless session[:user] end endThe
require_loginfilter runs before every controller action and sends users who aren't logged in to/login. -
In the
app/controllersfolder, create a file namedsessions_controller.rbwith the following contents:class SessionsController < ApplicationController skip_before_action :require_login def new end def create session[:user] = { 'id' => request.env['omniauth.auth'].uid } redirect_to root_path end def destroy # Clear the local Rails session reset_session # Redirect to FusionAuth to clear the SSO session redirect_to "#{FUSIONAUTH_URL}/oauth2/logout?#{{ client_id: ENV['FUSIONAUTH_CLIENT_ID'] }.to_query}", allow_other_host: true end endskip_before_actionlets users who aren't logged in reach these actions.- The
createaction runs after OmniAuth handles/oauth-callback, and stores the user's Id in the Rails session. - The
destroyaction clears the Rails session, then sends the user to FusionAuth's/oauth2/logoutendpoint so the FusionAuth session ends too.
-
In the
app/viewsfolder, create a folder namedsessions. In thesessionsfolder, create a file namednew.html.erbwith the following contents:<h1>Log in</h1> <%= button_to 'Log in with FusionAuth', '/auth/fusionauth', style: 'padding: 10px 20px; background: #007bff; color: white; border: none' %>OmniAuth only starts a login from a
POSTrequest with a CSRF token, so the login page usesbutton_toinstead of a link. -
Replace the contents of
config/routes.rbwith the following code, which adds the/login,/oauth-callback, and/logoutroutes:Rails.application.routes.draw do root 'notes#show' post 'save', to: 'notes#save' get 'login', to: 'sessions#new' get 'oauth-callback', to: 'sessions#create' get 'logout', to: 'sessions#destroy' end -
Replace the contents of
app/views/notes/show.html.erbwith the following code, which adds a Logout button:<%= link_to 'Logout', '/logout', class: 'logout-btn', style: 'float: right; background: #dc3545; color: white; padding: 8px 15px; text-decoration: none; border-radius: 4px' %> <h1>Edit: note.txt</h1> <%= form_with url: '/save' do %> <%= text_area_tag :content, @content, style: 'width: 100%; height: 300px; padding: 10px' %> <br> <%= button_tag 'Save Changes', style: 'padding: 10px 20px; background: #007bff; color: white; border: none' %> <% end %> -
That's it! Your Rails app should now use FusionAuth login. Run the app:
$ bin/rails server -
Open the app at http://localhost:3000 and click Log in with FusionAuth.
-
Log in with the following credentials:
- username:
richard@example.com - password:
password
- username:
-
Edit the text file from the safety of an authenticated Rails app.
-
Click Logout. FusionAuth ends your session and sends you back to the app's login page.
Add Independent Notes for Each User#
To see a more realistic example of FusionAuth usage, we can improve the app even more, so every user gets a unique note to edit. To accomplish this, we'll use FusionAuth's user data:
-
Open the FusionAuth Admin UI at http://localhost:9011/admin.
-
Log in with the following credentials:
- username:
admin@example.com - password:
password
- username:
-
Navigate to Applications -> QuickStart App -> Edit -> Registration .
- Under Self-service registration, check that Registration mode is set to Create registration. The QuickStart configuration has already turned on self-service registration.
- In the Registration field list, turn on the Enabled and Required switches for the following rows:
- Birthdate
- First name
- Last name
-
Click the Save button in the top right of the page to save your changes to self-service registration.
-
Navigate to Users -> Richard Hendricks -> Manage .
-
In the Source tab, look for the
firstNameandlastNamefields. That's what we'll use to personalize the UI for each user. We'll use the user'sidfield to generate a unique name for each user's note. -
Click the logout icon in the top right to log out of the Admin UI. We'll use a different user account to access our Rails app.
-
Replace the contents of
config/initializers/omniauth.rbwith the following code, which also requests theprofileandemailscopes:FUSIONAUTH_URL = 'http://localhost:9011' # the local FusionAuth instance uses http SWD.url_builder = URI::HTTP # only accept login requests for the app's own host OmniAuth.config.allowed_hosts = ['localhost'] # tell OmniAuth how to talk to FusionAuth Rails.application.config.middleware.use OmniAuth::Builder do provider :openid_connect, name: :fusionauth, issuer: FUSIONAUTH_URL, discovery: true, scope: [:openid, :profile, :email], pkce: true, callback_path: '/oauth-callback', client_options: { identifier: ENV['FUSIONAUTH_CLIENT_ID'], secret: ENV['FUSIONAUTH_CLIENT_SECRET'], redirect_uri: ENV['FUSIONAUTH_CALLBACK_URL'], } end -
Replace the contents of
app/controllers/sessions_controller.rbwith the following code, which reads the user's name (first and last) and email and stores them in the session:class SessionsController < ApplicationController skip_before_action :require_login def new end def create # OmniAuth validates the ID token and puts the user's details in info auth = request.env['omniauth.auth'] full_name = "#{auth.info.first_name} #{auth.info.last_name}".strip session[:user] = { 'id' => auth.uid, 'email' => auth.info.email, 'name' => full_name.presence || auth.info.email || 'User', } redirect_to root_path end def destroy # Clear the local Rails session reset_session # Redirect to FusionAuth to clear the SSO session redirect_to "#{FUSIONAUTH_URL}/oauth2/logout?#{{ client_id: ENV['FUSIONAUTH_CLIENT_ID'], post_logout_redirect_uri: 'http://localhost:3000/login', }.to_query}", allow_other_host: true end endOmniAuth validates the ID token and puts the user's details in
auth.info, so we don't need a separate JWT library. Thedestroyaction also passes apost_logout_redirect_uri, which sends the user back to the login page after FusionAuth ends their session. -
Replace the contents of
app/controllers/notes_controller.rbwith the following code, which stores each user's note in a separate file:class NotesController < ApplicationController # set up a directory for multi-user files DATA_DIR = Rails.root.join('user_data') FileUtils.mkdir_p(DATA_DIR) def show target_file = user_file # Ensure the file exists so we don't crash File.write(target_file, "Hello #{session[:user]['name']}!") unless File.exist?(target_file) @name = session[:user]['name'] @content = File.read(target_file) end def save File.write(user_file, params[:content]) redirect_to root_path # Refresh the page to show updated content end private # helper to get specific user file def user_file DATA_DIR.join("note-#{session[:user]['id']}.txt") end end -
Replace the contents of
app/views/notes/show.html.erbwith the following code, which shows the user's name:<%= link_to 'Logout', '/logout', class: 'logout-btn', style: 'float: right; background: #dc3545; color: white; padding: 8px 15px; text-decoration: none; border-radius: 4px' %> <p style="float: right; margin-right: 20px;">Welcome, <%= @name %></p> <h1>Personal Note Editor</h1> <%= form_with url: '/save' do %> <%= text_area_tag :content, @content, style: 'width: 100%; height: 300px; padding: 10px' %> <br> <%= button_tag 'Save Changes', style: 'padding: 10px 20px; background: #007bff; color: white; border: none' %> <% end %> -
Rails doesn't reload files in
config/initializers, so restart the server. Press Ctrl+C, then run:$ bin/rails server -
Open the app at http://localhost:3000 and click Log in with FusionAuth.
-
Log in with the following credentials:
- username:
richard@example.com - password:
password
- username:
-
In a separate private/incognito window, open the app at http://localhost:3000 and click Log in with FusionAuth.
-
Click Create an account and create an account using your personal email address, a password, your name, and your birthdate.
-
Enjoy using your unique user note! You should see your name at the top of the page, and in the default note text.
Your Rails app now provides unique notes for each user. Each user can independently edit and save their note. To see all of the notes, look for note-<id>.txt files in the user_data directory. To identify which note corresponds to which user, compare the id in the file name with the id field in the user's Source tab.
Summary#
In this QuickStart, FusionAuth handled login for your Rails app:
- OmniAuth sent users to the FusionAuth login page and exchanged the authorization code for tokens, so the app never saw their passwords.
- The
require_loginfilter kept logged-out users away from the notes page. - The ID token gave the app each user's unique Id and name. The app used the Id to keep each note separate and the name to greet the user.
- FusionAuth's self-service registration let new users create their own accounts, with no sign-up code in the app.
Next Steps#
This was a quick introduction to using FusionAuth for user authentication. To learn more about integrating FusionAuth with your product, see Get Started.
FusionAuth has many features (including Social Login, Single Sign-On, Passkeys, Multi-factor Authentication), most of which are free. This example app is a great starting point for learning about FusionAuth features.