Dynamic Role-Based Access Control (RBAC) with Granular Permissions in Node.js and React

In modern web applications, implementing a dynamic Role-Based Access Control (RBAC) system is crucial for managing user permissions effectively. This blog post covers how to build a scalable RBAC system in a Node.js and Express.js backend with a React frontend, ensuring real-time updates to user access across different roles.

Key Features of the RBAC System

▪️Granular Permissions: Permissions are dynamically configurable for each role.
▪️Real-time Updates: Changes in role permissions are instantly reflected in the application.
▪️Backend Enforcement: Middleware restricts access to APIs based on user roles.
▪️Frontend UI Control: Unauthorized users are prevented from accessing restricted UI elements.
▪️Scalability & Maintainability: Roles and permissions can be modified without changing the code.

How to Define and Store Permissions

Permissions should be stored in a roles table, where each role is associated with a list of allowed routes/actions. Example:

{
 "role": "Admin",
 "permissions": ["dashboard.view", "reports.view", "users.manage"]
}

This structure allows dynamic updates without modifying the codebase.

How Admins Can Update Permissions

Admins should have an API to modify user roles dynamically. The following workflow can be used:

Backend Implementation

Setting Up JWT Authentication

import jwt from "jsonwebtoken";
import { Request, Response, NextFunction } from "express";
import dotenv from "dotenv";


dotenv.config();


const generateTokens = (userId: string, role: string) => {
const accessToken = jwt.sign({ userId, role }, process.env.ACCESS_SECRET!, {
expiresIn: "15m",
});
const refreshToken = jwt.sign({ userId }, process.env.REFRESH_SECRET!, {
expiresIn: "7d",
});
return { accessToken, refreshToken };
};

Role & Permission Middleware

The Role & Permission Middleware describes how the backend enforces access control using a middleware function. Here’s how it works:

▪️Extract Token: It checks if the request has an authorization token.
▪️Decode Token: It verifies the JWT token and extracts the user’s role.
▪️Fetch Role Permissions: It retrieves the allowed permissions from the database.
▪️Check Permission: It verifies if the user has the required permission.
▪️Authorize or Reject: If the permission is missing, it returns a 403 Forbidden response; otherwise, it allows the request to proceed.

This ensures that only authorized users can access specific API routes dynamically, based on their assigned permissions.

Related read: Learn How To Implement Role-based API Authorization In Node.js

import { Request, Response, NextFunction } from 'express';
import jwt from 'jsonwebtoken';
import RoleModel from '../models/roleModel';


type DecodedToken = {
userId: string;
role: string;
};


export const roleMiddleware = (requiredPermission: string) => async (req: Request, res: Response, next: NextFunction) => {
try {
const token = req.headers.authorization?.split(' ')[1];
if (!token) return res.status(401).json({ message: 'Unauthorized' });


const decoded = jwt.verify(token, process.env.ACCESS_SECRET!) as DecodedToken;
const userRole = await RoleModel.findOne({ role: decoded.role });


if (!userRole || !userRole.permissions.includes(requiredPermission)) {
return res.status(403).json({ message: 'Forbidden' });
}
next();
} catch (error) {
res.status(500).json({ message: 'Internal Server Error' });
}
};

Admin API to Manage Permissions

To allow admins to dynamically manage user permissions, we need an API that updates the permissions for specific roles. Here’s how the request will be processed:

▪️The admin sends a request with the updated permissions for a role.
▪️The backend verifies if the admin has the necessary privileges.
▪️If authorized, the backend updates the permissions in the database.
▪️Changes take effect immediately, without requiring a restart.

Controller (Admin Permissions Management)

import { Request, Response } from "express";
import RoleModel from "../models/roleModel";


export const updateRolePermissions = async (req: Request, res: Response) => {
try {
const { role, permissions } = req.body;
const updatedRole = await RoleModel.findOneAndUpdate(
{ role },
{ permissions },
{ new: true }
);


if (!updatedRole) {
return res.status(404).json({ message: "Role not found" });
}


res
.status(200)
.json({ message: "Permissions updated successfully", updatedRole });
} catch (error) {
res.status(500).json({ message: "Error updating permissions", error });
}
};

Example API Request

PUT /api/admin/roles/permissions
Content-Type: application/json
Authorization: Bearer <admin-token>

{
 "role": "Manager",
 "permissions": ["dashboard.view", "reports.view"]
}

Expected Response

{
"message": "Permissions updated successfully",
"updatedRole": {
 "role": "Manager",
 "permissions": ["dashboard.view", "reports.view"]
 }
}

This ensures that role permissions can be updated dynamically and securely by authorized admins.

import { Request, Response } from "express";
import RoleModel from "../models/roleModel";


export const updateRolePermissions = async (req: Request, res: Response) => {
try {
const { role, permissions } = req.body;
await RoleModel.findOneAndUpdate({ role }, { permissions });
res.status(200).json({ message: "Permissions updated successfully" });
} catch (error) {
res.status(500).json({ message: "Error updating permissions" });
}
};

Secure Your React Frontend With Granular Role-Based Access — Get Started With Our ReactJS Development Services

Frontend Implementation

Restricting UI Elements Dynamically

In the frontend, we need to ensure that users only see the elements they have permission to access. This can be achieved using React context and conditional rendering.

Related read: Building Scalable Applications with React Micro Frontends

import { useContext } from "react";
import { AuthContext } from "../context/AuthContext";


const Dashboard = () => {
const { user } = useContext(AuthContext);


return (
<div>
<h1>Dashboard</h1>
{user?.permissions.includes("dashboard.view") && (
<p>Welcome to the Dashboard</p>
)}
{user?.permissions.includes("reports.view") && (
<button>View Reports</button>
)}
</div>
);
};


export default Dashboard;

Protecting Routes in React

To prevent unauthorized users from accessing protected pages, we implement a ProtectedRoute component that checks user permissions before rendering a page.

import { Navigate } from "react-router-dom";
import { useContext } from "react";
import { AuthContext } from "../context/AuthContext";


const ProtectedRoute = ({ children, requiredPermission }) => {
const { user } = useContext(AuthContext);
if (!user || !user.permissions.includes(requiredPermission)) {
return <Navigate to="/unauthorized" />;
}
return children;
};


export default ProtectedRoute;

Integrating Role-Based Routing in App.js

import { BrowserRouter as Router, Routes, Route } from "react-router-dom";
import Dashboard from "./pages/Dashboard";
import Reports from "./pages/Reports";
import Unauthorized from "./pages/Unauthorized";
import ProtectedRoute from "./components/ProtectedRoute";


const App = () => {
return (
<Router>
<Routes>
<Route
path="/dashboard"
element={
<ProtectedRoute requiredPermission="dashboard.view">
<Dashboard />
</ProtectedRoute>
}
/>
<Route
path="/reports"
element={
<ProtectedRoute requiredPermission="reports.view">
<Reports />
</ProtectedRoute>
}
/>
<Route path="/unauthorized" element={<Unauthorized />} />
</Routes>
</Router>
);
};


export default App;

Real-World Example

Imagine an application with three roles: Admin, Manager, and Employee.

▪️Admin: Can manage users, view reports, and modify permissions.
▪️Manager: Can view reports but cannot modify permissions.
▪️Employee: Can access only the dashboard.

If an Admin updates the Manager’s permissions to include “users.manage”, the Manager instantly gains access to that API and UI element, without requiring a code change.

Security Best Practices

▪️Use short-lived access tokens (e.g., 15 minutes) and refresh tokens.
▪️Store tokens securely (use HTTP-only cookies instead of local storage).
▪️Rate-limit authentication endpoints to prevent brute-force attacks.
▪️Implement logging & monitoring to track permission updates.

coma

Conclusion

This dynamic RBAC system provides granular permission control, allowing real-time updates to user access. By separating concerns between the backend (authorization enforcement) and frontend (UI access control), we ensure a secure, scalable, and maintainable authentication and authorization model.

Keep Reading

Keep Reading

  • Service
  • Career
  • Let's create something together!

  • We’re looking for the best. Are you in?