React SpringBoot Authentication – Part 3 (Protected Routes)

In this tutorial, you will learn how to protect some routes in your React application. We would create an Authentication Context and then we would create Protected Route component and use it to protect some routes n our application.

  1. Create the Authentication Context
  2. Create the Protected Route Component
  3. Protect Some Routes Using Protected Route Component
  4. Manage Login and Logout

 

1. Create the Authentication Context

To be able to manage authentication state across our application, we would use the useContext hook.

You will need to create a file called AuthContext.js. In this file, you will create and export an Auth context as well as an AuthContext provider.

The content of this file is given below:

import React, { createContext, useContext, useState } from 'react'

  const AuthContext = createContext();
  export const useAuth = () => useContext(AuthContext);
  export const AuthProvider = ({children}) => {

  const [isAuthenticated, setIsAuthenticated] = useState(() => {
    return localStorage.getItem('isAuthenticated') === true
  })

  const login = () => {
    setIsAuthenticated(true)
    localStorage.setItem('isAuthenticated', true)
  }

  const logout = () => {
    setIsAuthenticated(true)
    localStorage.setItem('isAuthenticated', false)
  }

  return (
    <AuthContext.Provider value={{isAuthenticated, login, logout}}>
        {children}
    </AuthContext.Provider>
  );
};

 

2. Create the Protected Route Component

To be able to protect some routes, we would need to have a wrapper around the Route component. The purpose would be to check whether a user is authenticated. If yes, the user is forwarded to the requested route, otherwise, he is redirected to the /login route.

The ProtectedRoute component is given below:

const ProtectedRoute = ({children}) =>  {
  const {isAuthenticated} = useAuth();
  if(!isAuthenticated){
    return <Navigate to="/login"></Navigate>
  }else {
      return children;
  }
}
export default ProtectedRoute

What happens here is that we retrieve the isAuthenticated state from  from the context and if it is not set, we would navigate to the Login component, otherwise, we would return the protected routes.

We would then modify App component to protect some components.

 

3. Protect Some Routes Using Protected Route Component

We would now modify our base App component to use our AuthProvider and Protected Route.

So in our App component,  we would make two changes:

  1. wrap the BrowserRouter inside the <AuthProvider> component
  2. include Protected Route component

So to protect the Product component, you will have to wrap it into the <ProtectedRoute> component like so:

<Route path="/product" element={<ProtectedRoute><Product></Product> </ProtectedRoute>} />

 

4. Manage Login and Logout

The two functions for managing user login and logout are available in the context and we just need to call each as needed.

For Login:

In the Login component, at successful user login we just need to call the login function and the same for logout.

Import the useAuth hook as shown below:

import { useAuth } from './AuthContext';

 

Next, you need to call the login function just before you navigate to the loginSuccess page.

For Logout:

In the AppBar component, import the useAuth hook as before.

Then you can write the logout event handler:

const logoutUser = () => {
  logout()
  navigate("/login")
}

 

Finally, in the Logout button, invoke the logoutUser() event handler

User Avatar

kindsonthegenius

Kindson Munonye is currently completing his doctoral program in Software Engineering in Budapest University of Technology and Economics

View all posts by kindsonthegenius →

Leave a Reply

Your email address will not be published. Required fields are marked *