Auth0 is a popular mechanism for establishing flexible authentication and authorization capabilities in SaaS applications. You can connect applications to Auth0 and specify your chosen identity provider (IdP)—e.g., Google, GitHub, or Facebook. When users log in to your application, Auth0 will authenticate them and send the authentication information back to the app.
This is part of a series of articles about Auth0
Auth0 offers SDKs for many common mobile, native, and web application platforms, enabling tight integration with your chosen tech stack and programming language. You can use the Auth0 React SDK to integrate Auth0 with React applications. Auth0 lets you configure multiple login options to offer users flexibility when logging in to an application.
This tutorial describes how to integrate and configure Auth0 with a new or existing React application.
In this article:
Auth0 simplifies the process of securing the web application stack. First, integrate Auth0 with React. After successfully logging into the application, the user will be redirected to an Auth0 custom login page. After a user logs in, Auth0 redirects them to the React application with JSON Web Tokens (JWTs).
To demonstrate React security fundamentals, Auth0 provides a basic project employing create-react-app. For application security, create React components and JavaScript services. Start by cloning the starting branch of spa_react_javascript_hello-world:
git clone -b starter git@github.com:auth0-developer-hub/spa_react_javascript_hello-world.git After cloning a repository, set an active directory to spa_react_javascript_hello-world: cd spa_react_javascript_hello-world Installing React dependencies: npm install
This basic React project uses API data to hydrate the user interface. The basic project uses a json-server to integrate the external API locally.
This React app will be integrated with an API server employing backend tech. http://localhost:6060 is the default API server. Build a virtual environment .env file inside the directory of the root project and specify the following variables to link the React application to an API server:
REACT_APP_API_SERVER_URL=http://localhost:6060 Execute the subsequent command to launch the JSON server API: npm run api Launch the React app with the following command: npm start
We will start by integrating user authentication in this basic React project. First, configure React to link to Auth0. Following that, we will use the Auth0 React SDK to authenticate users, and protect routes, render user-profiles, and fetch secure information to an external API server to hydrate certain application pages.
Follow these instructions to launch the Auth0 identity platform:
A new app was established when we signed up with Auth0. In addition, Auth0 requires certain application details. This information is under the Auth0 dashboard’s app settings.
Auth0 redirects us to callback URLs in the application after authentication. App Settings should include the app’s callback URL. This field must be set to sign in to the app.
After logging out of the authorization server, Auth0 can navigate to the app’s specified logout URL. The query parameter returnTo indicates it. Application Settings must include the app’s logout URL. This field must be set for us to log out of the application.
The app’s URL must be added to Application Settings’ Allowed Web Origins. Registering the application’s URL will allow it to refresh authentication tokens, keeping users signed in until they access the application again or refresh the page.
Installing the Auth0 React SDK in the directory of the project using this command:
npm install @auth0/auth0-react
We can use the SDK’s provided methods and variables to include Auth0 into the React app through React Hooks or Higher-Order Components.
React Context manages the users’ authentication state in the Auth0 React SDK. Wrap the app’s root component, including an Auth0Provider from the SDK, to integrate Auth0 into the React app.
import React from "react"; import ReactDOM from "react-dom"; import App from "./App"; import { Auth0Provider } from "@auth0/auth0-react"; ReactDOM.render( <Auth0Provider domain="YOUR_DOMAIN" clientId="YOUR_CLIENT_ID" redirectUri={window.location.origin} > <App /> </Auth0Provider>, document.getElementById("root") );
The following parameters are accepted by the Auth0Provider module:
Domain and clientId are the attributes’ values that match those of the Domain and Client ID fields in the Settings section of the app we created in Auth0. Whereas redirectUri is the URL to send users after Auth0 authentication.
Auth0Provider holds user authentication and SDK status, including whether Auth0 is available. In addition, the useAuth0() hook provides user login and logout helper functions.
Related: Read Our Auth0 React Guide
The useAuth0() hook’s loginWithRedirect() method allows adding a user authentication to the React app through Auth0 React SDK. Moreover, LoginWithRedirect() sends us to the Auth0 Universal Login Page for authentication. Auth0 redirects us to the app after authentication.
import React from "react"; import { useAuth0 } from "@auth0/auth0-react"; const LoginButton = () => { const { loginWithRedirect } = useAuth0(); return <button onClick={() => loginWithRedirect()}>Log In</button>; }; export default LoginButton;
Incorporate the LoginButton component. After clicking it, the React application should lead us to the Auth0 Universal Login page. Afterward, ensure that Auth0 returns us to the application through the redirectUri we specified in Auth0Provider.
After logging into the React app, we need to log out. The useAuth0() hook’s logout() method creates a logout button. Logout() takes us to the Auth0 logout endpoint (https://YOUR DOMAIN/v2/logout) and then to the application.
import React from "react"; import { useAuth0 } from "@auth0/auth0-react"; const LogoutButton = () => { const { logout } = useAuth0(); return ( <button onClick={() => logout({ returnTo: window.location.origin })}> Log Out </button> ); }; export default LogoutButton;
Incorporate the LogoutButton component. After clicking it, ensure you’re redirected to the Allowed Logout URLs you set up in Settings and that you’re logged out of the React app.
As users can log in and log out, users may prefer to access their profile details. User information is provided by the Auth0 React SDK’s user attribute.
Examine the profile.js code inside the interactive panel to look at a working example. Since the user property holds sensitive information about the user’s identity, its accessibility is based on the user’s authentication state. Avoid rendering errors by:
First, react’s rendering of components that rely on the user property must determine if the user is authenticated using Auth0’s isAuthenticated property. Secondly, to avoid potential issues, we should wait until the SDK has finished loading and is no longer shown as isLoading before accessing the isAuthenticated field.
import { useAuth0 } from "@auth0/auth0-react"; import React from "react"; const Profile = () => { const { user, isAuthenticated, isLoading } = useAuth0(); if (isLoading) { return <div>Loading ...</div>; } return ( isAuthenticated && ( <div> <img src={user.picture} alt={user.name} /> <h2>{user.name}</h2> <p>{user.email}</p> </div> ) ); }; export default Profile;
Frontegg is a comprehensive and end-to-end user management platform that works seamlessly with React. Frontegg React.js can be used to get started with just a few clicks – all you have to do is use the package manager and wrap your root component with the Frontegg Provider. Then you can redirect to your login and check the users’ authentication stats with the Frontegg useAuth hook. It’s really that easy.
Follow the link to read more about the Auth0 vs Frontegg comparison.
Start For Free