Created with Sketch.
Sign Up

TL;DR: In this post, we are going to integrate a React application with Auth0 Rules. Auth0 Rules allow for easier application of restrictions or allowances to projects. When using Auth0’s product, it is nice to know that there are rules made available to make life easier as a developer. Let’s see how a couple of these rules work. We can find the GitHub repo here for the project we will be adding rules to.

What Is An Auth0 Rule?

How does an Auth0 Rule help us in our authentication process? Let’s say we have an application and we want to make sure that a specific user has certain roles, like an admin role for example. Or we want to add in multi-factor authentication with Duo Security or Auth0 Guardian. Rather than writing out the code for all of that, Auth0 provides Rules that can be added to projects and will take care of all the heavy-lifting for authentication restrictions or requirements.

If we head on over to the Auth0 Docs on Rules, we can find the explanation of what a rule is:

Rules are JavaScript functions that execute when a user authenticates to your application. They run once the authentication process is complete, and you can use them to customize and extend Auth0's capabilities.

We can find and manage Rules in our Auth0 Dashboard. There, we will be able to configure one or more rules, depending on which ones we find necessary for our project. However, before diving into Auth0 Rules, we will need to get a React app up and running.

"Auth0 Rules are JavaScript functions that execute when a user authenticates to your application."

Our React Application

In this post, we will use the React application we created in the React Tutorial with Popup Authentication. In this React application, we initially have a view of "TV Shows" and a "Log In" button. Once the user clicks that, a pop-up modal will appear. The user will be able to authenticate and the app will take them to a view that has both "TV Shows" and "Movies" available. The "Movies" view is a protected route so the user can only view this list of information only if they are authenticated properly.

To grab that project, we can visit the GitHub repo to fork it and get the cloning link or we can run this command:

git clone https://github.com/auth0-blog/react-popup.git

After that, we can issue the following command to move the terminal to our React project.

cd react-popup

We will also need to install our dependencies for our project. We can do that by running the following command:

npm install

Setting up our Auth0 credentials

We will need to fill in three files with Auth0 credentials:

Note: All these files are marked as ignored on Git, so we will need to create them.

  1. ./src/auth/config.js
  2. ./api/config.js
  3. ./public/close-popup/index.html

To create all these files, we can issue the following commands:

touch ./src/auth/config.js
touch ./api/config.js
touch ./public/close-popup/index.html

Let's start with the first one.

1. src/auth/config.js

We will want this file to look like this:

// src/auth/config.js

export const config = {
  clientId: "your Auth0 client id",
  domain: "your Auth0 domain",
  // For production, redirect and logoutUrl should be on port 3005
  redirect: "http://localhost:3000/close-popup",
  logoutUrl: "http://localhost:3000",
  audience: "your API identifier"
};

Let's go to auth0.com and either login or signup. In the Dashboard, we will click on the "New Application" button, give the application a name, choose "Single Page App" and click "Create".

Once that is done, click on the "Settings" tab and there we will find all the information we need to put in this file. The audience property will be what we do next. So for now, we will leave it blank. In the properties, redirect and logoutUrl, we will want to put those values within the "Settings" for our application on our Dashboard. The redirect will go in the section that says "Allowed Callback URLs" and the logoutUrl value will go in the "Allowed Logout URLs" section. Be sure to hit "Save Changes" at the bottom when done!

2. api/config.js

We will want this file to look like this:

// api/config.js

module.exports = {
  AUTH0_DOMAIN: "your Auth0 domain",
  AUDIENCE: "your API identifier"
};

Still in our Auth0 Dashboard, let's click on "APIs" on the left-hand menu and then click "+ Create API". We will give our API a name and an identifier. The identifier could be something like https://movies-and-tv-shows/. Once the name and identifier are filled in, hit "Create".

Within the "Settings" tab, we will be able to find our API identifier that we just created. Now we can fill in this file with the correct information.

Note: We will need to update the audience field in the src/auth/config.js file as well.

3. /public/close-popup/index.html

We will want this file to look like this:

// public/close-popup/index.html

<!DOCTYPE html>
<html lang="en">
  <head>
    <meta
      charset="utf-8"
      content="font-src: 'self' data: img-src 'self' data: default-src 'self'"
    />
    <title></title>
    <!--
      Using CDN because proxy breaks relative links in this case,
      so linking to node_modules doesn't work in development env here
    -->
    <script src="https://cdn.auth0.com/js/auth0/9.8.1/auth0.min.js"></script>
    <!-- In production, use the node_modules script below for consistency -->
    <!-- <script src="/node_modules/auth0-js/dist/auth0.min.js"></script> -->
  </head>
  <body>
    <script type="text/javascript">
      const webAuth = new auth0.WebAuth({
        domain: "your Auth0 domain",
        clientID: "your Auth0 client id"
      });
      webAuth.popup.callback();
    </script>
  </body>
</html>

In this file, we are going to want to change these two lines to be our Auth0 credentials:

// public/close-popup/index.html

domain: "your Auth0 domain",
clientID: "your Auth0 client id"

Once those files are created, we can start the Express API by running:

nodemon

As the package.json file marks the server/server.js file as the main one, running nodemon without parameters will simply work. Then, in another tab, we can run the front-end with the following command:

npm start

After running this command, we will be able to see our app running on the http://localhost:3000/ URL. There, we will see "TV Shows" views and the "Log In" button. If we click on this button, a modal will appear so we can authenticate ourselves. After the authentication process, Auth0 will redirect us back to our app where we will see both the "TV Shows" and "Movies" views.

Adding in Auth0 Rules

Once we have the application working, we can start adding Auth0 Rules. Today, we will learn about three different rules:

  1. Set roles to a user
  2. Add country to the user profile
  3. Multi-factor with Google Authenticator

First steps to add in Auth0 rules

If we head back to our Auth0 Dashboard, we can go to the "Rules" section. We will see the main page of the Auth0 rules. Once in there, click on "+ CREATE YOUR FIRST RULE"

Now we are ready to pick which rule we will be adding today!

Set Roles to a User

Let’s say we want our email address to be considered an "admin". Auth0 has a rule that can help us out with that! If we click on the button that says "Set roles to a user" which is under the "Access Control" section, it will then take us to a page where we can see the code for the rule.

Note: If needed, we can always use ctrl+F (or cmd+F) to find keywords.

We will add in our particular email address. Find the line that looks like this within the code provided:

const endsWith = '@example.com';

After finding it, let's update it to be the email address that we will use while logging in:

const endsWith = 'myemail@email.com';

Note: Replace the value passed to endsWith with the desired email address. Any email that "endsWith" the value entered will be given the value of "admin". If you put "jorgenson@auth0.com" that would result in "sarah.jorgenson@auth0.com" and "jeff.jorgenson@auth0.com" having the "admin" value.

Scroll down and we will click on the Save button at the bottom.

That’s it! Now if we go to our Rules dashboard, we will see at the bottom of the screen that we now have that rule added in!

"You can set roles to a user by implementing the Auth0 Rule 'Set Roles to a User'"

But is it working?

To make sure our new rule is working properly, we can open the src/auth/service.js file in our project. Our login function should look like this:

// src/auth/service.js

  login() {
    this.auth0.popup.authorize({}, (err, authResult) => {
      if (err) this.localLogout();
      else {
        this.localLogin(authResult);
        this.accessToken = authResult.accessToken;
        console.log(authResult.idTokenPayload); // this is the line added
      }
    });
  }

That console.log will return our user’s information once they have logged in. Once that is saved, let’s head on over to our app in our browser. If we open up our dev tools by right-clicking in our app and clicking on "Inspect" we will have those open. Once those are open, click on the "Console" tab at the top of that. While we are logging in, we will watch that!

Click on "Log In" and the popup will appear, log in by whichever means and then the popup will disappear. Once that disappears, there should be a line in our "Console". Click on the drop-down arrow and all the user’s information will be there!

If we look at the line that looks like this:

https://example.com/roles: ["admin"]

We will see that, in fact, our user does have the "admin" role! Now, this only works if we used the email address to log in that we put as the "admin" in the rule. If we drop down that line, we’ll see a little more information on that admin role. The more information being the added role of admin." If we were to go back to that rule and change it to a different email address, then that email address we just used would change back to "user" status.

Now we know that rule is working!

Add Country to the User Profile

If we wanted the origin country and the timezone of the person logging in, there is an Auth0 rule for that as well! If we click on the "+ Create Rule" button in the "Rules" part of the Auth0 Dashboard, we can find the rule titled: "Add country to the user profile" under the section "Enrich Profile" of the Rules dashboard.

Once we click on that rule, we can see all the code that would make that rule work correctly. Click on "Save" and we are good to go! Again, let’s make sure it works!

But is it working?

If we kept the console.log in our login function from src/auth/service.js then we are going to be good to go.

We are going to head on over to the app in our browser and refresh the page. We are going to keep the "Console" tab open in our dev tools so that we can see the new console.log show up. Once we log in and are authorized correctly, let’s open up our user information in the "Console".

We should see the following lines added now:

https://example.com/country: "YOUR COUNTRY"
https://example.com/timezone: "YOUR TIME ZONE"

Note: After logging in, we will see our country's name (e.g., United States) and our timezone (e.g., PST)

We now see that it’s working and it’s attaching my country to my user profile. Great! Another rule has been added to our project!

Multi-factor with Google Authenticator

Multi-factor Authentication (MFA) is a system that will require users to present more than one piece of identifying information in order to log in successfully. Adding in Multi-factor Authentication sounds like a lot of work….but again, there’s an Auth0 Rule for that as well! If we click on "+ Create Rule" and scroll down to the section titled "Multi-factor" we will see many options! There will be options for:

  1. Multi-factor with Duo Security
  2. Multi-factor with Google Authenticator
  3. Multi-factor with Auth0 Guardian + Authorization Extension
  4. Multi-factor with Auth0 Guardian
  5. Multi-factor Authentication
  6. Multi-factor when request comes from outside an IP range

We have so many options!! Let’s click on the MFA option that is titled "Multi-factor with Google Authenticator".

Once we are in that rule, we are going to see all the code that would allow for that rule to work. The only line we are going to want to change is:

const CLIENTS_WITH_MFA = ['REPLACE_WITH_YOUR_CLIENT_ID'];

Let’s go find our CLIENT_ID! If we were to click on Applications on the left-hand side menu and find the application that is the one being used for our React app that we cloned earlier. In there, we are going to copy that Client ID and insert that value into the line within the rule. So it should look something like this:

const CLIENTS_WITH_MFA = ['your client id from project'];

Once we click "Save" at the bottom, we should be all ready to test it out!

But is it working?

Let’s head on over to our application in our browser and refresh the page. Click "Log In" and we’ll see the popup show up. Once we log in with whichever method, we will then see this:

We would need the Google Authenticator app on our phone in order to move on and scan the barcode, but we do see that it is working! If we were to scan that with the app on our phone, we would then get a six-digit verification code that we would put at the bottom of the popup. Once we continue on, the popup will disappear, we will be authentication with MFA and we will see the protected view of "TV Shows" and "Movies".

Note: If, for whatever reason, we don't want to use the Google Authenticator app, there are many other MFA alternatives available.

Conclusion

Notice how we didn’t have to add any code to our project? We were able to add in extra functionality to our project by just adding the Rule to our Auth0 account. That makes for easy implementation of many different restrictions or allowances when our users log in. It can also send back additional information from our users that might be useful for our project.

Take a look at the extensive list of Auth0 Rules provided. We may find that the code we need is already provided! As well, learn more about other Auth0 features like SSO, Universal Login, 2FA, and more.