This website uses cookies to ensure you get the best experience on our website.

Skip to content
LOGO
  • Company

    About IGNEK

    Learn about our story and our mission.

    Careers

    We're hiring!

    We always looking for talented peoples. Join our team!

    Blogs

    The latest industry news, updates and info.

    Case Studies

    Take a closer look at the projects we've delivered

    Webinar

    Watch our latest organized webinar

    Get in touch with our HR team

    • hr@ignek.com
    • +91 93284 95160
    • Ahmedabad, Gujarat, India – 382470
  • Services

    Enterprise Portal Development

    Custom Enterprise Portal Development for flawless Solutions

    Dedicated Development Team

    Expand Teams, Optimize Development with Our Expertise

    Back-end Development

    Empowering your digital presence with robust backend development expertise

    Front-end Development

    Crafting engaging user experiences through expert frontend development

    Digital Transformation

    Embrace digital transformation by modernizing process

    SaaS Development

    Transform your business with SaaS Innovative Solutions

    Technologies

    Liferay Services

    Development & Customization

    Theme

    Upgradation

    Migration

    Proof of Concept

    Performance Tunning

    Architecture

    Support & Maintenance

    E-commerce

    Expert Advice

    React Services

    Enterprise Development

    Custom Application

    Single Page Application

    Architecture

    API Integration

    Migration

    Consulting

    Maintenance & Support

    Spring Boot Services

    Web Service

    MVC Web Development

    API Integration

    Security

    Migration

    Microservices

    Support & Maintenance

    AEM Services

    Consulting Service

    Site Development

    Migration & Upgradation

    Integration

    Maintenance & Support

    Custom Solutions

    Content Management

    Team Augementation

  • Solution

    Ready for digital excellence

    In our rapidly evolving world, businesses are always on the lookout for fresh ways to improve their operations and connect with their audiences.

    Contact US

    Solutions

    SaaS : Software As A Service

    Transforming industries through cutting edge SaaS solutions.

    Customer Portal : Boost Business Productivity

    Streamline operations and enhance productivity with our Customer Portal solution.

    Liferay Based Intranet Portal

    Internal portal for company communication, collaboration and resources

    Integration

    Matomo Integration with Liferay

    Integrate Matomo to enable user interactions seamlessly.

    Microsoft Teams integration with Liferay

    Integrate to enable seamless collaboration, messaging within your portal.

    Jira Integration With Liferay

    Optimizes business operations by integrating with Jira.

  • Hire Us

    Liferay

    Get expert Liferay developers for seamless portal solutions.

    React JS

    Get expert ReactJS developers for dynamic web solutions.

    Web Developer

    Get custom web solutions from IGNEK's expert developers.

    Spring Boot

    Get top-notch Spring Boot developers for your project success!

    Healthcare

    Get top Healthcare Developers for cutting-edge medical software.

    MERN Stack

    Get expert MERN developers from IGNEK for custom, innovative project solutions.

    Why Hire Developers From IGNEK ?

    • Certified Developer
    • Transparent Communication
    • Flexible Hiring Modals
    • Fully Signed NDA
    • Cost Effective
    • Easy Exit Policy

    Get in touch with our Sales team

    • sales@ignek.com
    • +91 6351576580
    • info@ignek.com
    • Ahmedabad, Gujarat, India – 382470
SCHEDULE CALL
  • COMPANY
    • About
    • Case Studies
    • Blogs
    • Career
    • Webinar
  • SERVICES
    • Enterprise Portal Development
    • Dedicated Development Team
    • Back-end Development
    • Front-end Development
    • Digital Transformation
    • SaaS Development
  • SOLUTION
    • Customer Portal:  Boost Business Productivity
    • SaaS : Software as a Service
    • Liferay Based Employee Intranet Portal
  • TECHNOLOGY
    • Liferay Services
      • Liferay Development and Customization
      • Liferay Theme Development Service
      • Liferay DXP 7.4 Upgrade
      • Liferay Migration
      • Liferay Proof Of Concept
      • Liferay Performance Tuning
      • Liferay Architecture Design Service
      • Liferay Support And Maintenance Service
      • Liferay Ecommerce Development
      • Liferay Expert Advice
    • ReactJS Services
      • ReactJS Enterprise Application Development
      • ReactJS Custom Application Development
      • ReactJS Single Page Application Development (SPA)
      • ReactJS Applications Architecture
      • ReactJS API Integration
      • ReactJS Migration
      • ReactJS Consulting
      • ReactJS Maintenance and Support
    • Spring Boot Services
      • Spring Boot Web Development Service
      • Spring MVC Web Development
      • Spring Boot API Integration Service
      • Spring Boot Security
      • Spring Boot Migration Service
      • Spring Boot Microservices
      • Spring Boot Support & Maintenance Service
    • AEM Development Services
      • AEM Consulting Services
      • AEM Site Development
      • AEM Migration & Upgradation
      • AEM Integration Services
      • AEM Maintenance & Support
      • AEM Content Management
      • Custom AEM Solutions
      • AEM Team Augmentation
  • INTEGRATION
  • HIRE US
    • Hire Liferay Developer
    • Hire ReactJS Developer
    • Hire Spring Boot Developer
    • Hire Healthcare Developer
    • Hire Web Developer
    • Hire MERN Stack Developer
  • CONTACT US
  • Company

    About IGNEK

    Careers

    We're hiring!

    Blogs

    Case Studies

    Webinar

    Get in touch with our HR team

    • hr@ignek.com
    • +91 93284 95160
    • Ahmedabad, Gujarat, India – 382470
  • Services

    Enterprise Portal Development

    Dedicated Development Team

    Back-end Development

    Front-end Development

    Digital Transformation

    SaaS Development

    Technologies

    Liferay Liferay Services
    • Development & Customization
    • Theme
    • Upgradation
    • Migration
    • Proof of Concept
    • Performance Tuning
    • Architecture
    • Support & Maintenance
    • E-commerce
    • Expert Advice
    React React Services
    • Enterprise Development
    • Custom Application
    • Single Page Application
    • Architecture
    • API Integration
    • Migration
    • Consulting
    • Maintenance & Support
    Spring Boot Spring Boot Services
    • Web Service
    • MVC Web Development
    • API Integration
    • Security
    • Migration
    • Microservices
    • Support & Maintenance
    AEM AEM Services
    • Consulting Service
    • Site Development
    • Migration & Upgradation
    • Integration
    • Maintenance & Support
    • Custom Solutions
    • Content Management
    • Team Augmentation
  • Solution

    Ready for digital excellence

    In our rapidly evolving world, businesses are always on the lookout for fresh ways to improve their operations and connect with their audiences.

    Contact US

    Solutions

    SaaS : Software As A Service

    Customer Portal : Boost Business Productivity

    Liferay Based Intranet Portal

    Integration

    Matomo Integration with Liferay

    Microsoft Teams integration with Liferay

    Jira Integration With Liferay

  • Hire Us

    Liferay

    React JS

    Web Developer

    Spring Boot

    Healthcare

    MERN Stack

    Why Hire Developers From IGNEK ?

    • Certified Developer
    • Transparent Communication
    • Flexible Hiring Modals
    • Fully Signed NDA
    • Cost Effective
    • Easy Exit Policy

    Get in touch with our Sales team

    • sales@ignek.com
    • +91 6351576580
    • IGNEK
    • Ahmedabad, Gujarat, India – 382470
  • SCHEDULE CALL

Authentication and Authorization in React

  • ReactJS
  • March 27, 2024

Share On :

Introduction

Mastering authorization and authentication in React.js is crucial for building secure, scalable, and user-friendly applications. This blog will guide you through the intricacies of authentication and authorization in React.js. From understanding the fundamentals to implementing advanced features, we will explore best practices and real-world scenarios to empower you in creating resilient and secure applications.

Prerequisites:
  • Node.js and npm
  • React
  • Typescript
  • React-Query
  • Axios

 

Understanding Authentication and Authorization: 

Before we dive into the details of authentication and authorization, let’s consider a few important aspects.   

  • Difference Between Authentication and Authorization:
    Authentication and authorization are often used interchangeably, but they serve distinct purposes in the context of web security. Authentication verifies the identity of a user, ensuring that they are who they claim to be. This process involves validating credentials, commonly through a username and password. Authorization, on the other hand, is about determining what actions or resources a user can access after being authenticated.

  • Common Authentication Methods:
    There are three common methods of user authentication:
    1. Username/Password Authentication: This is the traditional method where users enter a unique username and a secure password to access their accounts.
    2. Social Login: This method uses OAuth or OpenID Connect to authenticate users through social media accounts like Google, Facebook, etc. It provides a seamless and secure login experience. 
    3. Token-based Authentication: This method authenticates users using tokens, such as JSON Web Tokens (JWTs). Upon successful login, tokens are issued and sent with each subsequent request to grant access.

 

  • Differentiating between Client-side and Server-side Authentication:
    Client-side authentication refers to authenticating users directly within the React.js application. This method may not be as secure, as sensitive information such as tokens may be exposed to potential threats. On the other hand, server-side authentication is handled on the server, and the client receives a session or token upon successful authentication. This approach is generally more secure as sensitive operations are carried out on the server.

  • Authorized According to User Role:
    Role-Based Access Control (RBAC) is an essential aspect of authorization in various applications. In React.js, users are given specific roles like admin, user, or moderator, and their access to resources or functionalities is granted based on these roles. The user interface can be dynamically adjusted based on the user’s role using conditional rendering in React components. This provides a personalized and secure experience for each user.

 

A Comprehensive Guide to Application:

This application is an authentication and authorization app with a login, register, and role-based dashboard UI. It consists of a React.js frontend and Node.js backend server with Express for REST APIs and MySQL DB. We have already created a Dockerized Backend server in NodeJS and Connected it with the MySQL DB, we also utilized it and will create this React application also dockerized. The focus of this blog revolves around the process of Authentication and Authorization in React. For the complete Server and Database connecting implementation, refer to the following link: Docker Compose for Node.js and MySQL Integration. 

To connect the React application to the same network and create a new docker container in docker-compose, you can use the Docker file for the Client folder.

 

# Use an official Node runtime as a parent image

FROM node:latest

# Set the working directory in the container

WORKDIR /app

# Copy package.json and package-lock.json to the container

COPY package*.json ./

# Install app dependencies

RUN npm install

# Copy the React app files to the container

COPY . .

#Defining the port

EXPOSE 3000

# Command to run the application

CMD [“npm”, “start”]

By following our guide, you can easily build a secure and efficient React application.

folder structure | Authentication and Authorization in React

Navigating the Frontend Setup In React:

Let’s start the UI implementation for the Login and Register components and role-based dashboard navigation using React with a TypeScript template. We will also set up React-router-dom and React-Query.

  1.  Initializing React Application:

    To create a React application, you need to start by creating a project folder in your root directory. Inside the project folder, create a client folder and install the necessary dependencies by running the following commands.

    //Create react app using the following cmd

    npx create-react-app client –template typescript


    //Install the required dependencies 

    npm i react-router-dom axios react-query

    • React-router-dom: It is an npm package that allows you to implement dynamic routing in a web app.
    • Axios/ Axios-Interceptor: Axios/Axios-Interceptors provide a powerful way to intercept and modify HTTP requests and responses.
    • React-Query: It offers an efficient way to handle server requests. 
  2. Implementing User Registration and Login: Please follow the below steps to implement user registration and login in your project:

    In the project client folder, locate the App.tsx file which serves as the entry point for the project.

    • Use React-router-dom to create routes for login, register, user dashboard, and admin dashboard.
    • Create a custom component for handling API requests. For optimal implementation, please refer to this link: Optimizing Network Requests in React with Axios Interceptors and React Query
    • Create separate files for Register.tsx and Login.tsx and design the user interface according to your preference.

				
					// Imports
… 
const Register = () => {
   …
  const [formData, setFormData] = useState<ApiParams>({
    fullName: "",
    username: "",
    email: "",
    phoneNumber: "",
    password: "",
    confirmPassword: "",
    role: "",
  });
  const handleChange = (e: React.ChangeEvent<HTMLInputElement>) => {
    const { name, value } = e.target;
    setFormData((prevData) => ({ ...prevData, [name]: value }));
  };
  
  const mutation = useApiMutation<ApiResponse, ApiParams>(      
  //API mutation hook for registration
    "/auth/register",
    "post",
    {
      onSuccess: (data) => {
        alert(data?.msg);
      },
      onError: (error) => {
        console.error("Mutation error:", error);
      },
    }
  );

  const handleSubmit = (e: React.FormEvent<HTMLFormElement>) => {  
  //Handle form submission
    e.preventDefault();
    if (formData.password !== formData.confirmPassword) {
      alert("Passwords do not match");
      return;
    }
    mutation.mutate({ data: formData });     
    // Make the API call
  };
return (
    <div className="container">
      <div className="title">Registration</div>
      <form onSubmit={handleSubmit}>
        … 
        …
        … 
      </form>
    </div>
  );
};
export default Register;



… imports

const Login = () => {
…
  const [formData, setFormData] = useState<ApiParams>({
    email: "",
    password: "",
  });
  const navigate = useNavigate();
  const handleChange = (e: React.ChangeEvent<HTMLInputElement>) => {
    const { name, value } = e.target;
    setFormData((prevData) => ({ ...prevData, [name]: value }));
  };
  //API mutation hook for login
  const mutation = useApiMutation<ApiResponse, ApiParams>(
    "/auth/login",
    "post",
    {
      onSuccess: (data) => {
        alert(data?.msg);
        localStorage.setItem("token", data?.token); //set token in localstorage 
         localStorage.setItem("role", data?.role);
        //role based navigation
        if (data?.role === "admin") {
          navigate("/admin/dashboard");
        } else {
          navigate("/user/dashboard");
        }
      },
      onError: (error) => {
        console.error("Mutation error:", error);
      },
    }
  );

  // Handle form submission
  const handleSubmit = (e: React.FormEvent<HTMLFormElement>) => {
    e.preventDefault();
       mutation.mutate({ data: formData });   // Make the API call
  };

  return (
    <div className="container">
      <div className="title">Login</div>
      <form onSubmit={handleSubmit}>
        …
      </form>
    </div>
  );
};

export default Login;


				
			

Let’s comprehend what we’ve written in the code.

    • import the hooks and files from there path.
    • Validate user input and form submission using the handleSubmit function 
    • Making API requests to the server for user authentication. To implement it we have initialized the API hook and here use the useApiMutation hook in both components.
    • At Login, we are setting the token and role in the local storage for further APIs authorization and navigation for the dashboard.

     3. Securing Routes with Protected Routes:

To secure routes, we create a new utility file named ProtectedRoutes.tsx in the client folder. This file contains the implementation code that checks if a user is logged in or not by verifying the token stored in the local storage.

				
					…
const ProtectedRoute: React.FC<{ children: ReactNode }> = ({ children }) => {
  const { isAuthenticated } = useContext(AuthContext) as ContextAuth;
  const AllRoutes = useMemo(
    () => React.lazy(() => import("../routes/IndexRoute")),
    []
  );

  return (
    <Suspense fallback="...Loading">
      <AllRoutes>
        {isAuthenticated ? children : <Navigate to="/login" />}
      </AllRoutes>
    </Suspense>
  );
};

export default ProtectedRoute;

				
			

Let’s comprehend what we’ve written in the code.

    • A context was created to globally check for token availability.
    • The navbar is dynamically imported to show for authorized users otherwise redirect to login.

 

Configure this component in our route folder.

				
					function Routes() {
  return (
    <RouterRoutes>
   …
      {adminRoutes.map(({ path, component: Component }) => (
        <Route
          key={path}
          path={path}
          element={
            <ProtectedRoute> //checking protected route
              <Component />
            </ProtectedRoute>
          }
        />
      ))}
      {userRoutes.map(({ path, component: Component }) => (
        <Route
          key={path}
          path={path}
          element={
            <ProtectedRoute> //checking protected route 
              <Component />
            </ProtectedRoute>
          }
        />
      ))}
      <Route path={"/"} element={<Navigate to="/login" />} />
    </RouterRoutes>
  );
}
export default Routes;

				
			

The main highlight is wrapping the user and admin route for the whole client application. When a component is passed as a child, it will check whether the user or admin route is authorized or not. 

Lastly, after the user logs in, we check their role and redirect them to the appropriate routes based on their role.

 

Conclusion:

Wrapping up our journey, we’ve successfully crafted an Authentication and Authorization Application using React. To enhance its efficiency and deployment, we’ve containerized it using Docker-Compose. Additionally, we’ve implemented a user-friendly role-based navigation system, ensuring a seamless experience throughout the application. With these enhancements, our application is not just secure but also user-centric, making it a robust solution for authentication and authorization needs in your projects.

 

Output:
output1 e1737977173604 | Authentication and Authorization in React
output2 e1737977200930 | Authentication and Authorization in React

Explore Our Services

Discover how we can help your business thrive, whether you’re running a small startup, an SME, or a large enterprise. We’re here to understand your unique needs and goals, offering the expertise and resources to support your journey to success.

Stay informed about our ReactJS services and updates by subscribing to our newsletter—just fill in the details below to subscribe.

Loading
Loading...

Related Blogs

November 10, 2023
Debugging React.js and GraphQL in Liferay cover image
Debugging React.js and GraphQL in Liferay
November 10, 2023
Leveraging Common Components in React TypeScript Projects with Liferay cover image
Explore Common Components in React TypeScript with Liferay's
March 27, 2024
Docker Compose for Node.js and MySQL Integration
Loading...

Featured Projects Portfolios

October 4, 2023
Enterprise Website _ Weekly Blogs and Educational Resources
Enterprise Website : Weekly Blogs and Educational Resources
October 4, 2023
Telemedicine Appointment & Health Record Portal
Telemedicine Appointment & Health Record Portal
October 3, 2023
Simplify Approvals and Goals With Agenda & Meeting SaaS Platform
Simplify Approvals and Goals With Agenda & Meeting SaaS Platform

Digital Solutions for Your Business with IGNEK

4.9

5.0

5.0

5.0

LOGO

Making the world a better place through constructing elegant hierarchies

COMPANY

  • About
  • Career
  • Case Study
  • Blogs

SERVICES

  • Enterprise Portal Development
  • Dedicated Development Team
  • Back-end Development
  • Front-end Development
  • Digital Transformation
  • SaaS Development

HIRE US

  • Liferay
  • Spring Boot
  • ReactJS
  • Healthcare
  • MERN Stack
  • AEM

CONTACT

  • info@ignek.com
  • info@ignek.com
SALES
  • sales@ignek.com
  • (+91) 635 157 6580
CAREER
  • hr@ignek.com
  • (+91) 932 849 5160
  • E 910-912, Ganesh Glory 11, Jagatpur Road, SG Highway, Ahmedabad, Gujarat - 382470

© 2018-2025 IGNEK, Inc. All rights reserved

Linkedin Facebook X-twitter Instagram