Guards
NestAuthAuthGuard and AdminSessionGuard.
NestAuthAuthGuard
The main guard. Apply it once globally and let decorators (@Auth, @Public, @NestAuthRoles, @NestAuthPermissions, @SkipMfa) opt routes in and out.
What it does, in order, on every request:
- Checks for
@Public()— if present, skip everything below. - Calls
guards.beforeAuth(request)— your hook can{ reject: true, reason: '...' }to short-circuit (used for IP allowlists, device fingerprinting, etc.). - Reads the
Authorizationheader (or cookie) and decides whether it's a JWT or an API key. - Validates the token / key.
- Resolves the active tenant.
- Loads
userAccessfor the user + tenant. - Resolves roles via
authorization.resolveRoles(default: read from DB). - Resolves permissions via
authorization.resolvePermissions(default: expand from roles). - Checks any
@NestAuthRolesand@NestAuthPermissionsconstraints. - Checks MFA enforcement (skipped if
@SkipMfa()is on the route). - Calls
guards.afterAuth(request, user)— last chance to reject. - Populates the request context (decorators above will see this).
If anything fails, the guard throws — your AuthExceptionFilter (registered in main.ts) turns that into a structured response with an error code from AUTH_ERROR_CODES.
AdminSessionGuard
Protects the embedded admin console. Applied automatically to every route under adminConsole.basePath. Validates the admin session cookie and (optionally) the admin's MFA status.
You don't usually apply this guard yourself — AdminConsoleModule registers it on its own controllers. See Admin Console.
Custom guards on top
You can chain your own guards after NestAuthAuthGuard runs. By the time your guard executes, request.user, request.session, request.tenantId are all set.
Practical patterns
- Optional auth —
@Auth(true)makes context available when present without enforcing it. - Test stubs — in tests, override
NestAuthAuthGuardwith a stub that injects whatever user you want. See Testing Your Auth. - IP allowlist — add the policy to
guards.beforeAuthso it runs on every authenticated route. See the IP allowlist recipe.
Related
- Decorators — what to put on routes.
- Hooks Reference —
guards.beforeAuth,guards.afterAuth. - Error codes.