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.
// 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
enumfor 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 calledRolesthat 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.
// 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
userobject 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.
// 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:
- 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.
- 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.
npm install bcrypt @types/bcryptHashing a Password (on Signup)
When a user creates an account, you hash their password before saving it.
// 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.
// 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
- Official NestJS Documentation on Authorization: https://docs.nestjs.com/security/authorization
- Official NestJS Documentation on Guards: https://docs.nestjs.com/guards
- bcrypt NPM Package: https://www.npmjs.com/package/bcrypt
- An article on why password hashing is critical: https://www.freecodecamp.org/news/how-to-hash-passwords-with-bcrypt-in-nodejs/
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:
Create a
@RolesDecorator:- This decorator should accept a variable number of
Roleenum values. - It must use
SetMetadatato attach the provided roles to the endpoint under the metadata key'roles'.
- This decorator should accept a variable number of
Implement the
RolesGuard:- The guard must implement the
CanActivateinterface. - Inject the
Reflectorservice to read metadata. - Inside the
canActivatemethod, retrieve the required roles metadata attached by your@Rolesdecorator using the'roles'key. - Extract the
userobject from the incomingrequest. Assume the user object is already attached to the request by a preceding authentication guard and has a propertyroleswhich is an array ofRoleenum 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
trueto grant access if a match is found, andfalseto deny access otherwise.
- The guard must implement the
Apply to the Controller:
- In the provided
AdminController, protect thegetAdminDatamethod by applying yourRolesGuardusing the@UseGuardsdecorator. - Use your
@Rolesdecorator on the same method to specify that only users with theRole.Adminrole are allowed.
- In the provided
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'.
export const Roles = (...roles: Role[]) => SetMetadata('roles', roles);RolesGuard Implementation
The canActivate method within RolesGuard should contain the following logic:
- Use
reflector.getAllAndOverride<Role[]>()to retrieve the roles metadata associated with the'roles'key from the handler and the class. - If no roles are required for the endpoint, the guard should grant access by returning
true. - Access the
requestobject viacontext.switchToHttp().getRequest(). - Retrieve the
userobject from the request. - Check if
user.rolescontains at least one of therequiredRolesusing a method likesome().
@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.
@Controller('admin')
export class AdminController {
@Get()
@UseGuards(RolesGuard)
@Roles(Role.Admin)
getAdminData() {
return { message: 'This is secure admin data.' };
}
}