Node.js Course
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

Loading Code Playground...

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?

Flash Cards

Question

What status code?

Click to reveal answer
Answer

403 Forbidden.

Question

How to implement it in Express?

Click to reveal answer
Answer

Create a middleware factory function. It checks the decoded JWT (or session) attached to the `req` object. If `req.user.role !== requiredRole`, send a 403. Otherwise, call `next()`.