Guards and Roles
Utilize NestJS Guards to protect routes and implement role-based access control (RBAC) to manage user permissions.
What are NestJS Guards?
In NestJS, Guards are special classes that decide if a given request should be processed by the route handler. Think of them as gatekeepers!
They sit between the incoming request and your application's logic, making authorization decisions.
- Authorization: Who is allowed to do what?
- Authentication: Who is this user? (Often handled before guards, but guards can confirm it).
Building a Basic Guard
All NestJS Guards must implement the CanActivate interface. This interface requires a single method: canActivate().
The canActivate() method returns a boolean, a Promise<boolean>, or an Observable<boolean>. If it returns true, the request proceeds; if false, it's blocked.
import { CanActivate, ExecutionContext, Injectable } from '@nestjs/common';
import { Observable } from 'rxjs';
@Injectable()
export class AuthGuard implements CanActivate {
canActivate(
context: ExecutionContext,
): boolean | Promise<boolean> | Observable<boolean> {
// Logic to determine if user is authorized
// For now, let's just allow it
return true;
}
}