Learn NestJS · 8/14

Advanced Security: Authorization

8 min read

🛡️ Advanced Security: Authorization in NestJS

Welcome back! So, you've mastered authentication. Your users can log in and prove who they are. Great! But now comes the next big question: now that they're inside the building, which rooms are they allowed to enter? This is the core of Authorization.

Authorization isn't about who a user is (that's authentication), but about what they are allowed to do. For example, an admin can delete users, but a regular user definitely shouldn't have that power.

This guide will walk you through three critical pillars of authorization in a modern NestJS application. We'll keep it practical, focusing on the tools and techniques you'll use daily in the industry.

1. Role-Based Access Control (RBAC) Concepts 🎭

The Problem: Imagine you're building a content management system. You have different types of users:

  • Admins: Can do anything, including deleting content and managing users.
  • Editors: Can create and edit content.
  • Viewers: Can only read content.

How do you enforce these rules? You could sprinkle if (user.role === 'admin') checks all over your code. This works for a tiny app, but it quickly becomes a tangled, unmanageable mess. If you need to add a new role, like Moderator, you'd have to hunt down every single if statement. That's a recipe for bugs and sleepless nights. 😩

The Solution: Role-Based Access Control (RBAC)

RBAC is a straightforward and powerful strategy for managing permissions. Instead of assigning permissions to individual users, you assign permissions to roles, and then assign those roles to users.

  • User: The person using your app.
  • Role: A named group of permissions (e.g., 'Admin', 'Editor').
  • Permission: A specific action that can be performed (e.g., create-post, delete-user).

This decouples your users from the specific permissions. Need to change what an 'Editor' can do? You only change it in one place: the role definition. It's clean, scalable, and the industry-standard approach for most applications.

Funny exaggeration: Trying to manage permissions without RBAC is like being a bouncer at a massive party and having to remember every single guest's name and whether they're allowed in the VIP section. With RBAC, you just give VIPs a gold wristband. Problem solved. wristband. Problem solved. ✨

2. Implementing Role Guards and Custom Metadata 👮

The Problem: We understand the concept of RBAC, but how do we actually make it work in NestJS? How do we protect a specific API endpoint, like DELETE /posts/:id, and ensure only a user with the 'Admin' role can execute it?

The Solution: We'll use a powerful duo: Guards and Custom Metadata.

Think of it like this:

  • Metadata: A label or a "sticky note" you put on your route handler. It says, "Hey, only users with the 'Admin' role should be allowed here."
  • Guard: A bouncer that stands in front of your route. It reads the "sticky note" (metadata) and then checks the incoming user's credentials to see if they have the required role.

Let's build it. The process is always the same: create the decorator, then create the guard that uses it.

Step 1: Create a @Roles() Decorator (The Sticky Note)

A decorator in NestJS is a function that adds metadata to a class or method. We'll create a @Roles() decorator to specify which roles are required for an endpoint.

typescript
// src/auth/decorators/roles.decorator.ts

import { SetMetadata } from '@nestjs/common';

export enum Role {
  User = 'user',
  Admin = 'admin',
}

export const ROLES_KEY = 'roles';
export const Roles = (...roles: Role[]) => SetMetadata(ROLES_KEY, roles);
  • We define an enum for our roles. This is great practice to avoid typos like 'admin' vs 'Admin'.
  • SetMetadata(key, value) is the core NestJS function that attaches our metadata. We're creating a decorator called Roles that takes an array of role names and attaches them to the route with the key 'roles'.

Step 2: Create the RolesGuard (The Bouncer)

A Guard is a class that implements the CanActivate interface. This interface requires a single method, canActivate(), which must return a boolean (or a Promise/Observable that resolves to a boolean). If it returns true, the request proceeds; if false, NestJS blocks it with a 403 Forbidden error.

typescript
// src/auth/guards/roles.guard.ts

import { Injectable, CanActivate, ExecutionContext } from '@nestjs/common';
import { Reflector } from '@nestjs/core';
import { ROLES_KEY, Role } from '../decorators/roles.decorator';

@Injectable()
export class RolesGuard implements CanActivate {
  constructor(private reflector: Reflector) {}

  canActivate(context: ExecutionContext): boolean {
    // Get the required roles from the @Roles() decorator
    const requiredRoles = this.reflector.getAllAndOverride<Role[]>(ROLES_KEY, [
      context.getHandler(),
      context.getClass(),
    ]);

    if (!requiredRoles) {
      // If no roles are required, allow access
      return true;
    }

    // Get the user object from the request
    // This assumes you have an authentication guard that runs before this guard
    // and attaches the user to the request.
    const { user } = context.switchToHttp().getRequest();

    // Check if the user's roles include any of the required roles
    return requiredRoles.some((role) => user.roles?.includes(role));
  }
}
  • We inject Reflector, a helper class that lets us read the metadata we set earlier.
  • reflector.getAllAndOverride() looks for metadata with the key 'roles' on both the route handler and the controller class.
  • We then grab the user object from the request (which should have been attached by your authentication guard, e.g., AuthGuard).
  • The final line is the magic: it checks if the user has at least one of the required roles.

Step 3: Put It All Together

Now, protecting an endpoint is beautifully simple and declarative.

typescript
// src/users/users.controller.ts

import { Controller, Get, Post, Delete, UseGuards } from '@nestjs/common';
import { AuthGuard } from 'src/auth/guards/auth.guard'; // Assuming you have this
import { RolesGuard } from 'src/auth/guards/roles.guard';
import { Roles, Role } from 'src/auth/decorators/roles.decorator';

@Controller('users')
@UseGuards(AuthGuard, RolesGuard) // Apply guards to the entire controller
export class UsersController {
  
  @Get()
  findAll() {
    // This route can be accessed by any authenticated user.
    return 'This action returns all users';
  }

  @Delete(':id')
  @Roles(Role.Admin) // ONLY users with the 'Admin' role can access this.
  deleteUser() {
    return 'This action deletes a user';
  }
}

Look how clean that is! The business logic in deleteUser() doesn't need to know anything about roles. All the authorization logic is handled cleanly by the decorators and the guard.

3. Securing Passwords with Hashing (Bcrypt) 🤫

The Problem: Your user signs up with the password "MySuperSecretPa $$w0rd". Where do you store it in your database? If you store it as plain text and your database is ever compromised, you have just handed every user's password to an attacker on a silver platter. This is a catastrophic, company-ending mistake.

The Solution: Hashing

Hashing is a one-way process that turns a string of any length into a unique, fixed-length string called a hash. You can't reverse the process to get the original password back.

But not all hashing is equal. A simple SHA256 hash isn't enough. Attackers use "rainbow tables" (massive pre-computed lists of hashes for common passwords) to crack them instantly.

Enter Bcrypt: The Industry Standard for Passwords

Bcrypt is an algorithm built specifically for hashing passwords. It has two secret weapons:

  1. Salting: Before hashing, bcrypt adds a unique, random string (a "salt") to each password. This means that even if two users have the same password, their stored hashes will be completely different, making rainbow tables useless.
  2. Cost Factor: Bcrypt is intentionally slow. You can configure a "cost factor" (or number of rounds) to make it take longer to compute a hash. This is a feature, not a bug! If it takes your server 100ms to hash one password, it will take an attacker's powerful machine years to brute-force billions of possibilities.

Fact: The "bcrypt" name comes from the Blowfish encryption cipher it's based on, and it was first presented at a USENIX conference way back in 1999. It's stood the test of time.

Implementation in NestJS

First, install the necessary package and its TypeScript types.

bash
npm install bcrypt @types/bcrypt

Hashing a Password (on Signup)

When a user creates an account, you hash their password before saving it.

typescript
// src/users/users.service.ts
import * as bcrypt from 'bcrypt';

async function createUser(createUserDto: CreateUserDto) {
  const saltOrRounds = 10; // The cost factor
  const hashedPassword = await bcrypt.hash(createUserDto.password, saltOrRounds);
  
  // Now, save the user to the database with the hashedPassword
  const newUser = this.userRepository.create({
    ...createUserDto,
    password: hashedPassword,
  });
  
  await this.userRepository.save(newUser);
  // ...
}

Comparing a Password (on Login)

When a user tries to log in, you never hash their input and compare the hashes. Instead, you use bcrypt's safe comparison function.

typescript
// src/auth/auth.service.ts
import * as bcrypt from 'bcrypt';

async function validateUser(email: string, pass: string): Promise<any> {
  const user = await this.usersService.findOne(email);
  if (user) {
    const isMatch = await bcrypt.compare(pass, user.password);
    if (isMatch) {
      // Passwords match, return the user object (without the password hash)
      const { password, ...result } = user;
      return result;
    }
  }
  return null;
}

bcrypt.compare() is incredibly smart. It takes the plain-text password from the login attempt and the full hash from your database (which includes the original salt) and securely checks for a match without ever needing to decrypt anything.


📚 Further Reading & Resources

Challenge

You are tasked with implementing a Role-Based Access Control (RBAC) system for a secure NestJS application. Your goal is to create a RolesGuard and a corresponding @Roles decorator to protect a specific controller endpoint.

Requirements:

  1. Create a @Roles Decorator:

    • This decorator should accept a variable number of Role enum values.
    • It must use SetMetadata to attach the provided roles to the endpoint under the metadata key 'roles'.
  2. Implement the RolesGuard:

    • The guard must implement the CanActivate interface.
    • Inject the Reflector service to read metadata.
    • Inside the canActivate method, retrieve the required roles metadata attached by your @Roles decorator using the 'roles' key.
    • Extract the user object from the incoming request. Assume the user object is already attached to the request by a preceding authentication guard and has a property roles which is an array of Role enum values (e.g., user.roles = [Role.Admin]).
    • Implement the logic to check if the user's roles include at least one of the required roles. The method should return true to grant access if a match is found, and false to deny access otherwise.
  3. Apply to the Controller:

    • In the provided AdminController, protect the getAdminData method by applying your RolesGuard using the @UseGuards decorator.
    • Use your @Roles decorator on the same method to specify that only users with the Role.Admin role are allowed.

Expected result

The final code should correctly implement and apply a custom @Roles decorator and a RolesGuard.

@Roles Decorator

The Roles decorator should be a one-line function that uses SetMetadata to attach an array of roles under the key 'roles'.

typescript
export const Roles = (...roles: Role[]) => SetMetadata('roles', roles);

RolesGuard Implementation

The canActivate method within RolesGuard should contain the following logic:

  1. Use reflector.getAllAndOverride<Role[]>() to retrieve the roles metadata associated with the 'roles' key from the handler and the class.
  2. If no roles are required for the endpoint, the guard should grant access by returning true.
  3. Access the request object via context.switchToHttp().getRequest().
  4. Retrieve the user object from the request.
  5. Check if user.roles contains at least one of the requiredRoles using a method like some().
typescript
@Injectable()
export class RolesGuard implements CanActivate {
  constructor(private reflector: Reflector) {}

  canActivate(context: ExecutionContext): boolean {
    const requiredRoles = this.reflector.getAllAndOverride<Role[]>('roles', [
      context.getHandler(),
      context.getClass(),
    ]);
    if (!requiredRoles) {
      return true;
    }
    const { user } = context.switchToHttp().getRequest();
    return requiredRoles.some((role) => user.roles?.includes(role));
  }
}

AdminController Application

The getAdminData method should be decorated with @UseGuards(RolesGuard) to apply the guard, and @Roles(Role.Admin) to restrict access to administrators only.

typescript
@Controller('admin')
export class AdminController {
  @Get()
  @UseGuards(RolesGuard)
  @Roles(Role.Admin)
  getAdminData() {
    return { message: 'This is secure admin data.' };
  }
}
typescript

Solve the challenge, then check it.

Ctrl+Enter

Course complete!

You've passed every challenge in this course.