Saturday, September 21, 2024
Google search engine
HomeLanguagesHow to Build a React App with User Authentication ?

How to Build a React App with User Authentication ?

User authentication is the process of securing user information through the use of some parameters like username, password, and more. This helps the user to access his perks and features on a particular website. Such authentication is used almost everywhere today. Some examples would be banking, booking tickets, online video streaming platforms, etc. We will be using React JS, a Javascript frontend library, and Auth0, a framework that will help us in making our authentication user-friendly as well as secure.

Let’s understand now how to build a React App with User Authentication, below is the step-by-step implementation for the same.

Step 1: Create a new React JS application, by using the following command:

npx create-react-app react-authenticator

This will create a new folder called react-authenticator with all the necessary starter files.

Step 2: Now move to the react-authenticator folder using the ‘cd’ command:

cd react-authenticator

Project Structure: Your folder structure should look something like this:

Folder Structure

Now, we need to install the auth0 library, so that we can perform the authentication process. To do this, use the following command:

npm install @auth0/auth0-react

That should install auth0. Let’s move on to some coding now. Open the file called index.js inside the src folder. Let us first understand what we are doing inside index.js

We are importing the Auth0Provider component from the auth0 library. We wrap our ‘App’ inside the Auth0 component so that we can further use the hook provided by auth0. Inside the Auth0Provider component, we pass the domain and clientID.

You can get your own domain and clientID. For the same, go to “https://auth0.com/” and sign up to create your own account. After creation, you will see a dashboard. Click on create an application and select single page application. Now, it will ask you which technology you are using. Select React. That’s it. Now, inside your application, go to settings, and you will find the domain and clientID which are unique to you.

Explanation: We pass our domain and clientID to the Auth0Provider component so that it can recognize, which application you are referring to. Then we pass ‘window.location.origin’ to the redirectUri. So, as and when authentication happens, the user will be redirected to the original page or home page. For this to work, go to your application on the auth0 website again. Now, set the Allowed Callback URLs, Allowed Logout URLs, and Allowed Web origins all to http://localhost:3000. That is it for index.js.

index.js

Javascript




import React from 'react';
import ReactDOM from 'react-dom/client';
import App from './App';
import { Auth0Provider } from '@auth0/auth0-react';
 
const root = ReactDOM.createRoot(document.getElementById('root'));
root.render(
    <Auth0Provider
        domain='dev-mf6lqfng.us.auth0.com'
        clientId='5c1HQIOd6HlVEi2CLLfTPO7HCImJ9qZr'
        redirectUri={window.location.origin}>
        <App />
    </Auth0Provider>
);


Now, inside the same src folder, create a folder called components. Inside the components folder, create three files: LoginButton.js, LogoutButton.js, and Profile.js. Now your folder structure will look like this:

Updated Folder Structure

Before we move on, we need to install bootstrap, to make our CSS job easier. To do the same, type in the command:

npm install bootstrap

Let us start with LoginButton.js. We have imported the hook called useAuth0 that provides methods for authentication. The first method is ‘loginWithRedirect’. This method, when called, takes the user to the login portal, and on login completion, takes him to the homepage. We have created a button called ‘Log In’ with an onclick that calls the loginWithRedirect method. The next method is ‘isAuthenticated’. This is another method of the useAuth0 hook and it returns a Boolean value: true or false. So, in the if condition, we are saying ‘!isAuthenticated’ i.e., if the user is not logged in, only then display the ‘Log In’ button. Finally, we export LoginButton.

LoginButton.js

Javascript




import React from "react";
import { useAuth0 } from "@auth0/auth0-react";
 
const LoginButton = () => {
    const { loginWithRedirect, isAuthenticated } = useAuth0();
    if (!isAuthenticated) {
        return <button className="btn btn-primary
            mx-5 my-5 px-4"
            onClick={() => loginWithRedirect()}>
            Log In</button>;
    }
};
 
export default LoginButton;


Before moving on to Logout.js, we first need to code Profile.js. In Profile.js, we use the user object provided by the useAuth0 hook. It stores the user information as an object, once a user is logged in. So, in the return statement, we are displaying the user’s name, given name, family name, email, and sub. These values are automatically stored through auth0.

Profile.js

Javascript




import React from 'react';
import { useAuth0 } from '@auth0/auth0-react';
 
const Profile = () => {
    const { user } = useAuth0();
 
    return (
        <>
            <div className="container">
                <p className="userInfo" id="userInfo1">
                    Name: {user.name}</p>
                <p className="userInfo" id="userInfo2">
                    Given Name: {user.given_name}</p>
                <p className="userInfo" id="userInfo3">
                    Family Name: {user.family_name}</p>
                <p className="userInfo" id="userInfo4">
                    Email: {user.email}</p>
                <p className="userInfo" id="userInfo5">
                    Sub: {user.sub}</p>
            </div>
        </>
    )
}
 
export default Profile


For this particular Component, we will write some custom CSS. So, inside the src folder, open App.css. This App.css also covers some custom CSS for the logout button and App.js. The remaining CSS is applied through the use of Bootstrap.

App.css

CSS




* {
    margin: 0;
    padding: 0;
}
 
.appName {
    color: #fff;
}
 
.logoutBtn {
    margin: auto;
}
 
.userInfo {
    background-color: #d9d9d9;
    box-shadow: 5px 0px 0px grey;
    width: 35%;
    padding: 20px;
    border-radius: 6px;
    font-weight: 600;
}


Finally, we will complete our LogoutButton.js component. In this case, we are using the logout method. The code works similarly to LoginButton.js. This time we are saying if(isAuthenticated) i.e., if the user is Logged in, then return the Logout button and the Profile component. This is the component we exported through Profile.js, and we have imported the same at the top of the code. Also, inside the logout button, we have said ‘returnTo: window.location.origin’, which will take the user back to the homepage, once he logs out.

LogoutButton.js

Javascript




import React from "react";
import { useAuth0 } from "@auth0/auth0-react";
import Profile from "./Profile";
 
const LogoutButton = () => {
    const { logout, isAuthenticated } = useAuth0();
 
    if (isAuthenticated) {
        return (
            <>
                <button className="btn btn-primary
                    mx-5 my-5 px-4 logoutBtn"
                    onClick={() => logout({ returnTo: window.location.origin })}>
                    Log Out
                </button>
                <br />
                <Profile />
            </>
        );
    }
};
 
export default LogoutButton;


Now, in the end, let’s code App.js, which will render all our components. In the src folder, open App.js and code the following. We are displaying a navbar followed by the two components we exported i.e., LoginButton and LogoutButton. We have imported both components at the top of the code. Also, we have, imported App.css and the bootstrap path for the necessary CSS.

App.js

Javascript




import './App.css';
import LoginButton from './components/LoginButton';
import LogoutButton from './components/LogoutButton';
import 'bootstrap/dist/css/bootstrap.min.css';
 
function App() {
    return (
        <>
            <nav className="navbar bg-dark">
                <div className="container-fluid">
                    <span className="appName">
                        React User Authentication</span>
                </div>
            </nav>
            <LoginButton />
            <LogoutButton />
        </>
    );
}
 
export default App;


Steps to run the application: Write the below code in the terminal to run the application:

npm start

Output: Now open your browser and go to http://localhost:3000/, you will see the following output:

 

When we click on the login button, we are redirected to the auth0 login portal. On successful login, we can see the user information displayed. And when we click on the Logout button, we are redirected to the homepage.

And that is the end of this article. We learned the use of React JS and Auth0 to provide a powerful and secure user authentication system, that you can embed across various applications. 

Whether you’re preparing for your first job interview or aiming to upskill in this ever-evolving tech landscape, neveropen Courses are your key to success. We provide top-quality content at affordable prices, all geared towards accelerating your growth in a time-bound manner. Join the millions we’ve already empowered, and we’re here to do the same for you. Don’t miss out – check it out now!

RELATED ARTICLES

Most Popular

Recent Comments