How to implement role-based access control in Node.js and Express application

Role-based access control (RBAC) is a crucial feature in many applications that ensures users have the right permissions based on their roles. Despite its importance, there’s only a few resources explaining how to build this feature in Node.js and Express. In this article, I’ll demonstrate how to successfully deploy RBAC in your application.

Step 1: Create a Role-Authorization Middleware

In our application, we’ll assume there are three roles: admin, mentor, and student. Each user account will have at least one role, and some users may have multiple roles.

//Define the 'role' field in your user schema

role: {

type: [String],

enum: ['admin', 'student', 'student-leader', 'mentor'],

default: ['student'],

},

Next, create a role-authorize.js file in your middleware folder:

const restrict = (...role: any) => {

return (req: Request, res: Response, next: NextFunction) => {

const userRoles = req.user.role;

if (!userRoles.some((r) => role.includes(r))) {

throw new UnauthenticatedError(

'Your roles are not allowed to access this route'

);

}

next();

};

};

Voilà! We’ve created a middleware that will only allow the request to proceed to the next function if the user’s role is allowed. Now, let’s use this middleware in our routes.

Step 2: Implement Role-Based Authorization in Routes

You can easily implement role-based authorization in your routes by passing the roles as arguments to the restrict middleware. For example:

router.route('/').get(getAllSession).post(restrict('mentor', 'student'), createSession);

The advantage of this approach is that it allows users to have multiple roles, and you can specify which roles are restricted for certain routes.

By following these steps, you can enhance the security of your Node.js and Express application by implementing role-based access control, ensuring that users only access the parts of your application that are appropriate for their roles.

Published by

Leave a comment