skip to content

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%

answer

  1. sign in might change it
  2. null user means guest
  3. reason: unauthenticated or forbidden
  4. nothing declared, nothing allowed
  5. the startup log lists them

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().

solid answer

~40 s

In NestJS 12 with `@nestjs/authorization` and the first-party authentication package, a guest reaches a policy only where authentication is optional or public; elsewhere authentication itself answers 401 first. The policy sees the guest as `null`, and a denial is classified by reason: `unauthenticated` (401, `UnauthorizedException`) when there is no user, `forbidden` (403, `ForbiddenException`) when there is one. `authorize()` throws an `AuthorizationError` that the module maps to those exceptions when it leaves a handler; thrown from your own guard or middleware it becomes a 500. The global `AuthorizationGuard` is deny-by-default: a handler with no `@Can()`, `@Can.Anyone()` or `@Public()` is refused, 403 for a user and 401 for a guest, and the module logs every such handler at startup. Response bodies never name the ability, so audit through `AuthorizationEvents`.

code

plaintext · 8 lines
plaintext
GET /orders/7                      (no token; the route requires sign-in)
HTTP/1.1 401 Unauthorized
WWW-Authenticate: Bearer realm="store"
{"message":"Unauthorized","statusCode":401}

GET /orders/7                      (a customer who does not own order 7)
HTTP/1.1 403 Forbidden
{"message":"Forbidden","statusCode":403}

go deeper

for a junior

Recall the two statuses: 401 means identify yourself, 403 means this identified user may not. Know that the package denies a route that declares nothing.

for a middle

Explain how the guest arrives as null, how the reason picks 401 or 403, and why authentication rather than authorization rejects a guest on a sign-in-required route.

for a senior

Diagnose the production cases: an undeclared route found through the startup log, an AuthorizationError in your own guard becoming a 500, and auditing denials through AuthorizationEvents.

for a principal

Decide team rules around these statuses: when a 404 should hide a forbidden record, and how denial events feed audit logging without logging whole users.

## Who decides that a caller is a guest In a NestJS 12 app using the first-party pair of packages, two global guards share every request. The **authentication** guard decides whether the route needs a signed-in user at all. By default it does, and a request without a valid credential is rejected with a **401** and a `WWW-Authenticate` challenge before any policy runs. Only where authentication is relaxed, with `@Authenticate({ optional: true })` or `@Public()`, does a guest reach the **authorization** guard, which then evaluates policies with a `null` user. The authorization guard reads the user through its `getUser` option, which defaults to `defaultGetUser`: `request.user` over HTTP. `null`, `undefined` and `false` all mean a guest. ## Why a denial is 401 for one caller and 403 for another When an ability or a `before()` hook refuses, `@nestjs/authorization` records a **reason**: | Caller | Reason | Status | HTTP exception | |---|---|---|---| | no user (guest) | `unauthenticated` | 401 | `UnauthorizedException` | | signed-in user | `forbidden` | 403 | `ForbiddenException` | The rationale is the status semantics: a 401 says "sign in and try again", because signing in might change the answer, while a 403 says the answer for this user is no. So a customer's order viewed by a guest on an optional-authentication route is a 401, and the same order viewed by another customer is a 403. How the error travels depends on where the check ran: - A `@Can()` denial is thrown by the guard as the transport's own exception. - `authorize()` in a service throws an `AuthorizationError` with `reason`, `status`, `policy` and `ability`. It is deliberately **not** an HTTP exception, because the same service also runs in queue workers and gateways. When it leaves a handler, `AuthorizationModule` turns it into the same `UnauthorizedException` or `ForbiddenException` the guard throws (a `WsException` or `RpcException` on those transports). - An `AuthorizationError` thrown **outside** a handler, from your own guard or middleware, is not converted and becomes a **500**. There, call `can()` and throw the exception you want. - `can()` never throws; it resolves to `false` for guests and forbidden users alike. One guard rail is worth knowing. If an ability typed `User` rather than `User | null` dereferences a guest's `null` user and throws a `TypeError` that mentions `null`, the evaluator treats it as a denial with reason `unauthenticated` and logs a warning once, so the typing slip fails closed with a 401 instead of a 500. Any other error, and any error for a signed-in user, propagates as a real failure. ## Why an unannotated route denies everyone `AuthorizationModule.forRoot()` registers `AuthorizationGuard` globally (unless `globalGuard: false`), and the guard is **deny-by-default**. It decides by what the handler and its class declare: | Declaration | Outcome | |---|---| | `@Can(Policy, 'ability')` | every requirement, class first, then method, must pass | | `@Can.Anyone()` | anyone authentication let through | | `@Public()` from `@nestjs/authentication` | treated like `@Can.Anyone()` | | nothing | denied: 403 for a user, 401 for a guest | So a new route whose author forgot `@Can()` is **closed, not open**. The denial carries an `AuthorizationError` whose `policy` and `ability` are both `null`. At startup the module also logs, at error level, every handler it will deny this way, by class and method name, suggesting `@Can()` or `@Can.Anyone()`. That log is the first place to look when a fresh route returns 403 to staff and admins alike. Deny-by-default holds only where the guard runs. Where Nest runs no global guard, nothing is enforced and nothing is denied: GraphQL field resolvers without `fieldResolverEnhancers: ['guards']`, and the message handlers of a hybrid app connected without `inheritAppConfig: true`. ## Diagnosing a denial in production - The response body says only `Unauthorized` or `Forbidden`; it never names the policy or the ability. - `AuthorizationEvents` exposes every denial on its `events$` observable and on the `nestjs:authorization:denied` diagnostics channel, as a `denied` event with `policy`, `ability`, `reason`, `user`, `args` and, for `@Can()`, the `handler`. A `can()` that resolves to `false` is not a denial and emits nothing. - A 403 confirms that the record exists. Where ids are guessable and existence is sensitive, check with `can()` and throw `NotFoundException` instead. - A 401 for a signed-in user on a `@Can()` route usually means the authorization guard ran before authentication: a guard-order problem, not a policy one.

  • A staff member gets a 403 on a brand-new export route even though the policy would allow it; where do you look first?
    At the route's declarations and the startup log. If the handler carries no `@Can()`, `@Can.Anyone()` or `@Public()`, the guard denies it whatever the policy says, and the authorization module logged it at startup as a handler it denies every call to. Add the right `@Can()` requirement rather than `@Can.Anyone()` unless the service checks.
  • Your own guard calls authorize() and production shows 500s instead of 403s; why?
    `AuthorizationError` is not an HTTP exception. `AuthorizationModule` converts it only when it leaves a handler; guards and middleware run before that, so the error reaches Nest's exception handling unconverted and becomes a 500. In a guard, call `can()` and throw `ForbiddenException` or `UnauthorizedException` yourself.
  • Why is a guest's denial on an optional-authentication route a 401 and not a 403?
    Authorization never decides whether a route needs a user; that is authentication's job. When a policy refuses a `null` user, the package answers 401 because signing in might change the answer, whereas a 403 states that this identified user may not. The same check returns 403 once a signed-in user fails it.

At a members' club, a visitor with no card is told to show one and come back (401), while a member whose card lacks the right tier is told no (403). A room whose door carries no sign stays locked to everyone until someone puts one up.

  • A policy denial is always a 403, whoever the caller is.
  • A route without @Can() is open, because nothing restricts it.
  • AuthorizationError extends HttpException, so it maps to 403 everywhere.
  • The 403 body names the policy and ability that refused the caller.
  • can() resolving to false emits a denied event for auditing.

Assumes NestJS 12, whose security docs teach the first-party @nestjs/authorization package, its deny-by-default guard and its 401 versus 403 mapping.