REST API Masterclass
Architecting Modern Backends01.Home02.What is REST?03.HTTP Deep Dive04.URI Best Practices05.JSON & Data Formats06.Environment Setup07.Your First Resource08.Advanced Controllers09.Database Strategy10.JWT Authentication11.Role-Based Auth (RBAC)12.API Versioning13.Filtering & Searching14.Pagination & Sorting15.Global Error Handling16.Rate Limiting17.CORS & Security18.Swagger & OpenAPI19.Testing with Supertest20.Webhooks & Caching21.Production Checklist
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.