Building a safe authentication system without any third-party service is a challenging task and is much easier to get wrong. Auth0 is a third-party service that allows developers to quickly add authentication to their apps.

In this tutorial, we will look at how to secure your React application with Auth0 React SDK.

To log in users, our application redirects to an Auth0 customizable page. After successful completion of login Auth0 then redirects users back to our application and returns with authentication and user information.

Project Setup

Start by creating react app on your machine.

Sign up for an Auth0 account

We need to create an account to use the Auth0 service, so sign up for a free Auth0 account.

After completing the sign-up steps, move forward by creating a new application. After clicking on Create new application we get options to create a native app, Single Page Web App, web app, or even CLIs.

Give your app a good name and as we’re building React app select Single Page Web App.

Once you create the application Auth0 takes you to the application Dashboard. In the Dashboard, click on Settings and copy Domain and Client ID that we will use later.

Now, scroll down and you will see Application URIs. Add URL http://localhost:3000 for

  • Allowed Callback URLs: redirects user after login
  • Allowed Logout URLs: redirects user after logout
  • Allowed Web Origins: silently refreshes authentication tokens and users will be logged out the next time they visit the application or refresh the page.

Scroll down to the bottom and click on Save Changes.

Install Auth0 React SDK

Now, in the react app install Auth0 React SDK.

npm install @auth0/auth0-react

Then, create a .env file in the root of the project and paste the Domain and Client ID that we copied earlier.

REACT_APP_AUTH0_DOMAIN = your domain REACT_APP_AUTH0_CLIENT_ID = your client id

In the index.js file wrap the root component App with Auth0Provider. Auth0 React SDK uses React Context to manage the authentication of applications. You can learn more about React Context here.

// index.js import React from "react"; import ReactDOM from "react-dom/client"; import "./index.css"; import App from "./App"; import { Auth0Provider } from "@auth0/auth0-react"; const root = ReactDOM.createRoot(document.getElementById("root")); root.render( <Auth0Provider domain={process.env.REACT_APP_AUTH0_DOMAIN} clientId={process.env.REACT_APP_CLIENT_ID} redirectUri={window.location.origin} > <App /> </Auth0Provider> );

Run your React application and make sure there are no errors related to Auth0.

Login and Logout Component

Now, we will create 3 components for authentication events: Login, Logout, and User.

In the src directory create new folder Components. Inside src/components/ Create 3 files

Login.jsx, Logout.jsx, User.jsx

// Login.jsx import React from "react"; import { useAuth0 } from "@auth0/auth0-react"; const Login = () => { const { loginWithRedirect } = useAuth0(); return <button onClick={() => loginWithRedirect()}>Log In</button>; }; export default Login;

First, we import the useAuth0 hook which is available in Auth0 React SDK.

Then, we are using loginWithRedirect method which is provided by the useAuth0 hook. loginWithRedirect method takes the user to the Auth0 Universal login page. After login, it redirects the user back to the application.

// Logout.jsx import React from "react"; import { useAuth0 } from "@auth0/auth0-react"; const Logout = () => { const { logout } = useAuth0(); return ( <button onClick={() => logout({ returnTo: window.location.origin })}> Log Out </button> ); }; export default Logout;

Similarly, for logout, we have the logout() method which comes with Auth0 React SDK. It redirects the user to the /v2/logout Auth0 endpoint to clear the login session and then takes the user back to the application.

// User.jsx import React from "react"; import { useAuth0 } from "@auth0/auth0-react"; const User = () => { 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 User;

The User component will be used to display the user’s information. We have a user object available in the useAuth0 hook which we will use to get the user’s name, email, etc. To check if the user has authenticated we are using isAuthenticated boolean property again available in the useAuth0 hook.

Now, import all the components in the App.js file. Also, we will need isAuthenticated property from the useAuth0 hook to check if the user has authenticated.

We want to display the Login button if the user isn’t authenticated and the Logout button if the user has completed authentication. To do that we are simply using conditional statements.

// App.js import logo from "./logo.svg"; import { useAuth0 } from "@auth0/auth0-react"; import "./App.css"; import Logout from "./Components/Logout"; import User from "./Components/User"; import Login from "./Components/Login"; function App() { const { isAuthenticated } = useAuth0(); return ( <div className="App"> {!isAuthenticated ? ( <div> <p>Login.</p> <Login /> </div> ) : ( <div> <Logout /> <User /> <header className="App-header"> <img src={logo} className="App-logo" alt="logo" /> <p> Edit <code>src/App.js</code> and save to reload. </p> <a className="App-link" href="https://reactjs.org" target="_blank" rel="noopener noreferrer" > Learn React </a> </header> </div> )} </div> ); } export default App;

Save the file and start React app. We’re all done now. Pat yourself on the back if you have made it till here. Here’s the result:

Conclusion

In this tutorial, we completed the user Authentication in our React app with Auth0. This was just the simple implementation of the Authentication. You can learn more about how to manage routes and everything else in Auth0’s official documentation.

Thank you so much for reading.

Feel free to comment if you have any questions or If you have any suggestions. If you want to request any article for a particular topic contact through the about page. I would love to hear from you.

👋 Hey, I'm Pratham Bhagat
I simplify complex web development topics. My curiosity leads me to learn about various technologies, and my love for writing helps me to impart my knowledge for the same.

💬 Leave a comment

Your email address will not be published.

We will never share your email with anyone else.