fusionauth logo
search-interface-symbol
Downloads
Quickstarts
API Docs
SDK
search-interface-symbol
talk to an expert
Log In
talk to an expert
Navigate to...
  • Welcome
  • Getting Started
    • Getting Started
    • 5-minute Setup Guide
      • Overview
      • Docker
      • Fast Path
      • Sandbox
    • Setup Wizard & First Login
    • Register a User and Login
    • Self-service Registration
    • Start and Stop FusionAuth
    • Core Concepts
      • Overview
      • Users
      • Roles
      • Groups
      • Registrations
      • Applications
      • Tenants
      • Identity Providers
      • Authentication/Authorization
      • Integration Points
    • Example Apps
      • Overview
      • Dart
      • Go
      • Java
      • JavaScript
      • .NET Core
      • PHP
      • Python
      • Ruby
    • Tutorials
      • Overview
      • Express.js
      • Java Spring
      • Python Django
      • Python Flask
      • React
      • Ruby on Rails
      • Ruby on Rails API
  • Installation Guide
    • Overview
    • System Requirements
    • Server Layout
    • Cloud
    • Cluster
    • Docker
    • Fast Path
    • Kubernetes
      • Overview
      • Deployment Guide
      • Minikube Setup
      • Amazon EKS Setup
      • Google GKE Setup
      • Microsoft AKS Setup
    • Kickstart™
    • Homebrew
    • Marketplaces
    • Packages
    • Database
    • FusionAuth App
    • FusionAuth Search
    • Common Configuration
  • Migration Guide
    • Overview
    • General
    • Auth0
    • Keycloak
    • Amazon Cognito
    • Firebase
    • Microsoft Azure AD B2C
    • Tutorial
  • Admin Guide
    • Overview
    • Account Portal
    • Config Management
    • Editions and Features
    • Key Rotation
    • Licensing
    • Monitoring
    • Prometheus Setup
    • Proxy Setup
    • Reference
      • Overview
      • Configuration
      • CORS
      • Data Types
      • Hosted Login Pages Cookies
      • Known Limitations
      • Password Hashes
    • Releases
    • Roadmap
    • Search And FusionAuth
    • Securing
    • Switch Search Engines
    • Technical Support
    • Troubleshooting
    • Upgrading
    • WebAuthn
  • Login Methods
    • Identity Providers
      • Overview
      • Apple
      • Epic Games
      • External JWT
        • Overview
        • Example
      • Facebook
      • Google
      • HYPR
      • LinkedIn
      • Nintendo
      • OpenID Connect
        • Overview
        • Amazon Cognito
        • Azure AD
        • Discord
        • Github
        • Okta
      • Sony PlayStation Network
      • Steam
      • Twitch
      • Twitter
      • SAML v2
        • Overview
        • ADFS
        • Azure AD
        • Okta
      • SAML v2 IdP Initiated
        • Overview
        • Okta
      • Xbox
    • OIDC & OAuth 2.0
      • Overview
      • Endpoints
      • Tokens
      • OAuth Modes
      • URL Validation
      • Integrations
        • CockroachDB
        • Salesforce
    • Passwordless
      • Overview
      • Magic Links
      • WebAuthn & Passkeys
    • SAML v2 IdP
      • Overview
      • Google
      • PagerDuty
      • SendGrid
      • Tableau Cloud
      • Zendesk
  • Developer Guide
    • Overview
    • API Gateways
      • Overview
      • Amazon API Gateway
      • Kong Gateway
      • ngrok Cloud Edge
    • Client Libraries & SDKs
      • Overview
      • Dart
      • Go
      • Java
      • JavaScript
      • .NET Core
      • Node
      • OpenAPI
      • PHP
      • Python
      • React
      • Ruby
      • Typescript
    • Events & Webhooks
      • Overview
      • Writing a Webhook
      • Securing Webhooks
      • Events
        • Overview
        • Audit Log Create
        • Event Log Create
        • JWT Public Key Update
        • JWT Refresh
        • JWT Refresh Token Revoke
        • Kickstart Success
        • Group Create
        • Group Create Complete
        • Group Delete
        • Group Delete Complete
        • Group Update
        • Group Update Complete
        • Group Member Add
        • Group Member Add Complete
        • Group Member Remove
        • Group Member Remove Complete
        • Group Member Update
        • Group Member Update Complete
        • User Action
        • User Bulk Create
        • User Create
        • User Create Complete
        • User Deactivate
        • User Delete
        • User Delete Complete
        • User Email Update
        • User Email Verified
        • User IdP Link
        • User IdP Unlink
        • User Login Failed
        • User Login Id Dup. Create
        • User Login Id Dup. Update
        • User Login New Device
        • User Login Success
        • User Login Suspicious
        • User Password Breach
        • User Password Reset Send
        • User Password Reset Start
        • User Password Reset Success
        • User Password Update
        • User Reactivate
        • User Reg. Create
        • User Reg. Create Complete
        • User Reg. Delete
        • User Reg. Delete Complete
        • User Registration Update
        • User Reg. Update Complete
        • User Reg. Verified
        • User 2FA Method Add
        • User 2FA Method Remove
        • User Update
        • User Update Complete
    • Guides
      • Overview
      • Application Specific Email Templates
      • Authentication Tokens
      • Exposing A Local Instance
      • JSON Web Tokens
      • Key Master
      • Localization and Internationalization
      • Multi-Factor Authentication
      • Multi-Tenant
      • Passwordless
      • Registration-based Email Verification
      • Searching With Elasticsearch
      • Securing Your APIs
      • Silent Mode
      • Single Sign-on
      • Two Factor (pre 1.26)
    • Integrations
      • Overview
      • CleanSpeak
      • Kafka
      • Twilio
    • Plugins
      • Overview
      • Writing a Plugin
      • Custom Password Hashing
    • User Control & Gating
      • Overview
      • Gate Unverified Users
      • Gate Unverified Registrations
      • User Account Lockout
  • Customization
    • Email & Templates
      • Overview
      • Configure Email
      • Email Templates
      • Email Variables
      • Message Templates
    • Lambdas
      • Overview
      • Apple Reconcile
      • Client Cred. JWT Populate
      • Epic Games Reconcile
      • External JWT Reconcile
      • Facebook Reconcile
      • Google Reconcile
      • HYPR Reconcile
      • JWT Populate
      • LDAP Connector Reconcile
      • LinkedIn Reconcile
      • Nintendo Reconcile
      • OpenID Connect Reconcile
      • SAML v2 Populate
      • SAML v2 Reconcile
      • SCIM Group Req. Converter
      • SCIM Group Resp. Convtr.
      • SCIM User Req. Converter
      • SCIM User Resp. Converter
      • Self-Service Registration
      • Sony PSN Reconcile
      • Steam Reconcile
      • Twitch Reconcile
      • Twitter Reconcile
      • Xbox Reconcile
    • Messengers
      • Overview
      • Generic Messenger
      • Twilio Messenger
    • Themes
      • Overview
      • Examples
      • Helpers
      • Localization
      • Template Variables
      • Kickstart Custom Theme
  • Premium Features
    • Overview
    • Advanced Registration Forms
    • Advanced Threat Detection
    • Application Specific Themes
    • Breached Password Detection
    • Connectors
      • Overview
      • Generic Connector
      • LDAP Connector
      • FusionAuth Connector
    • Entity Management
    • SCIM
      • Overview
      • Azure AD Client
      • Okta Client
      • SCIM-SDK
    • Self Service Account Mgmt
      • Overview
      • Updating User Data & Password
      • Add Two-Factor Authenticator
      • Add Two-Factor Email
      • Add Two-Factor SMS
      • Add WebAuthn Passkey
      • Customizing
      • Bootstrapping Login
      • Troubleshooting
    • WebAuthn
  • APIs
    • Overview
    • Authentication
    • Errors
    • API Explorer
    • Actioning Users
    • API Keys
    • Applications
    • Audit Logs
    • Connectors
      • Overview
      • Generic
      • LDAP
    • Consents
    • Emails
    • Entity Management
      • Overview
      • Entities
      • Entity Types
      • Grants
    • Event Logs
    • Families
    • Forms
    • Form Fields
    • Groups
    • Hosted Backend
    • Identity Providers
      • Overview
      • Links
      • Apple
      • External JWT
      • Epic Games
      • Facebook
      • Google
      • HYPR
      • LinkedIn
      • Nintendo
      • OpenID Connect
      • SAML v2
      • SAML v2 IdP Initiated
      • Sony PlayStation Network
      • Steam
      • Twitch
      • Twitter
      • Xbox
    • Integrations
    • IP Access Control Lists
    • JWT
    • Keys
    • Lambdas
    • Login
    • Message Templates
    • Messengers
      • Overview
      • Generic
      • Twilio
    • Multi-Factor/Two Factor
    • Passwordless
    • Reactor
    • Registrations
    • Reports
    • SCIM
      • Overview
      • SCIM User
      • SCIM Group
      • SCIM EnterpriseUser
      • SCIM Service Provider Config.
    • System
    • Tenants
    • Themes
    • Users
    • User Actions
    • User Action Reasons
    • User Comments
    • WebAuthn
    • Webhooks
  • Release Notes

    Integrate Your Ruby on Rails Application With FusionAuth

    Integrate Your Ruby on Rails Application With FusionAuth

    In this tutorial, you are going to learn how to integrate a Ruby on Rails application with FusionAuth.

    Here’s a typical application login flow before integrating FusionAuth into your Ruby on Rails application.

    Login before FusionAuth.
    Login before FusionAuth.

    And here’s the same application login flow when FusionAuth is introduced.

    Login with FusionAuth.
    Login with FusionAuth.

    Prerequisites

    For this tutorial, you’ll need to have Ruby, bundler and Rails installed.

    You’ll also need Docker, since that is how you’ll install FusionAuth.

    The commands below are for macOS, but are limited to mkdir and cd, which have equivalent in Windows and Linux.

    Download and Install FusionAuth

    First, make a project directory:

    
    mkdir integrate-fusionauth && cd integrate-fusionauth

    Then, install FusionAuth:

    
    curl -o docker-compose.yml https://raw.githubusercontent.com/FusionAuth/fusionauth-containers/master/docker/fusionauth/docker-compose.yml
    https://raw.githubusercontent.com/FusionAuth/fusionauth-containers/master/docker/fusionauth/docker-compose.override.yml
    curl -o .env https://raw.githubusercontent.com/FusionAuth/fusionauth-containers/master/docker/fusionauth/.env
    docker-compose up -d

    Create a User and an API Key

    Next, log into your FusionAuth instance. You’ll need to set up a user and a password, as well as accept the terms and conditions.

    Then, you’re at the FusionAuth admin UI. This lets you configure FusionAuth manually. But for this tutorial, you’re going to create an API key and then you’ll configure FusionAuth using our Ruby client library.

    Navigate to Settings → API Keys. Click the + button to add a new API Key. Copy the value of the Key field and then save the key. It might be a value like CY1EUq2oAQrCgE7azl3A2xwG-OEwGPqLryDRBCoz-13IqyFYMn1_Udjt.

    Doing so creates an API key that can be used for any FusionAuth API call. Save that key value off as you’ll be using it later.

    Configure FusionAuth

    Next, you need to set up FusionAuth. This can be done in different ways, but we’re going to use the Ruby client library. The below instructions use maven from the command line, but you can use the client library with an IDE of your preference as well.

    First, make a directory:

    
    mkdir setup-fusionauth && cd setup-fusionauth

    Now, copy and paste the following file into Gemfile.

    Your FusionAuth Gemfile
    
    source 'https://rubygems.org'
    
    gem "fusionauth_client"

    Install the gems.

    
    bundle install

    Then copy and paste the following code into the setup.rb file.

    
    require 'fusionauth/fusionauth_client'
    
    APPLICATION_ID = "e9fdb985-9173-4e01-9d73-ac2d60d1dc8e";
    RSA_KEY_ID = "356a6624-b33c-471a-b707-48bbfcfbc593"
    
    #  You must supply your API key as an envt var
    api_key_name = 'fusionauth_api_key'
    api_key = ENV[api_key_name]
    
    unless api_key
      puts "please set api key in the '" + api_key_name.to_s + "' environment variable"
      exit 1
    end
    
    client = FusionAuth::FusionAuthClient.new(api_key, 'http://localhost:9011')
    
    # set the issuer up correctly
    client_response = client.retrieve_tenants()
    if client_response.was_successful
      tenant = client_response.success_response["tenants"][0]
    else
      puts "couldn't find tenants " + client_response.error_response.to_s
      exit 1
    end
    
    
    client_response = client.patch_tenant(tenant["id"], {"tenant": {"issuer":"http://localhost:9011"}})
    unless client_response.was_successful
      puts "couldn't update tenant "+ client_response.error_response.to_s
      exit 1
    end
    
    # generate RSA keypair for signing
    
    client_response = client.generate_key(RSA_KEY_ID, {"key": {"algorithm":"RS256", "name":"For RailsExampleApp", "length": 2048}})
    unless client_response.was_successful
      puts "couldn't create RSA key "+ client_response.error_response.to_s
      exit 1
    end
    
    # create application
    # too much to inline it
    
    application = {}
    application["name"] = "RubyExampleApp"
    
    # configure oauth
    application["oauthConfiguration"] = {}
    application["oauthConfiguration"]["authorizedRedirectURLs"] = ["http://localhost:3000/auth/my_provider/callback"]
    application["oauthConfiguration"]["requireRegistration"] = true
    application["oauthConfiguration"]["enabledGrants"] = ["authorization_code", "refresh_token"]
    application["oauthConfiguration"]["logoutURL"] = "http://localhost:3000/"
    application["oauthConfiguration"]["clientSecret"] = "change-this-in-production-to-be-a-real-secret"
    
    # assign key from above to sign our tokens. This needs to be asymmetric
    application["jwtConfiguration"] = {}
    application["jwtConfiguration"]["enabled"] = true
    application["jwtConfiguration"]["accessTokenKeyId"] = RSA_KEY_ID
    application["jwtConfiguration"]["idTokenKeyId"] = RSA_KEY_ID
    
    client_response = client.create_application(APPLICATION_ID, {"application": application})
    unless client_response.was_successful
      puts "couldn't create application "+ client_response.error_response.to_s
      exit 1
    end
    
    # register user, there should be only one, so grab the first
    client_response = client.search_users_by_query({"search": {"queryString":"*"}})
    unless client_response.was_successful
      puts "couldn't find users "+ client_response.error_response.to_s
      exit 1
    end
    
    user = client_response.success_response["users"][0]
    
    # patch the user to make sure they have a full name, otherwise OIDC has issues
    client_response = client.patch_user(user["id"], {"user": {"fullName": user["firstName"]+" "+user["lastName"]}})
    unless client_response.was_successful
      puts "couldn't patch user "+ client_response.error_response.to_s
      exit 1
    end
    
    # now register the user
    client_response = client.register(user["id"], {"registration":{"applicationId":APPLICATION_ID}})
    unless client_response.was_successful
      puts "couldn't register user "+ client_response.error_response.to_s
      exit 1
    end

    Then, you can run the setup script.

    The setup script is designed to run on a newly installed FusionAuth instance with only one user and no tenants other than Default. To follow this guide on a FusionAuth instance that does not meet these criteria, you may need to modify the above script.

    Refer to the Ruby client library documentation for more information.

    This will create the FusionAuth configuration for your Ruby on Rails application.

    
    fusionauth_api_key=YOUR_API_KEY_FROM_ABOVE ruby setup.rb

    If you are using PowerShell, you will need to set the environment variable in a separate command before executing the script.

    
    $env:fusionauth_api_key='YOUR_API_KEY_FROM_ABOVE'
    ruby setup.rb

    If you want, you can login to your instance and examine the new application configuration the script created for you.

    Create Your Ruby on Rails Application

    Now you are going to create a Ruby on Rails application. While this section uses a simple Ruby on Rails application, you can use the same configuration to integrate your Ruby on Rails application with FusionAuth.

    First, make a directory:

    
    mkdir ../setup-ruby-on-rails && cd ../setup-ruby-on-rails

    Then, set up a new rails app.

    
    rails new myapp && cd myapp

    Install the omniauth gem and other supporting gems. Add the following to your Gemfile.

    
    gem "omniauth"
    gem "omniauth-rails_csrf_protection"
    gem "omniauth_openid_connect"

    Then, install them.

    
    bundle install

    Next, update your config/environments/development.rb file with FusionAuth OIDC configuration information.

    
      # fusionauth oidc configuration
      config.x.fusionauth.issuer = "http://localhost:9011"
      config.x.fusionauth.client_id = "e9fdb985-9173-4e01-9d73-ac2d60d1dc8e"

    You’ll have to add similar configuration to the relevant environment files when deploying to prod or other environments.

    Create a file called omniauth.rb in the config/initializers directory. Add the below to the file.

    Your omniauth.rb initializer
    
    
    # only if you want a link instead of a button for login
    #OmniAuth.config.allowed_request_methods = [:post, :get]
    
    Rails.application.config.middleware.use OmniAuth::Builder do
      provider :openid_connect,
      name: :my_provider,
      scope: [:openid],
      response_type: :code,
      issuer: Rails.configuration.x.fusionauth.issuer,
      ssl: false,
      client_options: {
        # discovery doesn't work with local development
        authorization_endpoint: Rails.configuration.x.fusionauth.issuer+"/oauth2/authorize",
        token_endpoint: Rails.configuration.x.fusionauth.issuer+"/oauth2/token",
        userinfo_endpoint: Rails.configuration.x.fusionauth.issuer+"/oauth2/userinfo",
        jwks_uri: Rails.configuration.x.fusionauth.issuer+"/.well-known/jwks.json",
        identifier: Rails.configuration.x.fusionauth.client_id,
        secret: ENV["OP_SECRET_KEY"],
        redirect_uri: 'http://localhost:3000/auth/my_provider/callback',
        send_nonce: false
      }
    end

    This pulls from the environment file and configures omniauth to communicate with FusionAuth.

    Next, you can create the following controllers and scaffolding.

    
    rails generate controller auth
    rails generate controller home
    rails generate scaffold todos
    rails db:migrate

    These controllers have the following purposes:

    • auth is for omniauth integration

    • home is an unprotected home page with a login button

    • todos is a set of protected CRUD pages; in a real world application these would be built out further.

    First, let’s update the config/routes.rb file. Here’s what that should look like:

    Your routes
    
    Rails.application.routes.draw do
      resources :todos
      get 'login', to: 'home#index'
      get 'logout', to: 'auth#logout'
      get 'auth/:provider/callback', to: 'auth#callback'
      root to: 'home#index'
    end

    Nothing too special here:

    • todos is the CRUD resource.

    • login points you to the home page, which is available to unauthenticated users. This is also the default page.

    • logout is tied to the auth controller’s logout method.

    • auth/:provider/callback is the omniauth callback method, which completes the OIDC grant.

    Now, update the auth controller at app/controllers/auth_controller.rb to look like this, which fulfills some of the routes above.

    This lets us have a nice logout method and also handle the callback from omniauth. The latter sets a session attribute with user data, which can be used by views later.

    Your auth controller
    
    class AuthController < ApplicationController
    
      skip_before_action :authenticate_user!
    
      def logout
        session[:user] = nil
        redirect_to Rails.configuration.x.fusionauth.issuer+"/oauth2/logout?client_id="+Rails.configuration.x.fusionauth.client_id
      end
    
      def callback
        #puts request.env['omniauth.auth'].info.inspect
        session[:user] = request.env['omniauth.auth'].info
        redirect_to todos_path
      end
    end

    Now, update the application controller at app/controllers/application_controller.rb. You’re enforcing authentication for all routes in your application by checking for the session attribute set by the auth controller after a successful login.

    Your application controller
    
    class ApplicationController < ActionController::Base
    
       before_action :authenticate_user!
    
       def authenticate_user!
         redirect_to '/login' unless session[:user]
       end
    
    end

    Now, let’s build out the home page. Update the home controller at app/controllers/home_controller.rb to look like this:

    Your homepage controller
    
    class HomeController < ApplicationController
    
      skip_before_action :authenticate_user!
    
      def index
      end
    
    end

    You’re skipping authentication for this route. This is so that a user has someplace to go if they are unauthenticated.

    The view is also welcoming, but prompts them to login. Replace app/views/home/index.html.erb with this:

    Your homepage view
    
    Home page. Welcome!
    <br/>
    <br/>
    
    Check out some <%= link_to 'todos', todos_path %>.
    
    <br/>
    <br/>
    You might have to login first.

    Finally, update the layout so the user has login or logout buttons on every page. Add the below code just after the <body> tag.

    An excerpt of changes to your layout
    
        <% if !session[:user] %>
          <%= form_tag('/auth/my_provider', method: 'post', data: {turbo: false}) do %>
            <button type='submit'>Login</button>
          <% end %>
        <% else %>
          Welcome <%= session[:user]['email'] %> | <%= link_to 'Logout', '/logout' %>
        <% end %>

    Once you’ve created these files, you can test the application.

    Testing the Authentication Flow

    Start up the Ruby on Rails application using this command:

    Start the application
    
    OP_SECRET_KEY=change-this-in-production-to-be-a-real-secret bundle exec rails s

    OP_SECRET_KEY is the client secret, which was defined by the Configure FusionAuth step. You don’t want to commit secrets like this to version control, so use an environment variable.

    You can now open up an incognito window and visit the Ruby on Rails app. Log in with the user account you created when setting up FusionAuth, and you’ll see the email of the user next to a logout link.

    Feedback

    How helpful was this page?

    See a problem?

    File an issue in our docs repo

    Have a question or comment to share?

    Visit the FusionAuth community forum.

    © 2023 FusionAuth
    How-to
    Blog
    Expert Advice
    Download
    Release Notes
    Subscribe for developer updates