NA +91-8727899942 thecoderjob@gmail.com

CHAPTER - 20

How to apply Role based access control in node Js

Implementing Role-Based Access Control (RBAC) in a Node.js application involves defining roles, permissions, and middleware to check whether a user has the required permissions to access a particular route or resource.

Here's a step-by-step guide to help you implement RBAC in your Node.js application :

1. Define Roles and Permissions

2. Middleware for Role Authorization

3. Apply Middleware to Routes

4. User Authentication

Here's is the Code !!

//Step 1
const roles = {
  admin: ['read', 'write', 'delete'],
  user: ['read'],
  guest: []
};

//Step 2
function authorize(role, permission) {
  return (req, res, next) => {
    const userRole = req.user.role; // Assuming you have a user object with a role property
    
    if (!roles[userRole] || !roles[userRole].includes(permission)) {
      return res.status(403).json({ message: 'Unauthorized' });
    }

    next();
  };
}

//Step 3
const express = require('express');
const app = express();

// Assuming you have a middleware to authenticate users and attach them to the request object
// app.use(authenticate);

app.get('/admin/dashboard', authorize('admin', 'read'), (req, res) => {
  res.json({ message: 'Admin Dashboard' });
});

app.post('/admin/create', authorize('admin', 'write'), (req, res) => {
  res.json({ message: 'Create new item' });
});

app.get('/user/profile', authorize('user', 'read'), (req, res) => {
  res.json({ message: 'User Profile' });
});

//Step 4
function authenticate(req, res, next) {
  // Implement your authentication logic here
  // If authentication is successful, attach the user object to the request
  req.user = { id: '123', role: 'admin' }; // Example user object
  next();
}

Chapter 19

How to apply JSON Web Tokens in node Js

Previous chapter

Chapter 21

How to handling synchronous and asynchronous errors in node Js

Next chapter

Get In Touch

NA

thecoderjob@gmail.com

+91-8727899942

Popular Links

© www.thecoderjob.com. All Rights Reserved.               Designed by HTML Codex