Node.js › Authentication & Authorization
What is Role-Based Access Control (RBAC), and how would you implement it as Express middleware?
IntermediateAnswer
RBAC assigns each user one or more roles (like 'admin', 'editor', 'viewer'), and access to specific resources or actions is granted based on the role rather than checking individual permissions per user -- this simplifies permission management considerably when many users share the same access needs, since granting or revoking access to a whole category of actions is done once at the role level rather than per user.
function requireRole(...allowedRoles) {
return (req, res, next) => {
if (!allowedRoles.includes(req.user.role)) {
return res.status(403).json({ error: 'Insufficient permissions' });
}
next();
};
}
app.delete('/users/:id', requireAuth, requireRole('admin'), deleteUserHandler);
app.put('/posts/:id', requireAuth, requireRole('admin', 'editor'), updatePostHandler);Real-world example A content-management API restricts the DELETE /users/:id endpoint to only the 'admin' role while allowing both 'admin' and 'editor' roles to update posts, implemented as a single reusable requireRole() middleware parameterized differently per route rather than duplicating permission-check logic in each handler.