Implementing Role-Based Authentication and Authorization in React JS and Role-Based Access Control in React Node

Posted by


Role-based authentication and authorization is an important concept in web application development. It allows you to control what different types of users can and cannot access within your application based on their roles or permissions. In this tutorial, we will explore how to implement role-based authentication and authorization in a React JS application using Node.js for the backend.

Prerequisites

Before we get started, make sure you have Node.js installed on your machine. You can download it from https://nodejs.org/. Also, make sure you have a basic understanding of React JS and Node.js.

Setting Up the Node.js Server

  1. Create a new folder for your project and navigate to it in your terminal.
  2. Run the following command to initialize a new Node.js project:
    npm init -y
  3. Install the necessary dependencies by running the following command:
    npm install express mongoose body-parser jsonwebtoken
  4. Create a new file named server.js and add the following code to create a simple Express server:
    
    const express = require('express');
    const bodyParser = require('body-parser');

const app = express();

app.use(bodyParser.urlencoded({extended: false}));
app.use(bodyParser.json());

const PORT = process.env.PORT || 5000;

app.listen(PORT, () => {
console.log(Server is running on port ${PORT});
});


### Setting Up the MongoDB Database
1. Install MongoDB on your machine by following the instructions on the official website: https://docs.mongodb.com/manual/installation/
2. Create a new database named `role-based-auth` by running the following command in the MongoDB shell:

use role-based-auth


### Creating User Roles and Permissions
1. Create a new file named `models.js` and add the following code to define the User model:
```javascript
const mongoose = require('mongoose');
const Schema = mongoose.Schema;

const userSchema = new Schema({
  email: {type: String, required: true},
  password: {type: String, required: true},
  role: {type: String, required: true}
});

const User = mongoose.model('User', userSchema);

module.exports = User;
  1. Set up the connection to the MongoDB database in the server.js file:
    
    const mongoose = require('mongoose');

mongoose.connect(‘mongodb://localhost/role-based-auth’, {
useNewUrlParser: true,
useUnifiedTopology: true
}).then(() => {
console.log(‘Connected to MongoDB’);
}).catch((err) => {
console.error(Failed to connect to MongoDB: ${err});
});

3. Create a new file named `roles.js` and add the following code to define the roles and permissions:
```javascript
const ROLES = {
  ADMIN: 'admin',
  USER: 'user'
};

module.exports = ROLES;

Implement Role-Based Authentication and Authorization in React JS

  1. Create a new React project by running the following command in your terminal:
    npx create-react-app role-based-auth-react
  2. Install the necessary dependencies for role-based authentication and authorization:
    npm install axios react-router-dom
  3. Set up the routes in the App.js file:
    
    import { BrowserRouter as Router, Route, Switch } from 'react-router-dom';

function App() {
return (








);
}

4. Create the login form component:
```javascript
import React, { useState } from 'react';
import axios from 'axios';

function Login() {
  const [email, setEmail] = useState('');
  const [password, setPassword] = useState('');

  const handleSubmit = async (e) => {
    e.preventDefault();

    try {
      const response = await axios.post('http://localhost:5000/login', {
        email,
        password
      });

      localStorage.setItem('token', response.data.token);

      // Redirect to the appropriate route based on the user's role
    } catch (error) {
      console.error(error);
    }
  };

  return (
    <form onSubmit={handleSubmit}>
      <input type="email" value={email} onChange={(e) => setEmail(e.target.value)} />
      <input type="password" value={password} onChange={(e) => setPassword(e.target.value)} />
      <button type="submit">Login</button>
    </form>
  );
}
  1. Implement role-based authorization in the App.js file by checking the user’s role stored in the JWT token:

    function PrivateRoute({ component: Component, ...rest }) {
    return (
    <Route
      {...rest}
      render={(props) => {
        const token = localStorage.getItem('token');
    
        if (!token) {
          // Redirect to the login page
        }
    
        const user = JSON.parse(atob(token.split('.')[1]));
    
        if (user.role !== 'admin') {
          // Redirect to the home page
        }
    
        return <Component {...props} />;
      }}
    />
    );
    }
  2. Protect the admin route using the PrivateRoute component:
    <PrivateRoute path="/admin" component={Admin} />

Conclusion

In this tutorial, we have explored how to implement role-based authentication and authorization in a React JS application using Node.js for the backend. By following these steps, you can create a secure and scalable web application that effectively manages user roles and permissions. You can further enhance this implementation by adding more roles, permissions, and features as needed for your application.

0 0 votes
Article Rating

Leave a Reply

20 Comments
Oldest
Newest Most Voted
Inline Feedbacks
View all comments
@redduckok8419
1 hour ago

axios.defaults.withCredentials = true; its ok

@rizkyamin417
1 hour ago

i using token call api, my sidebar always refres

@ni3maboukharist680
1 hour ago

Pleas can you share github link for code sources

@khushbookumari-gj9ns
1 hour ago

can you send me link of signup , sigin page and databse , not visible in the description .

@thugninja1217
1 hour ago

No one saw the spelling mistake ? hmmm 🤔

@carryon6918
1 hour ago

bro i need to make web application for admin and user app for android how to do that

@sivaprasadgandepalli6272
1 hour ago

Thanks a lot 😊

@Eswaramoorthik
1 hour ago

can you share your git?

@Tinkugupta-e3h
1 hour ago

is there any series for this project ? only one video . I want to make this project.

@user_noway
1 hour ago

What if I want to create this for the owner of the website and no user can access this even it tries to change the URL to /login and it re-direct to the main website? how is that possible?

@Status-i8n
1 hour ago

Keep it up broo I will support you

@diyatripathi503
1 hour ago

source code pls?

@abdellahfethulaziz7673
1 hour ago

yeah we need the source code

@RakeMeUp
1 hour ago

bro lives in a cave

@nitugiri8872
1 hour ago

source code?

@bachtranngoc7587
1 hour ago

how to store the roles in session

@certificationcaci6469
1 hour ago

Thank you for your explanation,
You need to learn more bro, like code-first approach to create your DB
Good luck.

@rishabagarwal3628
1 hour ago

Source code please!!

@ashutoshkaushik2133
1 hour ago

source code pls !!

@Roozikhan565
1 hour ago

Hi

20
0
Would love your thoughts, please comment.x
()
x