AccessPolicy Decorator
The AccessPolicy
decorator is meant to be used in the routes you wish to protect.
#
Usagepost.controller.ts
@Get('posts')@AccessPolicy(allowedRoles, policyMethod1, policyMethod2, policyMethod3 ...)async getPosts(@Query('crudQuery') crudQuery: string) { const match = await this.postsService.findMany(crudQuery); return match;}
#
allowedRolesThe first parameter passed to @AccessPolicy()
specifies which roles should be granted access to the decorated route.
Acceptable values are:
- 'everyone': This option makes the route public, granting access to anyone regardless if they are authenticated or not.
- 'anyRole': This option makes the route accessible to anyone who is authenticated and has at least one role.
- An Array or Set of ids: the specific role ids which should be granted access to the decorated route. These will be compared with roles retrieved from authData by passing it to getRolesFromAuthDataFn.
#
policyMethodsAll values after allowedRoles
are policyMethods
. These are used to apply any access control logic that goes beyond simple role checks. They can be built in policies, or your own custom policies.
You can add multiple policies by simply including more arguments to @AccessPolicy(roles, ...policies)
. See usage.