rails logo
ruby logo

Ruby on Rails Code Sample: Basic Authentication

v7
early release
Published on January 20, 2023
You are using the Early Release version of this code sample!
This is our initial take on what we believe is an idiomatic implementation of authentication in Rails.
As you explore this code sample, please help us shape its final release with your feedback: what should we start, continue, or stop doing?

This Ruby on Rails code sample powers up the "Rails Authentication By Example" guide, where you can learn how to implement authentication in Ruby on Rails web applications using Auth0.

Ruby on Rails Code Sample Specs

This code sample uses the following tools:

  • Ruby v3.1.2
  • Rails v7.0.3
  • Ruby on Rails Auth0 SDK v3.0

The Ruby on Rails project dependency installations were tested with bundler v2.3.19. Running the Ruby on Rails web application was tested using Ruby v3.1.2.

Quick Auth0 Set Up

First and foremost, if you haven't already, sign up for an Auth0 account to connect your web application with the Auth0 Identity Platform.

Next, you'll connect your web application with Auth0. You'll need to create an application registration in the Auth0 Dashboard and get three configuration values: the Auth0 Domain, the Auth0 Client ID, and the Auth0 Client Secret. You'll also need to define an Auth0 Audience value within your project to practice making secure calls to an external API.

Get the Auth0 domain and client ID

  • Open the Applications section of the Auth0 Dashboard.

  • Click on the Create Application button and fill out the form with the following values:

Name
Hello World Client
Application Type
Regular Web Applications
Regular Web Applications
  • Click on the Create button.
Visit the "Register Applications" document for more details.

An Auth0 Application page loads up.

As such, click on the "Settings" tab of your Auth0 Application page, locate the "Application URIs" section, and fill in the following values:

Allowed Callback URLs
http://localhost:4040/auth/auth0/callback
Allowed Logout URLs
http://localhost:4040

Scroll down and click the "Save Changes" button.

Next, locate the "Basic Information" section.

Auth0 application settings to enable user authentication

When you enter a value in the input fields present on this page, any code snippet that uses such value updates to reflect it. Using the input fields makes it easy to copy and paste code as you follow along.

As such, enter the "Domain" and "Client ID" values in the following fields to set up your web application in the next section:

For security, these configuration values are stored in memory and only used locally. They are gone as soon as you refresh the page! As an extra precaution, you should use values from an Auth0 test application instead of a production one.

Set Up and Run the Ruby on Rails Code Sample

Start by cloning the project into your local machine:

COMMAND
git clone https://github.com/auth0-developer-hub/web-app_rails_ruby_hello-world.git

Make the project directory your current working directory:

COMMAND
cd web-app_rails_ruby_hello-world

Then, check out the basic-authentication branch, which holds all the Ruby on Rails code related to implementing basic user authentication with Auth0:

COMMAND
git checkout basic-authentication

Next, install the Ruby on Rails project dependencies:

COMMAND
bundle install

You'll also need a session secret to sign the session ID cookie of your web application. Use the following command to generate a random secret key for Rails:

COMMAND
bin/rails secret

Copy the long-string output from the terminal and paste it into the following input box:

Create a .env file under the root project directory:

COMMAND
touch .env

Populate the .env with the following environment variables:

.env
PORT=4040
SECRET_KEY_BASE=KEY-VALUE
AUTH0_DOMAIN=AUTH0-DOMAIN
AUTH0_CLIENT_ID=AUTH0-CLIENT-ID
AUTH0_CALLBACK_PATH=/auth/auth0/callback
AUTH0_CLIENT_SECRET=AUTH0-CLIENT-SECRET

Get the Auth0 Client Secret

Head back to the "Settings" tab of your Auth0 application page in the Auth0 Dashboard to get the value for AUTH0_CLIENT_SECRET.

Locate the "Client Secret" field, copy its value, and paste it as the AUTH0_CLIENT_SECRET environment value in the .env file.

This page does not store the value of the Auth0 Client Secret. Not even in memory. Think of it as your application's password, which must be kept confidential at all times. If anyone gains access to your Client Secret, they can impersonate your application and access protected resources. The Auth0 Client Secret protects your resources by only granting authentication-related credentials in the form of tokens to requestors if they're authorized.

Run the Ruby on Rails Code Sample

Execute the following command to run the Ruby on Rails web application:

COMMAND
bin/rails s

This Ruby on Rails code sample offers a functional application with views and services to hydrate the user interface. It is important to notice that the service implemented in the basic-authentication branch simulates the external API by placing the responses directly on the code.

Later, you'll integrate this Ruby on Rails web application with a real API server using any of the "Auth0 Hello World" API code samples with the backend technology of your choice.

Use the Ruby on Rails Sample Application

You can now visit http://localhost:4040/ to access the application.

If you want to learn how to implement user authentication in Rails step by step, check out the "Rails Authentication By Example".

When you click on the "Log In" button, Rails takes you to the Auth0 Universal Login page. Your users can log in to your application through a page hosted by Auth0, which provides them with a secure, standards-based login experience that you can customize with your own branding and various authentication methods, such as logging in with a username and password or with a social provider like Facebook or Google.

Once you log in, visit the protected "Profile" page to see all the user profile information that Auth0 securely shares with your application using ID tokens:

You can test that the protected Rails routes require users to log in before accessing them. Click on the "Log Out" button and try to access the Profile page, Protected page, or the Admin page:

If everything is working as expected, Rails redirects you to log in with Auth0.

Connect the Ruby on Rails Code Sample with an API Server

Before you can practice requesting protected resources from an external API server using access tokens, you need to set up and configure an API with Auth0. You can pair this Ruby on Rails code sample with any of our "Hello World" API server code samples.

Set up a Hello World API server

Pick an API code sample in your preferred backend framework and language from the list below and follow the instructions on the code sample page to set it up. Once you complete the sample API server set up, please return to this Ruby on Rails code sample page to learn how to integrate that API server with your Ruby on Rails web application.

actix-web
rust
Actix Web/Rust API:Authorization Code Sample
Code sample of a simple Actix Web server that implements token-based authorization using Auth0.
aspnet-core
csharp
ASP.NET Core Code Sample:Web API Authorization
Code sample of a simple ASP.NET Core server that implements token-based authorization using Auth0.
django
python
Django/Python API:Authorization Code Sample
Code sample of a simple Django server that implements token-based authorization using Auth0.
express
javascript
Express.js Code Sample:Basic API Authorization
Code sample of a simple Express.js server that implements token-based authorization using Auth0.
express
typescript
Express.js/TypeScript Code Sample:Basic API Authorization
Code sample of a simple Express.js server built with TypeScript that implements token-based authorization using Auth0.
fastapi
python
FastAPI/Python Code Sample:Basic API Authorization
Code sample of a simple FastAPI server that implements token-based authorization using Auth0.
flask
python
Flask/Python API:Authorization Code Sample
Code sample of a simple Flask server that implements token-based authorization using Auth0.
laravel
php
Laravel/PHP API:Authorization Code Sample
Code sample of a simple Laravel server that implements token-based authorization using Auth0.
lumen
php
Lumen/PHP API:Authorization Code Sample
Code sample of a simple Lumen server that implements token-based authorization using Auth0.
phoenix
elixir
Phoenix/Elixir API:Authorization Code Sample
Code sample of a simple Phoenix server that implements token-based authorization using Auth0.
rails
ruby
Ruby on Rails API:Authorization Code Sample
Code sample of a simple Rails server that implements authorization using Auth0.
spring
java
Spring Code Sample:Basic API Authorization
Java code sample that implements token-based authorization in a Spring Web API server to protect API endpoints, using Spring Security.
spring
java
Spring Functional Code Sample:Basic API Authorization
Java code sample that implements token-based authorization in a Spring Web API server to protect API endpoints, following a functional approach.
spring-webflux
java
Spring WebFlux Code Sample:Basic API Authorization
Java code sample that implements token-based authorization in a Spring WebFlux API server to protect API endpoints, using Spring Security.
standard-library
golang
Golang Code Sample:Basic API Authorization
Code sample of a simple Golang server that implements token-based authorization using Auth0.
symfony
php
Symfony Code Sample:Basic API Authorization
Code sample of a simple Symfony server that implements token-based authorization using Auth0.

While setting up the API server code sample, you created an Auth0 Audience value. Store that value in the following field so that you can use it throughout the instructions present in this section easily:

Set up the Ruby on Rails client application

If you haven't cloned the repository already, start by cloning the Ruby on Rails project into your local machine:

COMMAND
git clone https://github.com/auth0-developer-hub/web-app_rails_ruby_hello-world.git

Make the project directory your current working directory:

COMMAND
cd web-app_rails_ruby_hello-world

Then, check out the basic-authentication-with-api-integration branch:

COMMAND
git checkout basic-authentication-with-api-integration

Next, install the Ruby on Rails project dependencies:

COMMAND
bundle install

Now, either create or update the .env file under the Ruby on Rails project directory with the following:

.env
PORT=4040
SECRET_KEY_BASE=KEY-VALUE
AUTH0_DOMAIN=AUTH0-DOMAIN
AUTH0_CLIENT_ID=AUTH0-CLIENT-ID
AUTH0_CALLBACK_PATH=/auth/auth0/callback
AUTH0_CLIENT_SECRET=AUTH0-CLIENT-SECRET
API_SERVER_URL=http://localhost:6060
AUTH0_AUDIENCE=AUTH0-AUDIENCE

This time around, you include the API_SERVER_URL and AUTH0_AUDIENCE values.

The API_SERVER_URL is the URL where your sample API server listens for requests. In production, you'll change this value to the URL of your live server.

The AUTH0_AUDIENCE is an identifier that represents the compatible Hello World API you just registered in your Auth0 tenant. This identifier is also known as the Auth0 audience. Your Ruby on Rails web application must provide this value to the Auth0 authorization server in order to get a valid access token to make authenticated requests to the compatible external API.

If you haven't started the Ruby on Rails web application yet, execute this command to run it:

COMMAND
bin/rails s

Now your Ruby on Rails is all set up to request protected data from the "Hello World" API server of your choice. Ensure that your API server is running and visit the Admin page of your Ruby on Rails web application:

Verify that this page is displaying the relevant messages from the API.

This basic-authentication-with-api-integration branch of the code sample repository demonstrates how to request protected data from an API using access tokens in Rails.