Role-Based Access Control (RBAC)
Authentication answers "Who are you?". Authorization (RBAC) answers"What are you allowed to do?".
1. Defining Roles
Commonly, users are assigned string roles such as "user", "editor", or "admin".
2. Restricting Routes
Create a middleware that checks the user's role before allowing the request to continue.
const restrictTo = (...roles) => {
return (req, res, next) => {
// req.user was populated by your JWT middleware
if (!roles.includes(req.user.role)) {
return res.status(403).json({
error: 'You do not have permission for this action'
});
}
next();
};
};
// Usage
router.delete('/:id', restrictTo('admin'), deleteUser);
3. Resource-Level Authorization
Sometimes roles aren't enough. An "Admin" can edit any post, but a "User" should only edit their own post.
if (post.authorId !== req.user.id && req.user.role !== 'admin') {
return res.status(403).json({ error: 'Access denied' });
}
4. The Principle of Least Privilege
Always default to No Access. Only grant the minimum permissions required for a user to perform their task.
Pro Pattern: For complex systems, use Permissionsinstead of Roles (e.g., can_edit_posts). A Role then becomes just a collection of these Permissions.