Authorization

Authorization refers to the process that determines what a user is able to do. For example, an administrative user is allowed to create, edit, and delete posts. A non-administrative user is only authorized to read the posts.

Authorization is orthogonal and independent from authentication. However, authorization requires an authentication mechanism.

There are many different approaches and strategies to handle authorization. The approach taken for any project depends on its particular application requirements. This chapter presents a few approaches to authorization that can be adapted to a variety of different requirements.

Basic RBAC implementation

Role-based access control (RBAC) is a policy-neutral access-control mechanism defined around roles and privileges. In this section, we’ll demonstrate how to implement a very basic RBAC mechanism using Nest guards.

First, let’s create a Role enum representing roles in the system:

  1. @@filename(role.enum)
  2. export enum Role {
  3. User = 'user',
  4. Admin = 'admin',
  5. }

info Hint In more sophisticated systems, you may store roles within a database, or pull them from the external authentication provider.

With this in place, we can create a @Roles() decorator. This decorator allows specifying what roles are required to access specific resources.

  1. @@filename(roles.decorator)
  2. import { SetMetadata } from '@nestjs/common';
  3. import { Role } from '../enums/role.enum';
  4. export const ROLES_KEY = 'roles';
  5. export const Roles = (...roles: Role[]) => SetMetadata(ROLES_KEY, roles);
  6. @@switch
  7. import { SetMetadata } from '@nestjs/common';
  8. export const ROLES_KEY = 'roles';
  9. export const Roles = (...roles) => SetMetadata(ROLES_KEY, roles);

Now that we have a custom @Roles() decorator, we can use it to decorate any route handler.

  1. @@filename(cats.controller)
  2. @Post()
  3. @Roles(Role.Admin)
  4. create(@Body() createCatDto: CreateCatDto) {
  5. this.catsService.create(createCatDto);
  6. }
  7. @@switch
  8. @Post()
  9. @Roles(Role.Admin)
  10. @Bind(Body())
  11. create(createCatDto) {
  12. this.catsService.create(createCatDto);
  13. }

Finally, we create a RolesGuard class which will compare the roles assigned to the current user to the actual roles required by the current route being processed. In order to access the route’s role(s) (custom metadata), we’ll use the Reflector helper class, which is provided out of the box by the framework and exposed from the @nestjs/core package.

  1. @@filename(roles.guard)
  2. import { Injectable, CanActivate, ExecutionContext } from '@nestjs/common';
  3. import { Reflector } from '@nestjs/core';
  4. @Injectable()
  5. export class RolesGuard implements CanActivate {
  6. constructor(private reflector: Reflector) {}
  7. canActivate(context: ExecutionContext): boolean {
  8. const requiredRoles = this.reflector.getAllAndOverride<Role[]>(ROLES_KEY, [
  9. context.getHandler(),
  10. context.getClass(),
  11. ]);
  12. if (!requiredRoles) {
  13. return true;
  14. }
  15. const { user } = context.switchToHttp().getRequest();
  16. return requiredRoles.some((role) => user.roles?.includes(role));
  17. }
  18. }
  19. @@switch
  20. import { Injectable, Dependencies } from '@nestjs/common';
  21. import { Reflector } from '@nestjs/core';
  22. @Injectable()
  23. @Dependencies(Reflector)
  24. export class RolesGuard {
  25. constructor(reflector) {
  26. this.reflector = reflector;
  27. }
  28. canActivate(context) {
  29. const requiredRoles = this.reflector.getAllAndOverride(ROLES_KEY, [
  30. context.getHandler(),
  31. context.getClass(),
  32. ]);
  33. if (!requiredRoles) {
  34. return true;
  35. }
  36. const { user } = context.switchToHttp().getRequest();
  37. return requiredRoles.some((role) => user.roles.includes(role));
  38. }
  39. }

info Hint Refer to the Reflection and metadata section of the Execution context chapter for more details on utilizing Reflector in a context-sensitive way.

warning Notice This example is named “basic“ as we only check for the presence of roles on the route handler level. In real-world applications, you may have endpoints/handlers that involve several operations, in which each of them requires a specific set of permissions. In this case, you’ll have to provide a mechanism to check roles somewhere within your business-logic, making it somewhat harder to maintain as there will be no centralized place that associates permissions with specific actions.

In this example, we assumed that request.user contains the user instance and allowed roles (under the roles property). In your app, you will probably make that association in your custom authentication guard - see authentication chapter for more details.

To make sure this example works, your User class must look as follows:

  1. class User {
  2. // ...other properties
  3. roles: Role[];
  4. }

Lastly, make sure to register the RolesGuard, for example, at the controller level, or globally:

  1. providers: [
  2. {
  3. provide: APP_GUARD,
  4. useClass: RolesGuard,
  5. },
  6. ],

When a user with insufficient privileges requests an endpoint, Nest automatically returns the following response:

  1. {
  2. "statusCode": 403,
  3. "message": "Forbidden resource",
  4. "error": "Forbidden"
  5. }

info Hint If you want to return a different error response, you should throw your own specific exception instead of returning a boolean value.

Claims-based authorization

When an identity is created it may be assigned one or more claims issued by a trusted party. A claim is a name-value pair that represents what the subject can do, not what the subject is.

To implement a Claims-based authorization in Nest, you can follow the same steps we have shown above in the RBAC section with one significant difference: instead of checking for specific roles, you should compare permissions. Every user would have a set of permissions assigned. Likewise, each resource/endpoint would define what permissions are required (for example, through a dedicated @RequirePermissions() decorator) to access them.

  1. @@filename(cats.controller)
  2. @Post()
  3. @RequirePermissions(Permission.CREATE_CAT)
  4. create(@Body() createCatDto: CreateCatDto) {
  5. this.catsService.create(createCatDto);
  6. }
  7. @@switch
  8. @Post()
  9. @RequirePermissions(Permission.CREATE_CAT)
  10. @Bind(Body())
  11. create(createCatDto) {
  12. this.catsService.create(createCatDto);
  13. }

info Hint In the example above, Permission (similar to Role we have shown in RBAC section) is a TypeScript enum that contains all the permissions available in your system.

Integrating CASL

CASL is an isomorphic authorization library which restricts what resources a given client is allowed to access. It’s designed to be incrementally adoptable and can easily scale between a simple claim based and fully featured subject and attribute based authorization.

To start, first install the @casl/ability package:

  1. $ npm i @casl/ability

info Hint In this example, we chose CASL, but you can use any other library like accesscontrol or acl, depending on your preferences and project needs.

Once the installation is complete, for the sake of illustrating the mechanics of CASL, we’ll define two entity classes: User and Article.

  1. class User {
  2. id: number;
  3. isAdmin: boolean;
  4. }

User class consists of two properties, id, which is a unique user identifier, and isAdmin, indicating whether a user has administrator privileges.

  1. class Article {
  2. id: number;
  3. isPublished: boolean;
  4. authorId: number;
  5. }

Article class has three properties, respectively id, isPublished, and authorId. id is a unique article identifier, isPublished indicates whether an article was already published or not, and authorId, which is an ID of a user who wrote the article.

Now let’s review and refine our requirements for this example:

  • Admins can manage (create/read/update/delete) all entities
  • Users have read-only access to everything
  • Users can update their articles (article.authorId === userId)
  • Articles that are published already cannot be removed (article.isPublished === true)

With this in mind, we can start off by creating an Action enum representing all possible actions that the users can perform with entities:

  1. export enum Action {
  2. Manage = 'manage',
  3. Create = 'create',
  4. Read = 'read',
  5. Update = 'update',
  6. Delete = 'delete',
  7. }

warning Notice manage is a special keyword in CASL which represents “any” action.

To encapsulate CASL library, let’s generate the CaslModule and CaslAbilityFactory now.

  1. $ nest g module casl
  2. $ nest g class casl/casl-ability.factory

With this in place, we can define the createForUser() method on the CaslAbilityFactory. This method will create the Ability object for a given user:

  1. type Subjects = InferSubjects<typeof Article | typeof User> | 'all';
  2. export type AppAbility = Ability<[Action, Subjects]>;
  3. @Injectable()
  4. export class CaslAbilityFactory {
  5. createForUser(user: User) {
  6. const { can, cannot, build } = new AbilityBuilder<
  7. Ability<[Action, Subjects]>
  8. >(Ability as AbilityClass<AppAbility>);
  9. if (user.isAdmin) {
  10. can(Action.Manage, 'all'); // read-write access to everything
  11. } else {
  12. can(Action.Read, 'all'); // read-only access to everything
  13. }
  14. can(Action.Update, Article, { authorId: user.id });
  15. cannot(Action.Delete, Article, { isPublished: true });
  16. return build({
  17. // Read https://casl.js.org/v5/en/guide/subject-type-detection#use-classes-as-subject-types for details
  18. detectSubjectType: item => item.constructor as ExtractSubjectType<Subjects>
  19. });
  20. }
  21. }

warning Notice all is a special keyword in CASL that represents “any subject”.

info Hint Ability, AbilityBuilder, AbilityClass, and ExtractSubjectType classes are exported from the @casl/ability package.

info Hint detectSubjectType option let CASL understand how to get subject type out of an object. For more information read CASL documentation for details.

In the example above, we created the Ability instance using the AbilityBuilder class. As you probably guessed, can and cannot accept the same arguments but has different meanings, can allows to do an action on the specified subject and cannot forbids. Both may accept up to 4 arguments. To learn more about these functions, visit the official CASL documentation.

Lastly, make sure to add the CaslAbilityFactory to the providers and exports arrays in the CaslModule module definition:

  1. import { Module } from '@nestjs/common';
  2. import { CaslAbilityFactory } from './casl-ability.factory';
  3. @Module({
  4. providers: [CaslAbilityFactory],
  5. exports: [CaslAbilityFactory],
  6. })
  7. export class CaslModule {}

With this in place, we can inject the CaslAbilityFactory to any class using standard constructor injection as long as the CaslModule is imported in the host context:

  1. constructor(private caslAbilityFactory: CaslAbilityFactory) {}

Then use it in a class as follows.

  1. const ability = this.caslAbilityFactory.createForUser(user);
  2. if (ability.can(Action.Read, 'all')) {
  3. // "user" has read access to everything
  4. }

info Hint Learn more about the Ability class in the official CASL documentation.

For example, let’s say we have a user who is not an admin. In this case, the user should be able to read articles, but creating new ones or removing the existing articles should be prohibited.

  1. const user = new User();
  2. user.isAdmin = false;
  3. const ability = this.caslAbilityFactory.createForUser(user);
  4. ability.can(Action.Read, Article); // true
  5. ability.can(Action.Delete, Article); // false
  6. ability.can(Action.Create, Article); // false

info Hint Although both Ability and AbilityBuilder classes provide can and cannot methods, they have different purposes and accept slightly different arguments.

Also, as we have specified in our requirements, the user should be able to update its articles:

  1. const user = new User();
  2. user.id = 1;
  3. const article = new Article();
  4. article.authorId = user.id;
  5. const ability = this.caslAbilityFactory.createForUser(user);
  6. ability.can(Action.Update, article); // true
  7. article.authorId = 2;
  8. ability.can(Action.Update, article); // false

As you can see, Ability instance allows us to check permissions in pretty readable way. Likewise, AbilityBuilder allows us to define permissions (and specify various conditions) in a similar fashion. To find more examples, visit the official documentation.

Advanced: Implementing a PoliciesGuard

In this section, we’ll demonstrate how to build a somewhat more sophisticated guard, which checks if a user meets specific authorization policies that can be configured on the method-level (you can extend it to respect policies configured on the class-level too). In this example, we are going to use the CASL package just for illustration purposes, but using this library is not required. Also, we will use the CaslAbilityFactory provider that we’ve created in the previous section.

First, let’s flesh out the requirements. The goal is to provide a mechanism that allows specifying policy checks per route handler. We will support both objects and functions (for simpler checks and for those who prefer more functional-style code).

Let’s start off by defining interfaces for policy handlers:

  1. import { AppAbility } from '../casl/casl-ability.factory';
  2. interface IPolicyHandler {
  3. handle(ability: AppAbility): boolean;
  4. }
  5. type PolicyHandlerCallback = (ability: AppAbility) => boolean;
  6. export type PolicyHandler = IPolicyHandler | PolicyHandlerCallback;

As mentioned above, we provided two possible ways of defining a policy handler, an object (instance of a class that implements the IPolicyHandler interface) and a function (which meets the PolicyHandlerCallback type).

With this in place, we can create a @CheckPolicies() decorator. This decorator allows specifying what policies have to be met to access specific resources.

  1. export const CHECK_POLICIES_KEY = 'check_policy';
  2. export const CheckPolicies = (...handlers: PolicyHandler[]) =>
  3. SetMetadata(CHECK_POLICIES_KEY, handlers);

Now let’s create a PoliciesGuard that will extract and execute all the policy handlers bound to a route handler.

  1. @Injectable()
  2. export class PoliciesGuard implements CanActivate {
  3. constructor(
  4. private reflector: Reflector,
  5. private caslAbilityFactory: CaslAbilityFactory,
  6. ) {}
  7. async canActivate(context: ExecutionContext): Promise<boolean> {
  8. const policyHandlers =
  9. this.reflector.get<PolicyHandler[]>(
  10. CHECK_POLICIES_KEY,
  11. context.getHandler(),
  12. ) || [];
  13. const { user } = context.switchToHttp().getRequest();
  14. const ability = this.caslAbilityFactory.createForUser(user);
  15. return policyHandlers.every((handler) =>
  16. this.execPolicyHandler(handler, ability),
  17. );
  18. }
  19. private execPolicyHandler(handler: PolicyHandler, ability: AppAbility) {
  20. if (typeof handler === 'function') {
  21. return handler(ability);
  22. }
  23. return handler.handle(ability);
  24. }
  25. }

info Hint In this example, we assumed that request.user contains the user instance. In your app, you will probably make that association in your custom authentication guard - see authentication chapter for more details.

Let’s break this example down. The policyHandlers is an array of handlers assigned to the method through the @CheckPolicies() decorator. Next, we use the CaslAbilityFactory#create method which constructs the Ability object, allowing us to verify whether a user has sufficient permissions to perform specific actions. We are passing this object to the policy handler which is either a function or an instance of a class that implements the IPolicyHandler, exposing the handle() method that returns a boolean. Lastly, we use the Array#every method to make sure that every handler returned true value.

Finally, to test this guard, bind it to any route handler, and register an inline policy handler (functional approach), as follows:

  1. @Get()
  2. @UseGuards(PoliciesGuard)
  3. @CheckPolicies((ability: AppAbility) => ability.can(Action.Read, Article))
  4. findAll() {
  5. return this.articlesService.findAll();
  6. }

Alternatively, we can define a class which implements the IPolicyHandler interface:

  1. export class ReadArticlePolicyHandler implements IPolicyHandler {
  2. handle(ability: AppAbility) {
  3. return ability.can(Action.Read, Article);
  4. }
  5. }

And use it as follows:

  1. @Get()
  2. @UseGuards(PoliciesGuard)
  3. @CheckPolicies(new ReadArticlePolicyHandler())
  4. findAll() {
  5. return this.articlesService.findAll();
  6. }

warning Notice Since we must instantiate the policy handler in-place using the new keyword, ReadArticlePolicyHandler class cannot use the Dependency Injection. This can be addressed with the ModuleRef#get method (read more here). Basically, instead of registering functions and instances through the @CheckPolicies() decorator, you must allow passing a Type<IPolicyHandler>. Then, inside your guard, you could retrieve an instance using a type reference: moduleRef.get(YOUR_HANDLER_TYPE) or even dynamically instantiate it using the ModuleRef#create method.