NestJS authentication guards #1305
-
|
I would like to know what is the way to handle role based protection for routes? For example I want to let only admin to be able to get list of users. I should just use nestjs guards to set roles with decorators and check it with auth guard? Or I only should set metadata and use auth middleware which will validate role? |
Beta Was this translation helpful? Give feedback.
Replies: 2 comments 1 reply
-
|
Hi @EliasGit117! I'm Dosu and I’m helping the orpc team. The standard and recommended way to handle role-based route protection in NestJS is to use custom decorators (like Example: // roles.decorator.ts
import { SetMetadata } from '@nestjs/common';
export const Roles = (...roles: string[]) => SetMetadata('roles', roles);
// roles.guard.ts
import { CanActivate, ExecutionContext, Injectable } from '@nestjs/common';
import { Reflector } from '@nestjs/core';
@Injectable()
export class RolesGuard implements CanActivate {
constructor(private reflector: Reflector) {}
canActivate(context: ExecutionContext): boolean {
const requiredRoles = this.reflector.getAllAndOverride<string[]>('roles', [
context.getHandler(),
context.getClass(),
]);
if (!requiredRoles) return true;
const { user } = context.switchToHttp().getRequest();
return requiredRoles.some((role) => user?.roles?.includes(role));
}
}Then, in your controller: @UseGuards(AuthGuard, RolesGuard)
@Roles('admin')
@Get('users')
findAllUsers() { ... }This pattern is widely used and supported in the NestJS ecosystem. You can also use middleware to set user context (e.g., from a JWT or session) before guards run, which is a common pattern in both NestJS and orpc. Middleware is great for authentication (setting If you are using orpc with NestJS, you can still use standard NestJS guards and decorators around your handlers, or you can implement RBAC in middleware by attaching user/role info to the context and checking it before the handler runs. Both approaches are valid, but using guards and decorators is the most idiomatic for NestJS projects, while middleware-based RBAC is more common in orpc-style codebases and can be more flexible for complex scenarios12. To reply, just mention @dosu. How did I do? Good | Irrelevant | Incorrect | Verbose | Hallucination | Report 🐛 | Other Footnotes |
Beta Was this translation helpful? Give feedback.
-
|
Shouldn't user data be i context of the request? |
Beta Was this translation helpful? Give feedback.
Hi @EliasGit117! I'm Dosu and I’m helping the orpc team.
The standard and recommended way to handle role-based route protection in NestJS is to use custom decorators (like
@Roles('admin')) together with guards (such as aRolesGuard). The decorator sets metadata on the route, and the guard reads this metadata to enforce access control. This approach is idiomatic, integrates well with NestJS features, and keeps your authorization logic clean and reusable.Example: