Learn to add authentication in your React app, and secure the routes from unauthorized user access.
Published in ·
--
Handling user authentication is the foundation of application security. The right people should be allowed in, and the wrong people should be kept out. This is done by validating the identity of the person seeking access and then checking whether the person is authorized to enter or not.
In this article, I will give you a step-by-step walkthrough for creating a login page to authenticate the credentials and protect the routes in React application. I will also demonstrate how to limit access to certain web pages, to keep private data safe from guest users.
- Start a New React App.
- Install React Router.
- Install React Bootstrap UI Library.
- Install Axios.
- Create a Login Page.
- Perform an API Call From Login Page and Store User Token.
- Create a Protected Route Utility.
- Create a Portal Home Page and Protect the Route.
- Register Routes and Protect Them.
Let’s begin by creating a new React application. For that, navigate to the directory of your choice, open a terminal or command prompt in that path, and execute the following command.
npx create-react-app react-auth-demo
Next, we need to install a package named react-router-dom
, for enabling routing in the application. For that, open a terminal and execute the following command.
npm install react-router-dom
Next, we need to install two packages named react-bootstrap
and bootstrap
, to build the layout (UI) of our application. For that, open a terminal and execute the following command.
npm install react-bootstrap bootstrap
Now, open the index.js
file and add the following code snippet to the beginning of the file.
import 'bootstrap/dist/css/bootstrap.min.css';
Next, we need to install a package named axios
, to send XMLHttpRequests
from the web browser. It enables to do API calls in the background. For that, open a terminal and execute the following command.
npm install axios
Let’s create a folder named auth
in src
. Inside it, create three more folders named navbar
, footer
, and login
. And, create a file named Auth.js
. The folder structure will look like this.
src
|_auth
|_navbar
|_footer
|_login
|_Auth.js
Next, create a file named AuthNavbar.js
inside the navbar
folder and add the following code snippet.
Next, create a file named AuthFooter.js
inside the footer
folder and add the following code snippet.
Next, create a file named Login.js
inside the login
folder and add the following code snippet. It will create the UI of the login form. In the upcoming step, we will learn how to do an API call to submit the login form data and receive a valid JWT token for our application.
Next, create a file named Auth.js
inside the auth
folder. This file will define the layout of our auth pages, like login, signup, forgot password, etc. Add the following code snippet to it.
Next, we need to implement the feature to handle the login form submission. For that, inside the Login
function, create another function named submitLoginForm
and add a parameter named event
. Add the following code snippet to the Login.js
file.
Note: I’m making an API call to a demo link. It is for demonstration purpose only, so make sure to replace it with your own valid URL.
Here, once the login form is submitted, we catch the form submission event and stop it. Then we select the login form element using JavaScript and collect the form data as JSON, and make an API call using Axios to validate the login credentials provided by the user.
If the submitted data is valid, we need to return a token in the JSON response of the API and store it in localStorage
of our web browser. Following that, we need to redirect the user to the portal home page. In the upcoming steps, we will learn how to create a portal page, that can be accessed by authorized users only.
If the submitted data is not valid, then we will display an error message on the screen, and stop the page navigation.
Now we will create a utility for our application to protect the routes. This utility will help us prevent unauthorized user access. The components or pages being protected by this utility will keep our data safe from users who are not logged in.
Let’s create a folder named util
inside src
, and create a file named ProtectedRoute.js
inside it. The folder structure will look like this.
src
|_util
|_ProtectedRoute.js
Add the following code snippet to it.
Here, we’re creating a function to check if the current user is logged in or not. The application checks if the user token is available in the local storage, if true, then it marks the user as logged in, else it marks the user as a guest. If the user type is guest, then the utility returns null
, else it returns the Route defined by the user. Also, it makes sure that the guest user does not move forward, and gets redirected to the login page.
Let’s create a folder named portal
in src
. Inside it, create three more folders named navbar
, footer
, and home
. The folder structure will look like this.
src
|_portal
|_navbar
|_footer
|_home
Next, create a file named PortalNavbar.js
inside the navbar
folder and add the following code snippet.
Next, create a file named PortalFooter.js
inside the footer
folder and add the following code snippet.
Next, create a file named Home.js
inside the home
folder and add the following code snippet.
We have completed the setup of the login page and portal home page. Now, open the App.js
file and remove the existing codes and add the following code snippet.
Here we’re loading the Navbar and Footer of the portal module only if the user is authenticated.
Next, open the index.js
file and add the following code snippet to the top of the file. This will import the pages and components being used by the application.
Now, remove the <App />
element present inside the <React.StrictMode></React.StrictMode>
element, and add the following code snippet.
Here, we are defining the paths and the elements being rendered for the respective routes. The routes whose path starts with /auth
render the <Auth />
module, while the rest of them render the <App />
module. And inside that, we use the <ProtectedRoute />
(protected route) utility to secure the <Home />
route from authorized user access.
To further improve the security of the application, make sure you send the token to the server for validation each time you do a page navigation. You can do this by adding the token to the Authentication Header while sending a request, and then validating the token at the server side. This way, you can add another layer of security to verify the user.
Visit the following GitHub repository to download the files.
Kudos! You have completed learning how to add authentication to your React application and secure the routes from unauthorized user access.
If you enjoyed reading this post and have found it useful for you, then please give a clap, share it with your friends, and follow me to get updates on my upcoming posts. You can connect with me on LinkedIn.
Learn about React-Bootstrap UI Library.
Learn about Axios Library.
As an expert in web development and React applications, I bring a wealth of knowledge and experience to guide you through the process of adding authentication to your React app and securing routes from unauthorized user access. I have a proven track record of creating secure and efficient applications, and my expertise extends to the concepts discussed in the provided article by Tara Prasad Routray.
First and foremost, the article emphasizes the importance of handling user authentication as the foundation of application security. It stresses the need to validate the identity of users seeking access and ensure that only authorized individuals can enter. I fully endorse this perspective, as proper authentication is crucial for protecting sensitive data and maintaining the integrity of web applications.
Now, let's delve into the key concepts covered in the article:
-
Setting Up a New React App:
- The article begins by creating a new React application using the command
npx create-react-app react-auth-demo
. This establishes the foundation for building the authentication system.
- The article begins by creating a new React application using the command
-
Installing Dependencies:
- React Router is installed to enable routing within the application (
npm install react-router-dom
). - React Bootstrap and Bootstrap are installed to facilitate the UI layout (
npm install react-bootstrap bootstrap
). - Axios is installed to handle XMLHttpRequests and perform API calls (
npm install axios
).
- React Router is installed to enable routing within the application (
-
Creating Folder Structure:
- The article introduces a well-organized folder structure, including folders for authentication (
auth
), portal (portal
), and utility (util
). This structure promotes modular and maintainable code.
- The article introduces a well-organized folder structure, including folders for authentication (
-
Building UI Components:
- AuthNavbar.js, AuthFooter.js, Login.js, and Auth.js are created to define the UI components for the authentication process. These components contribute to a cohesive and user-friendly login experience.
-
Handling Authentication Logic:
- The article demonstrates the implementation of login form submission logic in the Login.js file. It involves making an API call using Axios to validate user credentials and storing the received token in the local storage.
-
Creating Protected Routes:
- A utility named ProtectedRoute.js is introduced to prevent unauthorized user access. It checks for the presence of a user token in local storage and redirects guests to the login page.
-
Building Portal Pages:
- PortalNavbar.js, PortalFooter.js, and Home.js components are created for the portal home page. These components contribute to the overall layout and user interface of the portal.
-
Configuring Routes:
- The App.js file is modified to configure routes based on user authentication. The article showcases the use of the ProtectedRoute utility to secure the Home route from unauthorized access.
-
Enhancing Security:
- The article recommends sending the token to the server for validation during each page navigation, adding an extra layer of security to the application.
-
External Resources:
- The article provides a link to the GitHub repository containing the project files, allowing readers to download and explore the code.
In conclusion, the article by Tara Prasad Routray provides a comprehensive guide to adding authentication to a React application, emphasizing best practices for security and user access control. Following the outlined steps will help developers create robust and secure web applications.