skip to content

Sign-In & Policies

Nest authenticates with Passport-backed guards or its own v12 authentication package, and authorizes with role metadata or policy classes. Interviewers probe the global guard and its public routes.

on this pageshow

explore

questions

15

In a NestJS app, how do you restrict a route to certain roles with a custom @Roles() decorator and a roles guard?

level: juniorimportance: must knowfreq 65%

answer

  1. metadata first, enforcement second
  2. createDecorator or SetMetadata
  3. guard compares with request.user
  4. a false return means Forbidden

basics

~20 s

Create a Roles decorator with Reflector.createDecorator() or SetMetadata(), put it on the handler, and write a CanActivate guard that reads it through Reflector and compares it with request.user's roles; a false return makes Nest answer 403.

solid answer

~40 s

A `Roles` decorator built with `Reflector.createDecorator<string[]>()`, or a wrapper around `SetMetadata('roles', roles)` from `@nestjs/common`, only attaches metadata; it enforces nothing. The enforcement is a `RolesGuard` implementing `CanActivate`: it injects `Reflector`, reads the roles required by the handler (with `getAllAndOverride`, the controller's as a fallback), takes the user that authentication put on `request.user`, and returns whether that user holds one of them. When `canActivate` returns `false`, Nest throws a `ForbiddenException`, so the client gets a 403 with `"Forbidden resource"`. Two traps: the docs' sample returns `true` when a route has no `@Roles()`, so a forgotten decorator leaves the route open, and the guard assumes `request.user` is already set, so it must run after the authentication guard.

code

typescript · 22 lines
typescript
import { CanActivate, ExecutionContext, Injectable, UnauthorizedException } from '@nestjs/common';
import { Reflector } from '@nestjs/core';

export const Roles = Reflector.createDecorator<string[]>();

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

  canActivate(context: ExecutionContext): boolean {
    // The method's @Roles() wins; the controller's applies when the method has none.
    const required = this.reflector.getAllAndOverride(Roles, [context.getHandler(), context.getClass()]);
    if (!required) {
      return true; // no @Roles(): this guard does not restrict the route
    }
    const { user } = context.switchToHttp().getRequest();
    if (!user) {
      throw new UnauthorizedException(); // not signed in: 401, not 403
    }
    return required.some((role) => user.roles.includes(role)); // false: Nest answers 403
  }
}

go deeper

for a junior

Recall the two pieces: a decorator that only stores the required roles, and a CanActivate guard that reads them and compares them with request.user. Know that returning false gives a 403.

for a middle

Explain how the guard reads metadata from the handler and the class, why getAllAndOverride matters for controller defaults, and when to throw UnauthorizedException instead of returning false.

for a senior

Point out the fail-open default of the sample guard and the dependency on authentication having run first, and say how you would catch a forgotten decorator before production.

for a principal

Frame roles as a coarse, route-level tool: decide where a team needs record-level rules and a deny-by-default convention, and whether a hand-written guard still carries that weight.

## Two pieces: metadata and a guard In NestJS, restricting a route to certain roles takes two separate pieces. A **decorator** records which roles the route requires, as metadata on the handler or on the controller class. A **guard**, a class implementing `CanActivate`, reads that metadata on every request and decides whether the handler runs. The decorator on its own enforces nothing: a `@Roles(['admin'])` that no guard reads is a comment. The guard needs a third input that it does not produce itself: the **current user**. By convention the authentication step (a Passport guard, the first-party authentication package, or your own middleware) attaches the signed-in user to `request.user`, roles included. The roles guard only compares. ## Defining the decorator Nest offers two ways to attach the metadata: | Approach | Declaration | Usage | Read back with | |---|---|---|---| | `Reflector.createDecorator` from `@nestjs/core` | `Reflector.createDecorator<string[]>()` | `@Roles(['staff', 'admin'])`, one typed argument | `reflector.get(Roles, target)` | | `SetMetadata` from `@nestjs/common` | `(...roles: string[]) => SetMetadata('roles', roles)` | `@Roles('staff', 'admin')`, any arguments you design | `reflector.get('roles', target)` | - With `Reflector.createDecorator()`, the decorator object itself is the metadata key, and its type parameter types both the argument and the value the guard reads back. - With `SetMetadata`, you choose the key and the value, so a decorator can take several arguments. The docs advise wrapping it in your own decorator rather than writing `@SetMetadata('roles', [...])` on routes. ## Writing the guard A roles guard does four things on each request: 1. Injects `Reflector` and reads the required roles for the route: from the handler (`context.getHandler()`) and, for a controller-wide default, from the class (`context.getClass()`). 2. Returns `true` when the route declares no roles, if that is the rule you choose (the docs' sample does exactly this). 3. Reads the user from `context.switchToHttp().getRequest().user`. 4. Returns whether the user holds a required role. The matching rule (any role, all roles, a hierarchy) is yours: the docs call theirs `matchRoles()` and point out that Nest does not provide it. `reflector.get(Roles, context.getHandler())` reads the method only, so a class-level `@Roles()` is invisible to it. To let the controller set a default that a method overrides, read both targets with `getAllAndOverride`, which returns the first defined value in the order you pass the targets. The `Reflector` methods themselves belong with guards in general; here they are simply how the roles guard reads its input. ## What the client sees When `canActivate()` returns `false`, Nest throws a `ForbiddenException`, and the default exception handling sends: ```json { "statusCode": 403, "message": "Forbidden resource", "error": "Forbidden" } ``` To answer differently, throw an exception from the guard yourself. The usual case is a request with no user at all: that caller is not forbidden, they are not signed in, so `throw new UnauthorizedException()` (a 401) is the more accurate answer. Anything a guard throws goes through the exception filters like any other error. ## Binding it, and the traps The guard runs only where it is bound: `@UseGuards(RolesGuard)` on a controller or a method, or globally as an `APP_GUARD` provider. The binding mechanics are general guard material; for roles, these are the traps interviewers probe: - **Open by default.** The docs' sample returns `true` when a route has no `@Roles()`, so a forgotten decorator leaves the route open to everyone who got past authentication. If that is not acceptable, invert the rule: deny when no roles are declared, and mark open routes explicitly. - **No user yet.** The guard assumes `request.user` is already set. If it runs before authentication, the docs' sample reads `user.roles` on `undefined`, throws a `TypeError`, and the caller gets a 500; a version written with optional chaining denies everyone with a 403 instead. Either way the fix is guard order, not more code in the roles guard. - **Handler-only reads.** `reflector.get()` on the handler never sees a class-level `@Roles()`. - **Roles are coarse.** A roles guard answers "may staff call this route?". It cannot answer "may this customer see this particular order?", which depends on the record; that check belongs in the code that loads the order. The NestJS 12 docs point to a policy package for per-record rules and a deny-by-default stance, but the hand-written roles guard remains the building block interviewers expect a candidate to write from memory.

  • When would you build the roles decorator with SetMetadata instead of Reflector.createDecorator?
    `Reflector.createDecorator()` gives one typed argument and hides the key. `SetMetadata('roles', roles)` from `@nestjs/common` lets you pick the key and the value, so a wrapper like `(...roles: string[]) => SetMetadata('roles', roles)` can take several arguments, as in `@Roles('staff', 'admin')`. The guard then reads it with `reflector.get('roles', context.getHandler())`. The docs recommend wrapping `SetMetadata` in your own decorator rather than calling it on routes directly.
  • Why throw UnauthorizedException from the roles guard instead of returning false when request.user is missing?
    Returning `false` always produces a `ForbiddenException`, a 403, which tells the client that the answer is no for them. A caller without a user has not been identified at all, so a 401 telling them to authenticate is more accurate. Throwing `UnauthorizedException` from `canActivate` sends it through the exception filters like any other error. Ideally the authentication guard has already rejected such a request before the roles guard runs.
  • How would you make a route with no @Roles() denied rather than open?
    Change the guard's branch for missing metadata: instead of `return true`, return `false` (or throw), and add an explicit marker for routes everyone may call, read the same way through `Reflector`. That turns a forgotten decorator into a 403 found in testing instead of an open route found in production. The cost is that every route, including health checks, must now declare something.

  • The @Roles() decorator by itself blocks callers who lack the role.
  • A guard that returns false makes Nest answer 401 Unauthorized.
  • The docs' RolesGuard denies a route that has no @Roles() metadata.
  • reflector.get() on the handler also picks up roles set on the controller.
  • Nest ships a matchRoles() helper that compares required and granted roles.
  • A roles guard can safely run before the authentication guard.
open as a page

In a NestJS app using @nestjs/passport, what should a PassportStrategy subclass's validate() return, and where does that value end up?

level: juniorimportance: must knowfreq 70%

basics

~10 s

validate() should return the authenticated user, which AuthGuard assigns to req.user before the handler runs. Returning null or false fails authentication with a 401; a thrown exception goes to Nest's exception layer instead.

open as a page

In a NestJS 12 app, why must the authentication guard run before a roles or policy guard, and what decides which global guard runs first?

level: middleimportance: must knowfreq 50%

basics

~20 s

Role and policy guards read the user that authentication puts on request.user, so run first they see nobody. Global guards precede controller and route guards; singleton APP_GUARD providers run in module-scan order, before app.useGlobalGuards() ones.

open as a page

In a NestJS app, how do you register a JwtAuthGuard extending AuthGuard('jwt') globally and still let routes marked @Public() through?

level: middleimportance: must knowfreq 62%

basics

~10 s

Provide the guard under the APP_GUARD token, mark open routes with a @Public() decorator built on SetMetadata, and override canActivate() to read that flag with Reflector, returning true before calling super.canActivate().

open as a page

In a NestJS 12 app importing AuthenticationModule from @nestjs/authentication, why does a new health-check route answer 401, and how do you open it?

level: juniorimportance: should knowfreq 30%

basics

~20 s

AuthenticationModule.forRoot() registers AuthenticationGuard as a global guard by default, so every route needs a signed-in user and anonymous calls get 401. Marking the health route @Public() makes the guard skip it: no credential provider runs.

open as a page

With NestJS 12's @nestjs/authentication, how does a credential provider join the global guard's chain, and which provider authenticates a request?

level: middleimportance: should knowfreq 25%

basics

~20 s

A credential provider is a singleton @Injectable() that calls registerProvider(this) on the injected AuthenticationRegistry in its constructor. The guard tries providers in ascending order; the first to return a user wins, and null passes to the next.

open as a page

In a NestJS 12 app using @nestjs/authorization, how do @Policy() classes, @Can() and authorize() split an orders API's checks?

level: middleimportance: should knowfreq 25%

basics

~20 s

A @Policy() class holds abilities, methods taking the user that return true to allow. @Can() checks an ability in the global guard before the handler, for rules needing no record; authorize() checks it in the service after loading the order.

open as a page

With @nestjs/jwt in a NestJS app, how do JwtModule.register() and registerAsync() differ, and where does JwtService.sign() get its secret and expiry?

level: middleimportance: should knowfreq 45%

basics

~20 s

register() takes a fixed options object; registerAsync() builds it in a factory that can inject ConfigService. JwtService.sign() merges the module's signOptions, such as expiresIn, with per-call options and uses the module secret unless the call overrides it.

open as a page

In a NestJS 12 app on @nestjs/authentication, a credential provider's database lookup times out. What does the client receive, and why not 401?

level: seniorimportance: should knowfreq 18%

basics

~20 s

The guard catches only AuthenticationError; any other error from a provider is rethrown, so Nest answers 500 Internal server error. A 401 would wrongly tell clients their credentials are bad, prompting sign-outs and refresh storms during an outage.

open as a page

A NestJS 12 app on @nestjs/authentication signs every customer out on each deploy. What is missing, and what must its replacement session store guarantee?

level: seniorimportance: should knowfreq 20%

basics

~20 s

No SessionStore is registered, so sessions live in the in-memory default; the startup check only refuses that when NODE_ENV is production. Register a store with AuthenticationStorage.registerSource(), whose touchSession() is a conditional update and deleteSession() reports its row count.

open as a page

In a NestJS 12 app using @nestjs/authorization, why does one route answer a guest 401 and a customer 403, and why does a new unannotated route deny everyone?

level: seniorimportance: should knowfreq 22%

basics

~20 s

A guest reaches policies as a null user, so a denial is a 401 (signing in might change it); a signed-in user's denial is a 403. The global AuthorizationGuard denies every handler that declares no @Can(), @Can.Anyone() or @Public().

open as a page

In a NestJS app, how does a guard extending AuthGuard('jwt') end up sending 401, 403 or 500, and where do you customise that failure?

level: seniorimportance: should knowfreq 40%

basics

~20 s

Token problems and a validate() that returns null reach handleRequest() with no user and become UnauthorizedException, a 401. An exception thrown in validate() is rethrown unchanged, so ForbiddenException gives 403 and a plain Error gives 500.

open as a page

In NestJS 12's AuthenticationModule.forRoot(), why is session: { idleTtl: 3600 } a bug, and what else does the module reject at startup?

level: middleimportance: nice to knowfreq 15%

basics

~20 s

AuthenticationModule.forRoot() reads numeric lifetimes as milliseconds, so idleTtl: 3600 is 3.6 seconds: the module warns, then refuses to start because the one-minute touchInterval is not shorter. Unknown keys and features missing handlers also fail startup.

open as a page

Why would every route behind AuthGuard('jwt') in a NestJS app return 500 and log Unknown authentication strategy "jwt" after a refactor?

level: seniorimportance: nice to knowfreq 25%

basics

~20 s

Passport has no strategy registered as 'jwt' because the JwtStrategy instance was never created: it left the providers, its module is not imported, it was renamed, or it became request-scoped. Passport's plain Error reaches Nest as a 500.

open as a page

Your NestJS 12 services each hand-roll a @Roles() guard; would you standardise on @nestjs/authorization's deny-by-default policies, and what would the switch cost the team?

level: principalimportance: nice to knowfreq 12%

basics

~20 s

Adopt it where record-level rules and a closed-by-default stance matter: a forgotten @Can() closes a route instead of opening it. The cost is a declaration on every handler, strict guard ordering, singleton policies and a new dependency to track.

open as a page