Custom authorization can be created using
@authorize.custom decorator. Wrap it using function to create a new decorator like below
Apply your new created authorization decorator like below
@authorize.custom receive two parameters a callback which will evaluate user authorization and
tag metadata that will be used for further metadata processing. The callback signature is like below
infoMetadata information about current authorization.
locationlocation of decorator applied
AuthorizationContext members is like below
roleis roles of current login user, single or multiple role
userCurrent login user
ctxKoa context of current request
valueoptional, value of current parameter (if authorization applied into parameter)
Example we will create custom authorization to authorize if the current user is an
Admin or the owner of the data. As an example we have controller to modify user data like below
Controller to modify above domain is like below
modify above will only authorized to
Admin or if the login user has the same ID with the requested data.
Above snippet we created a new decorator
@isAdminOrOwner() that can be applied to any method that the first parameter was the ID. Than we query if the current login user is an
Admin or have the same ID with the requested data. To apply above decorator simply add it above the
Putting authorization implementation inside decorator is simple and easy to read, but in some case it might cause circular dependency issue. You can use dependency resolver to solve this issue, by register the authorization classes by ID.
The first step, create a class implements
Authorizer interface like below.
Register the created resolver into the Plumier application
Then use the ID on each authorization applied.
This functionality work well with dependency injection, register the custom authorizer by name/id and plumier will automatically pass the ID into the custom dependency resolver.