Skip to content

The authenticator

Every way to declare an authenticator: a provider or a factory, where its arguments come from, how a shared registration is reused, and the boot errors that tell you what is wrong.

6 min read Source

The authenticator answers one question per request: who is this? Everything else — rules, @Guard, @CurrentIdentity() — reads the Identity it returns.

@SecurityConfiguration({authenticator}) accepts a provider or a factory. Never a pre-resolved instance: the injector always owns the object, which is what lets the authenticator depend on application services and be shared with the rest of the application.

The four declaration forms

Form Declaration Resolved Dependencies from
factory authenticator: (store, auth) => auth.add(…) boot shared providers in order, or providers
provider factory authenticator: {provide: DefaultAuthenticator, useFactory: () => …} boot the provider's own providers
provider value authenticator: {provide: DefaultAuthenticator, useValue: instance} boot none, handed over as is
provider class authenticator: {provide: Token, useClass: ZeroArgAuthenticator} boot none, constructed with no arguments
none omit authenticator – every caller is a guest

A bare instance is not accepted:

// rejected at class definition
authenticator: new DefaultAuthenticator([new TokenChecker(verify)])
// @SecurityConfiguration: authenticator must be a provider or a factory -
// use {provide: DefaultAuthenticator, useFactory: () => instance}

// accepted
authenticator: {provide: DefaultAuthenticator, useFactory: () => new DefaultAuthenticator([new TokenChecker(verify)])}

The factory form, in full

This is the form to reach for when the authenticator needs application services — a user store, a key service, a configuration reader.

@Injectable()
class UsersStore implements IdentityStore {
  async find(name: string): Promise<Identity | null> { … }
  async passwordOf(name: string): Promise<string | null> { … }
}

@SecurityConfiguration({
  authenticator: (store: UsersStore, authenticator: DefaultAuthenticator) => authenticator
    .add(new JwtTokenChecker(new JwtVerifier({algorithms: ["HS256"], secret: SECRET})))
    .add(new LoginChecker(store, new ScryptPasswordHasher())),
  guards: guards => guards.anyRequest("identified()")
})
@RootModule({shared_providers: [UsersStore, DefaultAuthenticator], controllers: [ArticlesController]})
class Application {}

Two things make it work, and both follow from decorator order:

  1. @SecurityConfiguration is applied above @RootModule, so it runs last and can read the module's live shared_providers array.
  2. A bare DefaultAuthenticator in that array is normalized to {provide: DefaultAuthenticator, useFactory: () => new DefaultAuthenticator()}. useClass is the only injector path that reads design:paramtypes, and @Injectable() on the class advertises [Array] for its checkers parameter — which the injector cannot resolve. The class itself is untouched: the constructor still accepts checkers, add() is simply the DI path.

Nothing is removed from shared_providers, so the instance stays reachable from every module.

Where the arguments come from

The factory receives its parameters positionally. There are three sources, in priority order:

Source When Order
providers on the configuration declared exactly as declared
@RootModule({shared_providers}) providers omitted declaration order, sliced to the factory's arity
the provider's own providers provider factory as declared on the provider
// the shared order matches the parameters
@RootModule({shared_providers: [UsersStore, DefaultAuthenticator]})
authenticator: (store: UsersStore, authenticator: DefaultAuthenticator) => …
// explicit order, when the shared order does not match
@SecurityConfiguration({
  providers: [ScryptPasswordHasher, UsersStore, DefaultAuthenticator],
  authenticator: (hasher: ScryptPasswordHasher, store: UsersStore, authenticator: DefaultAuthenticator) =>
    authenticator.add(new LoginChecker(store, hasher)),
  guards: guards => guards.anyRequest("identified()")
})

A factory is an arrow function: it carries no parameter metadata, so its arity is all the package can see. Two consequences:

  • Declaring fewer providers than parameters is a boot error naming both numbers.
  • Declaring more is fine — the surplus is ignored, and a zero-argument factory ignores the shared list entirely.
@SecurityConfiguration: the authenticator factory declares 2 dependencies,
but only 1 provider(s) are available - declare them in @RootModule({shared_providers})
or in @SecurityConfiguration({providers})

The provider forms

A provider gives you an explicit token, which is useful when the authenticator is produced by something other than DefaultAuthenticator, or when you want to register it yourself.

// a plain factory provider
@SecurityConfiguration({
  authenticator: {
    provide: DefaultAuthenticator,
    useFactory: () => new DefaultAuthenticator([new TokenChecker(verifyOpaqueToken)])
  },
  guards: guards => guards.anyRequest("identified()")
})
// a provider factory with its own dependencies
@SecurityConfiguration({
  authenticator: {
    provide: DefaultAuthenticator,
    useFactory: (store: UsersStore) => new DefaultAuthenticator([new LoginChecker(store, new ScryptPasswordHasher())]),
    providers: [UsersStore]
  },
  guards: guards => guards.anyRequest("identified()")
})
// a ready-made instance
const authenticator = new DefaultAuthenticator([new TokenChecker(verifyOpaqueToken)]);

@SecurityConfiguration({
  authenticator: {provide: DefaultAuthenticator, useFactory: () => authenticator},
  guards: guards => guards.anyRequest("identified()")
})

{provide, useValue} accepts the same instance and is still supported, but useFactory is what every example here uses: construction stays visible at the call site, and the shape is identical across the four forms.

useClass is for a zero-argument implementation of Authenticator. A class with its own constructor dependencies belongs in useFactory — the injector resolves useClass asynchronously, and an interceptor factory cannot await.

Reuse, not duplication

If the application already registered an authenticator, the declaration is a fallback and its factory is never invoked:

@RootModule({
  shared_providers: [{
    provide: DefaultAuthenticator,
    useFactory: () => new DefaultAuthenticator([new JwtTokenChecker(verifier)])
  }]
})

The same applies to @SecurityConfiguration, which only registers what does not already resolve:

Situation Result
token already resolvable reused; a declared factory is not called
bare DefaultAuthenticator in shared_providers normalized to a zero-arg factory
{provide: DefaultAuthenticator, useClass: DefaultAuthenticator} normalized the same way
your own provider under that token left exactly as written — its useFactory and its own dependencies are preserved
nothing registered the declaration is materialized and stored under its token

That last-but-one row matters: the package only repairs the spelling it knows is broken. A provider you wrote is yours.

What gets registered

Token Value Why
DefaultAuthenticator (or the provider's own provide) the instance the chain uses so @Inject(DefaultAuthenticator) returns the same object, not a second one
GuardChain the chain, as a value resty invokes the interceptor instance it finds; an authenticator placed in the interceptor list would be treated as an interceptor
providers entries only when the token does not already resolve a duplicate would be re-created or throw
@Controller({path: "/session"})
class SessionController {
  constructor(@Inject(DefaultAuthenticator) private readonly authenticator: DefaultAuthenticator) {
  }

  @GET()
  me(): object {
    /** the same instance the guard chain consults */
    return {checkers: (this.authenticator as unknown as {checkers: Array<unknown>}).checkers.length};
  }
}

A shared authenticator across modules

Because the instance lives on the shared injector, a controller in an imported feature module needs nothing extra:

@Module({providers: [], controllers: [FeatureController]})
class FeatureModule {}

@SecurityConfiguration({ … })
@RootModule({
  shared_providers: [UsersStore, DefaultAuthenticator],
  controllers: [ArticlesController],
  imports: [FeatureModule]
})
class Application {}
@Controller({path: "/feature"})
class FeatureController {
  constructor(
    @Inject(DefaultAuthenticator) private readonly authenticator: DefaultAuthenticator,
    @Inject(UsersStore) private readonly store: UsersStore
  ) {
  }
}

One authenticator, one store, no second copy — that is what shared means here.

Common mistakes

Symptom Cause Fix
… must be a provider or a factory at class definition a bare instance was passed wrap it in {provide: DefaultAuthenticator, useFactory: () => instance}
No provider Array on class Array at boot useClass on a class with a collection parameter use a zero-arg useFactory
the authenticator factory declares 2 dependencies, but only 1 provider(s) are available shared list shorter than the arity add the service to shared_providers, or declare providers
DefaultAuthenticator is already defined in injector the same token registered twice by hand remove it from providers; an existing registration is reused automatically
the chain receives a promise an async factory the factory must be synchronous
404 on every route a boot error surfaced as a missing route read the server log; resty maps DI failures to 404
the factory gets undefined the shared order does not match the parameter order declare providers explicitly

Next

  • Credentials — what goes inside the authenticator
  • JWT — the built-in verifier
  • Rules — what the identity is then checked against