Access controlling is one of the most important parts of every application, there are many kinds of models for access controlling like MAC (Mandatory Access Control), DAC (Discretionary Access Control), RBAC (Role Based Access Control) and etc (for more information about access models see this link)
loopback-authorization-extension is a powerful and generic implementation of HRBAC (Hierarchical Role Based Access Control) access model
Installation
npm i --save loopback-authorization-extension
Usage
Follow these steps to add authorization extension to your loopback4 application
Use the command lb4 repository for simplifing your Repository creation, then replace DefaultCrudRepository class with UserRepositoryMixin()(), RoleRepositoryMixin()() or PermissionRepositoryMixin()() as the parent class, then bind them
Now authorization extension is fully added and you can protect your endpoints using @authorize decorator
You can feel the power of loopback-authorization-extension is in this step, by using And types, Or types, Async Authorizers
// ...
import{MyPermissions}from"~/permissions.ts";
@authenticate(...)
@authorize<MyPermissions>({
and:["CREATE_USER","DELETE_USER"]
})
asynceditUser(...args): Promise<any>{...}
// ...
More about @authorize
This decorator accepts an object of type And or Or or StringPermissionKey or AsyncPermissionKey
your can define any logical combinations of your Permissions to control access much better
Example:
{
and: [
{key:"A"},
{key:"B"},
{key:"C",not:true},
{or:[{key:"D"},{key:"E"}]}
];
}
AsyncAuthorizer
In some special cases we need to check some other permissions or conditions such as querying in database or etc, for these cases we can use AsyncAuthorizer for running an async function of type (invocationContext) => Promise<boolean>
You can add or remove users, roles and permissions using your repositories
Many-To-Many relations
Users, Roles, Permissions has many-to-many relations, using, DefaultUserRoleRepository, DefaultRolePermissionRepository you can add some users to roles or assign permissions to roles