Node.js
/Intermediate
Role Based Access Control (RBAC)
Definition
An approach to restricting system access to authorized users based on their assigned role (e.g., 'user', 'admin', 'moderator').
Explain Like I'm New
Authentication (Login) asks: 'Who are you?'. Authorization (RBAC) asks: 'Are you allowed to do this?'. If an ordinary user tries to send a DELETE request to `/api/users/all`, the RBAC system checks their role. Since their role is 'user' and not 'admin', the system throws a 403 Forbidden error and blocks the request.
Real World Example
Adding a `role` field to your Mongoose User schema. Writing a generic `requireRole('admin')` Express middleware and plugging it into sensitive administrative routes.
Common Use Cases
- •Admin dashboards
- •Multi-tier subscription models (free vs premium features)
Interactive Example
// 1. The RBAC Middleware Factory // It takes the role we WANT to require, and returns a middleware function const authorize = (requiredRole) => { return (req, res, next) => { // Assume req.user was populated by a previous JWT authentication middleware const user = req.user; if (!user) { return console.log("401 Unauthorized: Please log in."); } if (user.role !== requiredRole) { return console.log(`403 Forbidden: You are a ${user.role}, but this requires ${requiredRole}!`); } console.log("Access Granted! Proceeding to route..."); next(); }; }; // 2. Simulated Requests const mockNext = () => console.log("--> Reached Controller Logic\n"); console.log("--- Alice (Admin) requesting Dashboard ---"); const reqAlice = { user: { name: "Alice", role: "admin" } }; authorize('admin')(reqAlice, {}, mockNext); console.log("--- Bob (User) requesting Dashboard ---"); const reqBob = { user: { name: "Bob", role: "user" } }; authorize('admin')(reqBob, {}, mockNext);
Interview Questions
basic
- What HTTP status code is returned if a user is authenticated, but lacks the proper role?
intermediate
- How do you implement RBAC in an Express application?