Ruby On Rails Authorization
Authentication tells your application to trust a user, granting him or her access to it. But that might not be enough. Most times, you will need to grant or restrict users from accessing specific parts of your application based on a number of attributes (commonly named "claims", being their "role", "department", or "country" a few examples). In this section, you'll learn how to assign a "role" claim to your users, and use those claims to authorize them to access an "admin" page.
Download a sample project specific to this tutorial configured with your Auth0 API Keys.
- Ruby 2.3.1
- Rails 5.0.0
Create a Rule to Assign Roles
Many identity providers will supply access claims, like roles or groups, with the user. You can request these in your token by setting
scope: openid roles or
scope: openid groups. However, not every identity provider provides this type of information. Fortunately, Auth0 has an alternative to it, which is creating a rule for assigning different roles to different users.
Create a Rule to assign roles
First, we will create a rule that assigns our users either an
admin role, or a single
user role. To do so, go to the new rule page and select the "Set Roles To A User" template, under Access Control. Then, replace this line from the default script:
if (user.email.indexOf('@example.com') > -1)
to match the condition that fits your needs. Notice that you can also set more roles other than
user, or customize the whole rule as you please.
By default, it says that if the user email contains
@example.com they will be given an
admin role, otherwise a regular
Add the following dependencies to your
Gemfile and run
gem 'omniauth', '~> 1.3.1' gem 'omniauth-auth0', '~> 1.4.2'
Create the Admin and Unauthorized Views
Add a placeholder text to indicate the user has accessed the admin area in the Admin View (
<div class="alert alert-success" role="alert"> You are viewing this because you are logged in and you have 'admin' role. </div> <%= link_to "Back to Home", dashboard_path %>
And a placeholder to indicate the user cannot access the requested content in the Unauthorized View (
<div class="alert alert-danger" role="alert"> Unauthorized: you are not allowed to see this content </div> <%= link_to "Back to Home", dashboard_path %>
Create the Admin Controller
In the Admin Controller, add a
before_action to check if the user has the admin role. If not, redirect the user to the unauthorized page:
class AdminController < ApplicationController include Secured before_action :admin? def show end private def admin? redirect_to unauthorized_show_path unless roles.include?('admin') end def roles app_metadata ? app_metadata[:roles] :  end def app_metadata session[:userinfo][:extra][:raw_info][:app_metadata] end end
That's it. Now you can verify that only users logged in with an email that contains
@example (or following the rule you've introduced) will be able to access the admin page.