Role-based access control middleware in Express
layered authorization design.
authenticate first to set req.user, then a parameterized role-check middleware that compares req.user.role and returns 403 if it fails, applied to protected routes.
WHAT THIS TESTS Whether you can build authorization as a clean, reusable layer that runs after authentication and never trusts client-supplied roles.
A GOOD ANSWER COVERS RBAC layers on top of authentication. First, an authentication middleware verifies the JWT or session and sets req.user with the role taken from the trusted token payload or database, never from a request header the client controls. Second, you write a higher-order authorization middleware: a function authorize that takes the allowed roles and returns an Express middleware. That middleware checks whether req.user.role is in the allowed set; if so it calls next, otherwise it responds 403 Forbidden. You then chain the guards on protected routes so authentication runs before authorization. This keeps controllers free of access logic and makes the policy declarative at the route definition.
COMMON WRONG ANSWERS Reading the role from req.body or a custom header, scattering if-statements through controllers, returning 401 for a permission failure, or hardcoding a single role check that cannot be reused.
LIKELY FOLLOW-UPS Resource ownership checks versus role checks, where the role comes from, supporting multiple allowed roles, and how RBAC differs from attribute-based access control.
ONE CONCRETE EXAMPLE const authorize = (...roles) => (req, res, next) => { if (!roles.includes(req.user.role)) return res.status(403).json({ error: 'forbidden' }); next(); }; then app.delete('/api/users/:id', authenticate, authorize('admin'), deleteUser). A normal user passes authentication, gets req.user.role of user, fails the authorize('admin') check, and receives 403 without ever reaching the controller.
Read the original → techmarcos.com
Get five bites like this every day.
Tezvyn delivers a daily feed of 60-second tech bites with quizzes to lock in what you learn.