AxilJS RBAC: Role and Permission-Based Access Control
Implement role-based access control (RBAC), permission-based authorization, and resource ownership checks in TypeScript and Node.js applications with AxilJS.
Role-Based Access Control (RBAC)
AxilJS provides authorization middleware for implementing role-based access control (RBAC), permission-based access control, and resource ownership checks in TypeScript and Node.js applications.
These authorization checks can be combined with JWT authentication to protect routes based on the authenticated user's role, permissions, or ownership of a resource.
Role-Based Access
Use requireRole() to restrict a route to one or more roles.
A single role can be provided as a string:
Multiple allowed roles can be provided as an array:
The authenticated user must have an allowed role to access the protected route.
Permission-Based Access Control
For more granular authorization, use requirePermission().
Permissions can represent specific application capabilities, such as:
This approach allows authorization rules to be defined around specific actions rather than relying only on broad user roles.
Wildcard Permissions
Permission patterns can use wildcards.
The admin:* pattern matches permissions such as:
This can be useful when a role or user should have access to an entire permission namespace rather than a single operation.
Resource Ownership
Use requireOwnership() when access should depend on whether the authenticated user owns the requested resource.
The 'id' argument identifies the route parameter used for the ownership check.
For example, with:
the middleware can use the id route parameter to determine whether the authenticated user owns the requested resource.
Administrators bypass the ownership check.
Combining Authentication and Authorization
Authentication and authorization can be composed as middleware:
The request first passes through JWT authentication and then through the role authorization check.
This separation keeps authentication and authorization responsibilities distinct.
Choosing an Authorization Strategy
Use role-based authorization when access is naturally grouped by roles:
Use permission-based authorization when you need fine-grained control over individual operations:
Use ownership checks when access depends on the relationship between the authenticated user and a resource:
These mechanisms can be used independently or composed with JWT authentication to enforce application-specific access-control rules.
Common RBAC Patterns
An administrator-only endpoint:
An endpoint available to multiple roles:
A permission-protected endpoint:
An ownership-protected endpoint: