Role-Based Access Control (RBAC) in MongoDB Schemas
Understand how to implement role-based access control in MongoDB schemas to restrict access based on user roles. Learn to add role fields to user models, create Express middleware for authorization, and test routes to secure admin and user access within a MERN stack application.
The previous lesson answered the authentication question: Who is this user? Authorization answers a different question: Is this user allowed to do this? A logged-in shopper and a logged-in admin are both authenticated, but only the admin should access an admin dashboard or delete another user’s data. Role-based access control (RBAC) handles this by assigning each user a role and checking that role before routes with restricted access run. It is common in production MERN applications, and it builds directly on the protect middleware.
Note: This is Express middleware and is read-along. It builds on the
Usermodel and theprotectmiddleware from the previous lessons, adding arolefield and a second guard.
To make the layering concrete, the next visual should show a request passing through both guards before an admin route:
That starts with recording the role of the user.
Adding a role to the User schema
RBAC begins in the data. Each user needs a role, and an enum restricts it to the allowed values, so an invalid role cannot be stored. A default makes ...