Role Based Access Control (RBAC)
The RBAC component provides a clean and reusable middleware to restrict API access based on user roles (e.g., admin, user, manager). It integrates seamlessly with the authentication system.
Installation Guide
npx servercn-cli add rbacPrerequisites
This component assumes you have:
- Authentication Middleware: Detailed in the Verify Auth Middleware component.
- User Model: Your user schema/model should include a
rolefield. - Populated User: Your
req.userobject must contain theroleproperty.
If your authentication middleware only attaches the user ID (e.g., from a JWT payload), you may need to fetch the full user profile or include the role in the JWT payload.
Or follow the guides:
Ensure the following environment variables are defined in .env:
Ensure the following configuration are defined:
src/configs/env.ts
To ensure the authentication middleware functions correctly, your project must define a User model with a structure similar to the following.
src/models/user.model.ts
To access authenticated user data inside request handlers, define a custom request type.
src/types/user.ts
How It Works
The middleware accepts a list of allowed roles. When a request hits a protected route:
- It checks if
req.userexists. - It compares
req.user.roleagainst the allowed roles. - If matched, the request proceeds (
next()). - If not matched, it returns a 403 Forbidden error.
Basic Implementation
Here is the core logic for the RBAC middleware.
1. MVC Structure
src/middlewares/authorize-role.ts
2. Feature Structure
src/shared/middlewares/authorize-role.ts
Usage Example
Use authorizeRoles in your route definitions. It typically runs after your authentication middleware.
Extending Types
To make TypeScript happy with req.user.role, extend your Express Request type definition.
src/types/user.ts