skip to content

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%

answer

  1. providers register themselves
  2. inject the registry in the constructor
  3. the registry locks at module init
  4. ascending order, first user wins

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.

solid answer

~40 s

In NestJS 12's `@nestjs/authentication`, credential providers are not listed in `forRoot()`. Each is an `@Injectable()` singleton in one of your modules (often a `SessionCookieProvider` subclass) that injects `AuthenticationRegistry` and calls `registry.registerProvider(this, { order })` in its constructor. The registry locks in `AuthenticationModule`'s `onModuleInit` and logs the chain; registering later, from a request-scoped, transient or lazy-loaded provider or a lifecycle hook, throws. For each protected request the guard calls the providers in ascending `order` (default `0`): `null` means "not my credentials, try the next", the first result with a user wins, and a thrown `AuthenticationError` stops the chain with a refusal. Two providers on the same `order` fail at registration unless one passes `replace: true`. `@Authenticate({ providers: [...] })` narrows the chain for one route.

go deeper

for a junior

Recall that a provider registers itself with registerProvider(this) from its constructor and that returning null means the request is not its business.

for a middle

Explain the lock at onModuleInit, ascending order with the first user winning, and why null, a user and an AuthenticationError lead to different guard outcomes.

for a senior

Show you would read the startup chain log, choose explicit orders when adding a provider, and restrict sensitive routes to one provider class with @Authenticate.

for a principal

Weigh self-registering providers against a central list: discuss how ordering conventions and startup failures keep a growing team from silently shadowing one provider with another.

## What a credential provider is In NestJS 12's `@nestjs/authentication`, the global `AuthenticationGuard` does not know how to read a cookie or a header itself. It delegates to **credential providers**: objects with an `authenticate(context)` method that look at the incoming request and either return a result with a `user`, return `null` when the request carries nothing they understand, or throw an `AuthenticationError` when the credentials are theirs but invalid. The package ships base classes for the common cases, such as `SessionCookieProvider` for the session cookie, and any object with `authenticate()` (and optionally `challenge()`) qualifies. A credential provider is an ordinary `@Injectable()` class in one of your own modules, so it can inject a users repository, configuration or anything else that module provides. ## Registering from the constructor There is no list of providers in `AuthenticationModule.forRoot()`. Each provider **registers itself** by injecting `AuthenticationRegistry` and calling `registerProvider(this)` in its constructor: ```typescript import { Injectable } from '@nestjs/common'; import { AuthenticationRegistry, SessionCookieProvider, type SessionRecord } from '@nestjs/authentication'; import type { User } from '../users/user.js'; import { UsersRepository } from '../users/users.repository.js'; @Injectable() export class SessionAuth extends SessionCookieProvider<User> { constructor( private readonly usersRepository: UsersRepository, registry: AuthenticationRegistry, ) { super(); registry.registerProvider(this); // order defaults to 0 } validate(session: SessionRecord) { return this.usersRepository.findById(session.userId); } } ``` `SessionCookieProvider` receives `SessionService` by property injection, which is why the constructor lists only its own dependencies and the registry. Returning `null` from `validate()` (the user was deleted) ends that session. ## When the registry locks The registry accepts registrations only until it **locks**, which happens in `AuthenticationModule`'s `onModuleInit` (by then every singleton constructor has run) or at the first read of the chain, whichever comes first. At the lock it orders the chain and logs it, for example `AuthenticationRegistry: providers SessionAuth`. A registration after that throws, and the message names what runs too late: - providers of **lazy-loaded modules**; - **request-scoped** and **transient** providers; - calls made from **lifecycle hooks** such as `onApplicationBootstrap()`. With a second provider, say a bearer-token provider registered at `order: 1`, the line reads `AuthenticationRegistry: providers SessionAuth, JwtAuth`: the names appear in the order the guard will try them, which makes the log the quickest way for a reviewer to confirm that a newly added provider did not jump ahead of the session cookie. Other registration mistakes also fail at startup rather than at the first request: an object without `authenticate()`, passing the class instead of `this`, the same instance twice, the same class provided in two modules, or two providers asking for the same `order` without `replace: true`. Putting a `providers` key into `forRoot()` fails with a hint pointing back to `registerProvider()`. If nothing registers at all, the module only warns, and every route that is not `@Public()` answers `401`. ## How the guard walks the chain For a route that is not public, the guard: 1. Takes the registered providers in **ascending `order`** (default `0`). 2. Calls each provider's `authenticate()` in turn; a `null` result passes the request to the next one. 3. Stops at the **first result with a user**: that provider wins, and the user is recorded for `@CurrentUser()` and `AuthenticationContext`. 4. Stops with a refusal if a provider throws `AuthenticationError`, answering with that error's status and code. 5. Answers `401` `missing_credentials` when every provider returned `null`, unless the route is optional. The raw result is cached on the request, so providers run once per call even when something else asks again. | Situation | What the guard does | | --- | --- | | provider returns `null` | tries the next provider | | provider returns a user | stops, user recorded | | provider throws `AuthenticationError` | stops, refusal with its status and code | | provider throws any other error | rethrows it, so Nest's exception layer answers | ## Per-route restriction A route can narrow the chain with `@Authenticate({ providers: [SessionCookieProvider] })`. Classes are matched with `instanceof`, so a base class covers its subclasses, and credentials from any other provider count as none on that route. That is how a route accepts only the browser session even though the app also registers a bearer-token provider at `order: 1`. A restricted run is not cached for the rest of the request, so it never decides the outcome for another route or resolver that shares the same request; typical uses are an account-settings route that should accept only the browser session, or an internal route that accepts only one machine credential.

  • Why does registering a credential provider from onApplicationBootstrap() fail?
    The registry locks in `AuthenticationModule`'s `onModuleInit`, or at the first read of the chain if that is earlier, so the guard sees a fixed, ordered chain before any request. `onApplicationBootstrap()` runs after that lock, so `registerProvider()` throws and names lifecycle hooks, request-scoped, transient and lazy-loaded providers as too late. Register from the constructor of a singleton instead.
  • What happens when a session provider at order 0 and a bearer-token provider at order 1 both see credentials on one request?
    The guard calls the order-0 provider first. If it returns a user, it wins and the bearer provider is never called. Only if it returns `null` does the guard try order 1. If the first provider throws `AuthenticationError`, the chain stops with a refusal and the second provider is not consulted.

  • List the credential provider classes under providers in AuthenticationModule.forRoot().
  • A request-scoped credential provider is fine, since it gets a fresh instance per request.
  • The provider with the highest order runs first.
  • Every registered provider runs, and their users are merged.
  • A provider should throw when the request carries no credentials it understands.

Assumes NestJS 12: the first-party @nestjs/authentication package declares @nestjs/common and @nestjs/core 12 as peer dependencies and is taught by the v12 security docs.