Express.js
/Beginner
Role-Based Authorization
Definition
Authorization happens *after* Authentication. While auth verifies WHO you are, authorization verifies WHAT you are allowed to do. Role-Based Access Control (RBAC) involves checking a user's role (admin, user, editor) before granting access to a specific route.
Explain Like I'm New
Authorization happens *after* Authentication.
Interactive Example
// Middleware factory function const restrictTo = (...roles) => { return (req, res, next) => { // req.user was attached by the JWT middleware previously if (!roles.includes(req.user.role)) { return res.status(403).json({ error: 'You do not have permission to perform this action' }); } next(); }; }; // Only admins or lead-guides can delete tours app.delete('/tours/:id', protect, restrictTo('admin', 'lead-guide'), deleteTour);
Interview Questions
basic
- What is the primary purpose of Role-Based Authorization in Express.js?
- How do you initialize Role-Based Authorization?
intermediate
- How does Role-Based Authorization integrate with other middleware components?
- Can you explain a common use case for Role-Based Authorization?
advanced
- What are the performance implications of Role-Based Authorization in a high-traffic production application?
- How would you debug issues related to Role-Based Authorization?
trick
- Is it possible to achieve the same result as Role-Based Authorization without using Express?