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 compose commands after installation, run docker context use orbstack)
  • Podman (in the commands below, replace docker with podman)

Create a Simple Rails App#

For this QuickStart, we'll use a Rails app that reads and writes data to a text file:

  1. Install Rails:

    $ gem install rails -v 8.1.4.1
    
  2. Create a Rails app named rails-quickstart and navigate into its folder:

    $ rails new rails-quickstart --minimal --skip-active-record
    
    $ cd rails-quickstart
    

    The --minimal flag leaves out the optional Rails frameworks, and --skip-active-record leaves out the database, because the app stores its data in a text file.

  3. In the app/controllers folder, create a file named notes_controller.rb with 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
  4. In the app/views folder, create a folder named notes. In the notes folder, create a file named show.html.erb with 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_with adds a CSRF token to the form, because Rails rejects form submissions without one.

  5. Replace the contents of config/routes.rb with the following code, which connects the URLs to the controller:

    Rails.application.routes.draw do
      root 'notes#show'
      post 'save', to: 'notes#save'
    end
  6. Run the app:

    $ bin/rails server
    
  7. Open the app at http://localhost:3000.

  8. Replace the text area text with "Hello Rails", then click the Save Changes button.

  9. In a file browser or terminal, look in the rails-quickstart folder. You should see a new file named note.txt, with text content "Hello Rails".

  10. 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:

  1. Open your container management tool (listed in the prerequisites above).

  2. From the rails-quickstart folder, clone the GitHub repository for the FusionAuth instance you'll use with this QuickStart:

    $ git clone https://github.com/FusionAuth/fusionauth-quickstart-app.git
    
  3. Navigate into the cloned directory:

    $ cd fusionauth-quickstart-app
    
  4. To start a local instance of FusionAuth, run the following command (omit the -d flag to see all Docker logs):

    $ docker compose up -d
    
  5. 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.

  6. Open http://localhost:9011/admin to access the FusionAuth Admin UI.

  7. Log in with these credentials:

    • username: admin@example.com
    • password: password
  8. 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.

  9. 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:

  1. Navigate out of the fusionauth-quickstart-app folder, back to the rails-quickstart folder that contains app and note.txt:

    $ cd ..
    
  2. Create a file named .env with 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
  3. 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.0
    

    Most 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 .env file we just created.

  4. In the config/initializers folder, create a file named omniauth.rb with 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'],
        }
    end

    The new code tells OmniAuth how to talk to FusionAuth:

    • SWD.url_builder = URI::HTTP lets OmniAuth fetch the discovery document over http, which the local FusionAuth instance uses.
    • OmniAuth.config.allowed_hosts stops OmniAuth from building callback URLs for any host except localhost.
    • provider :openid_connect uses 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/fusionauth route, which sends the user to the FusionAuth login page. It also handles the /oauth-callback route: 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.

  5. Replace the contents of app/controllers/application_controller.rb with 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
    end

    The require_login filter runs before every controller action and sends users who aren't logged in to /login.

  6. In the app/controllers folder, create a file named sessions_controller.rb with 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
    end
    • skip_before_action lets users who aren't logged in reach these actions.
    • The create action runs after OmniAuth handles /oauth-callback, and stores the user's Id in the Rails session.
    • The destroy action clears the Rails session, then sends the user to FusionAuth's /oauth2/logout endpoint so the FusionAuth session ends too.
  7. In the app/views folder, create a folder named sessions. In the sessions folder, create a file named new.html.erb with 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 POST request with a CSRF token, so the login page uses button_to instead of a link.

  8. Replace the contents of config/routes.rb with the following code, which adds the /login, /oauth-callback, and /logout routes:

    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
  9. Replace the contents of app/views/notes/show.html.erb with 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 %>
  10. That's it! Your Rails app should now use FusionAuth login. Run the app:

    $ bin/rails server
    
  11. Open the app at http://localhost:3000 and click Log in with FusionAuth.

  12. Log in with the following credentials:

    • username: richard@example.com
    • password: password
  13. Edit the text file from the safety of an authenticated Rails app.

  14. 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:

  1. Open the FusionAuth Admin UI at http://localhost:9011/admin.

  2. Log in with the following credentials:

    • username: admin@example.com
    • password: password
  3. 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
  4. Click the Save button in the top right of the page to save your changes to self-service registration.

  5. Navigate to Users -> Richard Hendricks -> Manage .

  6. In the Source tab, look for the firstName and lastName fields. That's what we'll use to personalize the UI for each user. We'll use the user's id field to generate a unique name for each user's note.

  7. 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.

  8. Replace the contents of config/initializers/omniauth.rb with the following code, which also requests the profile and email scopes:

    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
  9. Replace the contents of app/controllers/sessions_controller.rb with 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
    end

    OmniAuth validates the ID token and puts the user's details in auth.info, so we don't need a separate JWT library. The destroy action also passes a post_logout_redirect_uri, which sends the user back to the login page after FusionAuth ends their session.

  10. Replace the contents of app/controllers/notes_controller.rb with 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
  11. Replace the contents of app/views/notes/show.html.erb with 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 %>
  12. Rails doesn't reload files in config/initializers, so restart the server. Press Ctrl+C, then run:

    $ bin/rails server
    
  13. Open the app at http://localhost:3000 and click Log in with FusionAuth.

  14. Log in with the following credentials:

    • username: richard@example.com
    • password: password
  15. In a separate private/incognito window, open the app at http://localhost:3000 and click Log in with FusionAuth.

  16. Click Create an account and create an account using your personal email address, a password, your name, and your birthdate.

  17. 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_login filter 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.