Implement Role-Based Access Control
Role-Based Access Control, commonly called RBAC, restricts operations according to user roles.
Our application currently supports:
- user
- admin
Create a reusable middleware that checks whether the authenticated user has one of the permitted roles.
This middleware must execute after authentication because req.user is populated by the authentication middleware.
Role Authorization Middleware
export function authorize(...allowedRoles) {
return (req, res, next) => {
if (!req.user) {
return res.status(401).json({
success: false,
message: 'Authentication required'
});
}
if (!allowedRoles.includes(req.user.role)) {
return res.status(403).json({
success: false,
message: 'You do not have permission to perform this action'
});
}
next();
};
}Checks the authenticated user's role and rejects requests that do not meet the required permissions.
Key Takeaways
RBAC restricts operations according to user roles.
Authentication must execute before role authorization.
Return 403 when an authenticated user lacks permission.