Join Our Newsletter!

Keep up to date with our latest blog posts, new widgets and features, and the Common Ninja Developer Platform.

Implementing Auth0 Authentication in React Apps

Common Ninja,

Summary (TL;DR): In this article, we’ll discuss what authentication is and why it’s needed, and we’ll go over how to implement it in React using Auth0. We’ll go over everything from installing dependencies to creating an account on Auth0, creating a new application, and more!

Implementing Auth0 Authentication in React Apps

Authentication is vital for multi-user applications as they manage user access and restrict unwanted usage. Finding a suitable implementation that can seamlessly handle this functionality is crucial.

While building an authentication system is possible, it is time-consuming and has a significant workload.

In contrast, there are easier ways to implement authentication through an authentication provider.

Authentication providers, as the name implies, provide authentication features and can be easily implemented in an application. An example of an authentication provider is Auth0.

In this tutorial, we will expand on what user authentication is, how to implement it in a React application using Auth0, and demonstrate how to do it.

While You Are Here, Why Not Learn How To Implement Okta Authentication in React?

What Is User Authentication?

User authentication refers to a security method put in place to verify the identities of users trying to gain access to a network or application or prevent unauthorized users from gaining access to a service.

This is handled via a procedure where the application requests personalized passwords and credentials to give authorized access. If any users lack the required access credentials, authentication fails and access is denied.  

Why Use Auth0?

Auth0 is a flexible authentication provider that provides different methods and functionalities for handling different authentication patterns.

Auth0 authentication methods include username and passwords, OTP login system, multi-factor authentication, social logins (Google, GitHub, Facebook, Twitter, etc.) and allows user profile data to be retrieved after authentication is successful.  

It is a time and cost-saving alternative to building an authentication system for an application. By using an authentication provider like Auth0, the development team can devote efforts towards building the application, while Auth0 handles all features of user management.

Implementing User Authentication

In this tutorial, we will demonstrate handling user authentication with Auth0 and the React.js framework. 

Installing Dependencies

To get started with this tutorial, you will need to create a React application in a directory of your choosing and install the Auth0 SDK package in the created directory with the following CLI commands:

npx create-react-app authentication cd authentication npm install @auth0/auth0-react npm install react-router-dom@6

The above command creates a React application in your directory with the Auth0 and React-router dependencies in it.

Creating an Account on Auth0

To make use of Auth0, you will need to have a user account on it. If you don’t have a pre-existing account, navigate in your browser to Auth0 signup page and create a new user account. Upon creating a user account, you will be navigated to the dashboard.

Creating a New Application

Click on Create Application, and on the modal that appears key in the name of the application and select single page web application from the app categories.

Clicking on the Create button will create the new application.

Adding Application URLs

For the login and signup features of our authentication, our React application will redirect users to an auth page provided by Auth0. When authenticated,  the users will then be redirected to the application.

For this, we will need to specify the callback URLs leading from the Login page back to our React application. We can do this in the settings tab of our newly created Auth0 application.

In the “Allowed callback URL”, “Allowed login URL” and “Allowed web origins” paste in the URL of the React application (this is the localhost URL) and click on the save changes button at the bottom.

Application Setup

For our React application, we will have two pages, a welcome page with the Login button and a dashboard page to which authenticated users will be redirected. To achieve this, make the following modifications to your project directory.

To use React-router we will need to wrap the parent component App.js with the router providers in our index.js file:

import React from "react"; import ReactDOM from "react-dom/client"; import { BrowserRouter, Routes, Route } from "react-router-dom"; import "./index.css"; import App from "./App"; import Dashboard from "./Dashboard"; const root = ReactDOM.createRoot(document.getElementById("root")); root.render( <React.StrictMode> <BrowserRouter> <Routes> <Route path="/" element={<App />} /> <Route path="dashboard" element={<Dashboard />} /> </Routes> </BrowserRouter> </React.StrictMode> );

In the code above, the root route returns the App component while the dashboard route will return a Dashboard component.

In the src directory, create a new file called Dashboard.js with the following lines of code in it:

import React from "react"; const Dashboard = () => { return ( <div> <h1>Welcome user</h1> </div> ); }; export default Dashboard;

We will later modify this component to display details of authenticated users. Next, we will set up our home page in App.js :

import "./App.css"; import Nav from "./components/Nav"; function App() { return ( <div className="App"> <Nav /> <h1>Welcome to this React Application</h1> <h3>Get authenticated to Continue</h3> </div> ); } export default App;

We will use a navigation component to switch between routes. In the src directory, create a new file Nav.js, and add the following code to it:

import React from "react"; import { Link } from "react-router-dom"; const Nav = () => { return ( <div className="navigation"> <li> <Link to="/">Login/Signup</Link> </li> <li> <Link to="/dashboard">Dashboard</Link> </li> <button>Login</button> </div> ); }; export default Nav;

Add the following lines to App.css to better style the application:

.App, .dashboard { height: 100vh; display: flex; justify-content: center; align-items: center; flex-direction: column; position: relative; } button{ padding: 8px 10px; } .navigation{ display: flex; gap: 3em; align-items: center; width: 100%; height: 50px; background-color: #f5f5f5; padding: 0 20px; box-shadow: 0px 2px 4px rgba(0, 0, 0, 0.1); position: absolute; top: 10px; } .navigation li{ list-style-type: none; } .navigation li:hover{ cursor: pointer; }

Creating an Auth0 Provider

To make use of Auth0 in our React application, we will need to import the authentication provider module from the Auth0 SDK and wrap our application component in it. In index.js we will modify the root and dashboard routes as shown below:

import { Auth0Provider } from "@auth0/auth0-react"; //.... <Route path="/" element={ <Auth0Provider domain="YOUR_DOMAIN" clientId="YOUR_CLIENT_ID" redirectUri={window.location.origin} > <App /> </Auth0Provider> } /> <Route path="dashboard" element={ <Auth0Provider domain="YOUR_DOMAIN" clientId="YOUR_CLIENT_ID" redirectUri={window.location.origin} > <Dashboard /> </Auth0Provider> } />

The domain and clientid can be found in the settings tab of your application on Auth0.

Adding Login and Logout Features

To handle the login and logout functionalities of our application, we will modify our button in Nav.js to redirect users to the Auth0 login page when it is clicked.

import { useAuth0 } from "@auth0/auth0-react"; //... const { user, isAuthenticated, loginWithRedirect, logout } = useAuth0(); //... <button onClick={()=>{loginWithRedirect()}}>Login</button>

Here, we imported useAuth0 from the Auth0-react module and defined constants making use of the useAuth0 to handle different tasks. We added the loginWithRedirect defined above to the button. 

If we run the application with the npm start command, we get a result similar to the below image:

Now when the login button is clicked we are redirected to the Auth0 authentication page:

If you log in with the form above, you will be redirected to the React application since it’s the specified URL in our “callback URL”.

To handle logouts, we will check if the user isAuthenticated returns true to determine whether to render the login or logout button. We will do this in Nav.js:

{isAuthenticated ? ( <button onClick={() => { logout(); }} > Logout </button> ) : ( <button onClick={() => { loginWithRedirect(); }} > Login </button> )}

Getting Authentication Details

Upon authentication, we want our users to be able to view details regarding them provided by the authentication provider on the Dashboard page. We will get this using the user  state from the useAuth0 method:

import React from 'react' import { useAuth0 } from "@auth0/auth0-react"; import Nav from './components/Nav'; const Dashboard = () => { const {user} = useAuth0(); return ( <div className='dashboard'> <Nav/> <h1>Welcome user</h1> <img src={user.picture} alt='profile'/> <h3>{user.name}</h3> <h3>{user.email}</h3> <h3>{user.gender}</h3> <h3>{user.profile}</h3> </div> ) } export default Dashboard;

With this done, when we navigate to the “/dashboard” route we can view the details of the authenticated user.

Creating a Protected Route

Notice that if a user attempts to access the “/dashboard” route without being authenticated, it displays an error as the state user would return undefined. To solve this, we will make the “/dashboard” link in index.js only lead to this route when user returns true:

<Link to={user? "/dashboard": "/"}>Dashboard</Link>

Also in the Dashboard.js file, we will use Navigate from React-router to route users to the root route when user does not return a value.

if (!user) { return <Navigate to="/" replace />; } else { return ( <div className="dashboard"> <Nav /> <h1>Welcome user</h1> <img src={user.picture} alt="profile" /> <h3>{user.name}</h3> <h3>{user.email}</h3> <h3>{user.gender}</h3> <h3>{user.profile}</h3> </div> ); } };

Conclusion 

Authentication is vital for multi-user applications as they manage user access and restrict unwanted usage. Building an authentication system is time-consuming and has a significant workload. There are easier ways to implement authentication through an authentication provider.

In this tutorial, we learned about user authentication and how we can set up authentication in a React application using Auth0.