Open In App

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.

Prerequisites

Approach to Create User Authentication:

Steps to create React Application And Installing Module:

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



npx create-react-app react-authenticator

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

cd react-authenticator

Step 3: Install the following dependencies



npm install @auth0/auth0-react bootstrap

Project Structure:

The updated dependencies in package.json file will look like:

"dependencies": {
"@auth0/auth0-react": "^2.2.4",
"@testing-library/jest-dom": "^5.17.0",
"@testing-library/react": "^13.4.0",
"@testing-library/user-event": "^13.5.0",
"bootstrap": "^5.3.2",
"react": "^18.2.0",
"react-dom": "^18.2.0",
"react-scripts": "5.0.1",
"web-vitals": "^2.1.4"
}

Example: Create the following files and add codes in these files.




//index.js
 
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>
);




//LoginButton.js
 
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;




//Profile.js
 
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




//LogoutButton.js
 
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;




//App.js
 
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;




/*App.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;
}

Steps 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.


Article Tags :