# FusionAuth QuickStart for Ruby on Rails

Integrate FusionAuth with an example Ruby on Rails website.

> For the index of this section of the site, see [llms.txt](https://fusionauth.io/docs/llms.txt)

![Ruby on Rails](https://fusionauth.io/img/icons/ruby-on-rails.svg)

This QuickStart explains how to add a login page and authentication to a website built with [Ruby on Rails](https://rubyonrails.org/). 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:

*   [Ruby](https://www.ruby-lang.org/en/documentation/installation/) 3.2 or later
*   [Docker](https://docs.docker.com/get-started/get-docker/) 23 or later

If you use macOS or Windows, you need one of the following container management tools:

*   [Docker Desktop](https://www.docker.com/products/docker-desktop/)
*   [OrbStack](https://docs.orbstack.dev/quick-start) (to use OrbStack for `docker compose` commands after installation, run `docker context use orbstack`)
*   [Podman](https://podman.io/docs/installation) (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:
    
    ```shell-session
    $ gem install rails -v 8.1.4.1
    ```
    
2.  Create a Rails app named `rails-quickstart` and navigate into its folder:
    
    ```shell-session
    $ rails new rails-quickstart --minimal --skip-active-record
    ```
    
    ```shell-session
    $ 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:
    
    ```ruby
    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:
    
    ```erb
    <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:
    
    ```ruby
    Rails.application.routes.draw do
      root 'notes#show'
      post 'save', to: 'notes#save'
    end
    ```
    
6.  Run the app:
    
    ```shell-session
    $ bin/rails server
    ```
    
7.  Open the app at [http://localhost:3000](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](https://github.com/FusionAuth/fusionauth-quickstart-app):
    
    ```shell-session
    $ git clone https://github.com/FusionAuth/fusionauth-quickstart-app.git
    ```
    
3.  Navigate into the cloned directory:
    
    ```shell-session
    $ 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):
    
    ```shell-session
    $ 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](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`:
    
    ```shell-session
    $ 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):
    
    ```plaintext
    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:
    
    ```shell-session
    $ bundle add omniauth_openid_connect --version 0.8.0
    ```
    
    ```shell-session
    $ bundle add omniauth-rails_csrf_protection --version 2.0.1
    ```
    
    ```shell-session
    $ bundle add dotenv --version 3.2.0
    ```
    
    Most importantly, we're adding [omniauth\openid\connect](https://github.com/omniauth/omniauth_openid_connect), which handles communication with our FusionAuth instance through [OmniAuth](https://github.com/omniauth/omniauth). We're also adding [omniauth-rails\csrf\protection](https://github.com/cookpad/omniauth-rails_csrf_protection), which checks the CSRF token when a user starts the login, and [dotenv](https://github.com/bkeepers/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:
    
    ```ruby
    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 [PKCE](https://fusionauth.io/docs/authentication/oauth/authorization-code.md#proof-key-for-code-exchange), 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 token](https://fusionauth.io/docs/authentication/oauth/tokens.md#id-token), and passes the user's details to the app.
    
5.  Replace the contents of `app/controllers/application_controller.rb` with the following code:
    
    ```ruby
    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:
    
    ```ruby
    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:
    
    ```erb
    <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:
    
    ```ruby
    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:
    
    ```erb
    <%= 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:
     
     ```shell-session
     $ bin/rails server
     ```
     
11.  Open the app at [http://localhost:3000](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](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:
    
    ```ruby
    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:
    
    ```ruby
    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:
     
     ```ruby
     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:
     
     ```erb
     <%= 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:
     
     ```shell-session
     $ bin/rails server
     ```
     
13.  Open the app at [http://localhost:3000](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](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](https://fusionauth.io/docs/get-started.md).

FusionAuth has many features (including [Social Login](https://fusionauth.io/docs/authentication/identity-providers.md#social-identity-providers), [Single Sign-On](https://fusionauth.io/docs/authentication/sessions/enable-sso.md), [Passkeys](https://fusionauth.io/docs/authentication/passkeys/configure.md), [Multi-factor Authentication](https://fusionauth.io/docs/authentication/multi-factor-authentication.md)), most of which are free. This example app is a great starting point for learning about FusionAuth features.
---

## Other pages in Web

> For the full index of this section, see [Quickstarts](https://fusionauth.io/docs/llms-quickstarts.txt).

- [FusionAuth QuickStart for Python Django](https://fusionauth.io/docs/quickstarts/web/django.md): Integrate FusionAuth with an example Python Django website.
- [FusionAuth QuickStart for .NET](https://fusionauth.io/docs/quickstarts/web/dotnet.md): Learn how to add FusionAuth login to an ASP.NET Core Razor Pages app.
- [FusionAuth QuickStart for Express](https://fusionauth.io/docs/quickstarts/web/express.md): Integrate FusionAuth with an example Express website.
- [FusionAuth QuickStart for Python Flask](https://fusionauth.io/docs/quickstarts/web/flask.md): Integrate FusionAuth with an example Python Flask website.
- [Web](https://fusionauth.io/docs/quickstarts/web.md): Explore step-by-step web application QuickStart guides from FusionAuth to seamlessly integrate authentication into your application.
- [FusionAuth QuickStart for Next.js](https://fusionauth.io/docs/quickstarts/web/nextjs.md): Integrate FusionAuth with an example Next.js website.
- [FusionAuth QuickStart for Nuxt](https://fusionauth.io/docs/quickstarts/web/nuxt.md): Integrate FusionAuth with an example Nuxt website.
- [FusionAuth QuickStart for Golang](https://fusionauth.io/docs/quickstarts/web/quickstart-golang-web.md): QuickStart integration of a Golang web application with FusionAuth using the CoreOS OIDC library.
- [FusionAuth QuickStart for Remix](https://fusionauth.io/docs/quickstarts/web/quickstart-javascript-remix-web.md): QuickStart integration of Javascript Remix web application with FusionAuth.
- [FusionAuth QuickStart for Drupal](https://fusionauth.io/docs/quickstarts/web/quickstart-php-drupal-web.md): QuickStart integration of Drupal web application with FusionAuth.
- [FusionAuth QuickStart for Laravel](https://fusionauth.io/docs/quickstarts/web/quickstart-php-laravel-web.md): QuickStart integration of PHP Laravel web application with FusionAuth.
- [FusionAuth QuickStart for PHP](https://fusionauth.io/docs/quickstarts/web/quickstart-php-web.md): QuickStart integration of PHP web application with FusionAuth.
- [FusionAuth QuickStart for Rust with Actix](https://fusionauth.io/docs/quickstarts/web/quickstart-rust-actix-web.md): QuickStart integration of a Rust Actix web application with FusionAuth.
- [FusionAuth QuickStart for WordPress](https://fusionauth.io/docs/quickstarts/web/quickstart-wordpress-web.md): QuickStart integration of WordPress application with FusionAuth.
- [FusionAuth QuickStart for Spring Boot With Thymeleaf](https://fusionauth.io/docs/quickstarts/web/spring-boot.md): Learn how to add FusionAuth login to a Spring Boot app with Thymeleaf.
