Guards
NestAuthAuthGuard and AdminSessionGuard.
NestAuthAuthGuard
The main guard. There are two ways to apply it — pick one:
Opt-in (recommended for most apps) — put @Auth() (or @UseGuards(NestAuthAuthGuard)) on the specific routes/controllers you want protected. Everything else stays open. Nothing else to configure.
Global guard + @Public() opt-out — apply the guard app-wide and mark open routes @Public(). Good when "secure by default, list the exceptions" fits your app better.
Both modes work out of the box. The library's own public endpoints (
/auth/login,/auth/signup,/auth/refresh-token,/auth/forgot-password,/auth/reset-password, the SSO callback,client-config, …) are already marked@Public(), so a global guard never blocks login. The admin console is likewise exempt — it authenticates with its own cookie-basedAdminSessionGuard, not NestAuth JWTs, so a globalNestAuthAuthGuardis not applied to it.
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.