@ballistix.digital/identity-connector
v0.6.0
Published
NestJS module that signs a user in with an OIDC access token and provisions users at one or more identity providers, behind provider-agnostic contracts.
Maintainers
Keywords
Readme
@ballistix.digital/identity-connector
A NestJS module that signs a user in with an OIDC access token and provisions users at one or more identity providers, behind provider-agnostic contracts. The app does not know which provider is behind it, and one app can use more than one at the same time. The providers are Zitadel, Entra and Auth0, each behind an entry of its own.
This file is the consumer guide and the public contract. The pages that describe how the package is built live in the Ballistix wiki.
Install
npm install @ballistix.digital/identity-connector @ballistix.digital/exception-mapper @ballistix.digital/exception-types class-validator class-transformerThe providers verify tokens, and the Zitadel provider signs its service user's
assertion, with jose. Install it when the application imports ./zitadel,
./entra or ./auth0:
npm install jose@^6Zitadel's bulk import hashes a password with bcryptjs, which it loads only
when called. Install it when the application calls provisionMany() on a
Zitadel connection:
npm install bcryptjs@^3jose ships ES modules only. Node 24 loads it from CommonJS by itself, but
Jest's CommonJS runtime does not: a Jest setup that loads a provider entry
transforms jose to CommonJS (transformIgnorePatterns:
['/node_modules/(?!jose/)']). Give jose a transformer of its own that only
rewrites the import syntax and keeps class fields as they are
(useDefineForClassFields: true): jose's error classes break under the
[[Set]] semantics Ballistix packages compile with, and ts-jest keeps one
configuration per Jest project, so a second ts-jest entry does not help. This
repository's test/module/common/esModule.transformer.js is such a
transformer.
A browser build that reads the ./types entry alone installs the package by
itself:
npm install @ballistix.digital/identity-connectorThe package needs Node 24 or later and has no dependencies of its own. Every peer dependency is optional, so npm installs none of them for you: install in the application what the entries it imports need.
Entries
| Entry | Holds |
| --- | --- |
| . | The module, the runtime, the contracts, and identityConnectorException and identityConnectorExceptionTypeOf |
| ./zitadel | The Zitadel provider |
| ./entra | The Entra provider |
| ./auth0 | The Auth0 provider |
| ./testing | The test doubles and the store contract |
| ./types | The exception type enum, with no framework import |
Signing in
An app writes three classes and registers them. Each one extends a class of the package, which holds the logic.
Register
ExceptionModuleand the app's provider classes, one per identity provider connection:@Module({ imports: [ ExceptionModule.forRoot(), IdentityConnectorModule.forRoot({ identityProviders: [ComplianceZitadel] }), ], }) export class AppModule {}The module builds each provider once, with what its constructor injects, so a global
ConfigModuleor a module inimportsmust provide it; every guard and identity management then shares that instance. Two providers with the same name stop the app at boot, since a store keeps an identity under its provider's name, and so do two providers that list the same issuer: a token names only its issuer, so with the same audience each would accept the other's tokens. A missingExceptionModulestops it too: without its filter, every refusal would reach the client as a 500.Write the user store over the app's own table. It implements
UserStore, and the library never touches the table itself:@Injectable() export class UserStoreService extends UserStore<User> { findByIdentityId(identityId, provider, transaction) { /* find by the column of that provider, on the transaction when given */ } async linkByEmail(identity) { /* one match by email, conditional link */ } async create(identity) { /* only with createOnSignIn: return the user the identity already has, or insert one */ } async sync(user, identity) { /* write roles, email, names; return the value for request.user */ } toProfile(user, provider) { /* throw identityConnectorException(NO_EMAIL) when the user has none */ } link(user, identityId, provider, transaction) { /* conditional: no other identity, no other user, by primary key */ } }Extend the guard, pass it the providers whose tokens it accepts, and put it on the controllers.
request.useris whatsync()returned:@Injectable() export class AuthGuard extends IdentityAuthGuard<User> { constructor(runtime: IdentityRuntime, store: UserStoreService, zitadel: ComplianceZitadel) { super(runtime, store, [zitadel]); } } @UseGuards(AuthGuard)
A guard accepts the tokens of the providers it passes to super(), at least
one, injected by the class it registered in IdentityConnectorModule.forRoot();
a guard for employee routes passes only the Entra provider. A token goes to
the one among them that lists its issuer, before anything is verified, and a
token of another registered provider is refused as PROVIDER_NOT_ACCEPTED. A
guard without providers, or with a provider the module does not register,
stops the app at boot. A provider the app registers only when it is
configured is injected with @Optional() and passed only when it is set:
constructor(runtime: IdentityRuntime, store: UserStoreService, entra: ComplianceEntra, @Optional() zitadel?: ComplianceZitadel) {
super(runtime, store, zitadel ? [entra, zitadel] : [entra]);
}Provisioning users
Provisioning gives one of the app's users an identity at the identity
provider, for example when the app invites a customer: the identity provider's
identity with the user's email, or a new one, linked to the user through the
store's link(). The app then sends its own mail with a link where the user
sets up how they sign in, such as a password.
Extend IdentityManagement once per place the app manages identities, such as
customers and employees. It injects the store and the provider class, and
passes the management options of that place: their shape is the provider's,
for Zitadel the organization new users land in.
@Injectable()
export class CustomerIdentityManagement extends IdentityManagement<User, ComplianceZitadel> {
constructor(runtime: IdentityRuntime, store: UserStoreService, zitadel: ComplianceZitadel, config: ConfigService) {
super(runtime, store, zitadel, {
organizationId: config.get('ZITADEL_CUSTOMERS_ORG_ID'),
federatedOrganizationIds: [config.get('ZITADEL_VDL_ORG_ID')],
});
}
}Inject it where the domain needs it:
if (!(await this.customers.isFederated(user))) {
await this.customers.provision(user, transaction);
// queue the app's own mail
}
// in the mail job, at send time, so the link is never stored
const link = await this.customers.createAccountSetupLink(user, { returnUrl });isFederated(user)is true when the user's email signs in elsewhere, for example employees whose domain belongs to an organization that signs in through Entra. Call it beforeprovision():provision()does not check it, and would give such a user an identity of its own.provision(user, transaction?)does nothing for a user already linked to the provider. Otherwise it finds the identity by email or creates one, and links it withlink(user, identityId, provider, transaction). The store'slink()decides: it refuses a user that has another identity of the provider, and an identity another user has. When it refuses,provision()reads the owner withfindByIdentityId(identityId, provider, transaction)to throwIDENTITY_ALREADY_LINKEDorLINK_REFUSED. The transaction reaches both unchanged, so the store runs them on the connection the transaction holds: with a pool of one connection, a read outside it would wait forever. The guard callsfindByIdentityIdwithout a transaction.provision()returns nothing and throws on failure. When it fails after the identity was created, the next call finds that identity by email and links it, rather than creating a second one.provisionMany(users, { transaction?, dryRun?, identityIdOf? })isprovision()for a page of users, such as a migration of existing users needs. It asks the provider for every email at once withfindByEmails(), creates the missing identities at once withcreateMany(), then links each user asprovision()does. It returns one result per user, in the order given, and a failure fails only its own user; it throws only when the whole call fails, such asNOT_CONFIGUREDor an unreachable search. CheckisFederated()first, as forprovision(). Pass a page of users per call, such as a hundred. When the provider holds several identities with one email, the user is linked to the first the provider answers.identityIdOf(user)names the id a created identity gets, such as the user's own id, for a provider that lets the caller choose it, as Zitadel's import does; without it, or with another provider, the provider picks the id.createAccountSetupLink(user, { returnUrl })asks the provider for a link where the identity sets up how it signs in, such as a password.
const results = await this.customers.provisionMany(page, { dryRun });
for (const result of results) {
if (result.outcome === ProvisionOutcomeEnum.FAILED) {
log(result.user.id, identityConnectorExceptionTypeOf(result.error) ?? result.error.message);
}
}| Outcome | Meaning |
| --- | --- |
| ALREADY_PROVISIONED | The user had an identity at the provider; nothing changed |
| PROVISIONED | The user is linked to the identity with its email, which the provider had or created |
| WOULD_LINK, WOULD_CREATE | dryRun: what a real run would do. A dry run creates, links and forgets nothing |
| FAILED | The user got no identity. error is what provision() would have thrown |
Two users with one email get one identity: the first links it, and the second
fails with IDENTITY_ALREADY_LINKED, as two provision() calls in a row
would. A dry run reports the same, and also IDENTITY_ALREADY_LINKED for an
identity another user already holds.
A provider without bulk calls answers findByEmails() and createMany() with
one findByEmail() or create() per user, so provisionMany() works with
every provider; Zitadel overrides both.
A sign-in refused just before the user is provisioned is not remembered after
provision() links the identity, so the user signs in at once. That holds
when the guard and the identity management inject the same store instance:
the guard remembers sign-ins per store instance, so two store classes are two
caches, even over one table, and so is one class registered in two modules.
Register the store once, as a singleton: a request-scoped store gets a new
cache on every request, which remembers nothing and does not run parallel
first sign-ins of one identity one at a time. Calling provision() again for
a user already linked clears the refusal as well.
Each method reads the email and the identity id through the store's
toProfile(user, provider), so the app never handles an identity id. Two
identity managements may inject one provider class, each with its own
management options. An identity management whose provider class is not
registered in IdentityConnectorModule.forRoot() stops the app at boot.
What the methods throw; Exceptions lists every type with its code and field:
| Type | Status | Exception | When |
| --- | --- | --- | --- |
| NO_EMAIL | 409 | PreconditionFailedException | toProfile() found no email on the user |
| IDENTITY_ALREADY_LINKED | 409 | PreconditionFailedException | provision(): the store's link() refused, and another user owns the identity with the user's email |
| LINK_REFUSED | 409 | PreconditionFailedException | provision(): the store's link() refused for another reason, such as a user with another identity of the provider |
| USER_NOT_PROVISIONED | 409 | PreconditionFailedException | createAccountSetupLink(): the user has no identity at this provider |
| NOT_CONFIGURED | 503 | GenericErrorException | The provider holds no management credentials. Catch it to skip provisioning, for example on a local machine |
| NOT_SUPPORTED | 501 | GenericErrorException | The provider cannot perform the call |
| PROVIDER_UNREACHABLE | 503 | GenericErrorException | The provider could not be reached |
A refusal of the provider that retrying does not fix, such as a rejected key,
is a plain Error with the provider's answer; the provider's section says
which.
Exceptions
The library has no exception class of its own. It throws the exceptions of
@ballistix.digital/exception-types, so the app's exception filter and its
frontends see the same classes and envelopes as for any other error. Each
type of IdentityConnectorExceptionTypeEnum reaches the client as:
| Type | Status | Code | Exception | Where the type sits | Thrown by |
| --- | --- | --- | --- | --- | --- |
| NO_TOKEN | 401 | UNAUTHENTICATED | UnauthenticatedException | errors[0].message | The guard: no Bearer token |
| UNKNOWN_ISSUER | 401 | UNAUTHENTICATED | UnauthenticatedException | errors[0].message | The guard: no registered provider lists the token's issuer |
| PROVIDER_NOT_ACCEPTED | 401 | UNAUTHENTICATED | UnauthenticatedException | errors[0].message | The guard: the provider that lists the token's issuer is registered, but not one the guard accepts |
| INVALID_TOKEN | 401 | UNAUTHENTICATED | UnauthenticatedException | errors[0].message | The guard and the providers: the token is not valid |
| USER_NOT_LINKED | 403 | ACCESS_DENIED | AccessDeniedException | errors[0].message | The guard: no user for the identity |
| NO_EMAIL | 409 | PRECONDITION_FAILED | PreconditionFailedException | errors[0].condition | The store's toProfile() |
| IDENTITY_ALREADY_LINKED | 409 | PRECONDITION_FAILED | PreconditionFailedException | errors[0].condition | provision() |
| LINK_REFUSED | 409 | PRECONDITION_FAILED | PreconditionFailedException | errors[0].condition | provision() |
| USER_NOT_PROVISIONED | 409 | PRECONDITION_FAILED | PreconditionFailedException | errors[0].condition | createAccountSetupLink() |
| NOT_SUPPORTED | 501 | GENERIC_ERROR | GenericErrorException | errors[0].message | A management call the provider cannot perform |
| NOT_CONFIGURED | 503 | GENERIC_ERROR | GenericErrorException | errors[0].message | A management call without credentials |
| PROVIDER_UNREACHABLE | 503 | GENERIC_ERROR | GenericErrorException | errors[0].message | A provider that cannot reach its identity provider |
A frontend that maps the library's refusals reads the type from the field the
table names; the code alone does not tell USER_NOT_LINKED apart from another
403, nor a 401 of the library from another UNAUTHENTICATED.
To react to one case, read the type with
identityConnectorExceptionTypeOf(error)and compare it; never compare the message or the class. It answers only for an exception with the code and status the type is thrown with, andundefinedfor anything else.try { await this.customers.provision(user, transaction); } catch (error) { if (identityConnectorExceptionTypeOf(error) !== IdentityConnectorExceptionTypeEnum.NOT_CONFIGURED) throw error; }To throw one, from a store or from a provider the app writes, use
identityConnectorException(type): it picks the class and status the type reaches the client with, for examplethrow identityConnectorException(IdentityConnectorExceptionTypeEnum.NO_EMAIL)intoProfile().
Zitadel
ZitadelProvider from ./zitadel signs users in with access tokens of one
Zitadel instance. The app extends it once per connection:
@Injectable()
export class ComplianceZitadel extends ZitadelProvider {
constructor(config: ConfigService) {
super({
name: 'zitadel',
issuer: config.get('ZITADEL_ISSUER'),
projectId: config.get('ZITADEL_PROJECT_ID'),
organizationIds: [config.get('ZITADEL_VDL_ORG_ID')],
roleOrganizationIds: [config.get('ZITADEL_VDL_ORG_ID')],
linkByEmail: true,
serviceUserKey: config.get('ZITADEL_SERVICE_USER_KEY'),
});
}
}| Option | Required | Meaning |
| --- | --- | --- |
| name | yes | The provider name; unique in the app |
| issuer | yes | The Zitadel instance URL: the one issuer it accepts and the base of its endpoints. A trailing slash is dropped |
| projectId | yes | The Zitadel project: the audience every token carries |
| organizationIds | yes, at least one | The organizations whose users may be linked or created at sign-in |
| roleOrganizationIds | yes, at least one | The organizations whose role grants count |
| linkByEmail, createOnSignIn | no, both off | As for every provider |
| serviceUserKey | no | The key file of the service user that calls the management API, parsed or as its JSON text. Left out or an empty string, every management call throws NOT_CONFIGURED; null or text that is not JSON stops the app at boot |
Both organization lists are required and may not be empty. An empty list would quietly let every organization in, or let every organization's role grants count: another organization with a grant on the project could then hand its users an elevated role. A connection with a missing or empty option stops the app at boot with a message that names the provider and every failing option.
The app's Zitadel application must issue JWT access tokens. The provider verifies each token against the instance's signing keys (RS256, this issuer, this project as audience) and caches the keys, so a signed-in user costs no call to Zitadel; an opaque access token cannot be verified and is refused as not valid.
The keys are cached by jose's createRemoteJWKSet. A token whose key is
cached is answered from the cache. Once the keys are ten minutes old, the next
token waits for a fresh set. A token with a key id the cache lacks fetches the
keys again when the last fetch that succeeded is 30 seconds old or more;
otherwise, it is refused as not valid (401). Every token waiting on a fetch
shares it. Tokens with made-up key ids therefore cost Zitadel at most one
request per 30 seconds and never lock out a user whose key is known. A key
Zitadel adds is accepted within 30 seconds, and a key it withdraws is refused
within ten minutes. A fetch gets 5 seconds; when the keys are needed and cannot
be fetched, the token fails with PROVIDER_UNREACHABLE (503) rather than as
not valid, so a user with a key Zitadel just added is not signed out. While
Zitadel's key endpoint is down, every sign-in fails this way once the keys are
ten minutes old.
On a first sign-in, when no user is linked yet, the provider calls Zitadel's
userinfo endpoint to complete the identity: email, whether Zitadel verified
it, and names. It refuses a user whose organization is not in
organizationIds with USER_NOT_LINKED (403). The frontend must request the
scope urn:zitadel:iam:user:resourceowner at sign-in: without it userinfo
leaves the organization out, and every first sign-in is refused. The provider
passes emailVerified on without checking it; a store that links by email
decides whether an unverified email may link.
Managing Zitadel users
With serviceUserKey, an IdentityManagement on this provider provisions
users at Zitadel. Its management options:
| Management option | Required | Meaning |
| --- | --- | --- |
| organizationId | yes | The organization provision() searches by email and creates new users in |
| federatedOrganizationIds | no | Organizations whose users sign in elsewhere: isFederated() is true for an email on one of their domains |
The service user is a machine user with a key of type JSON. It needs to search
and create users and create password codes in organizationId, and to read the
domains of federatedOrganizationIds. The provider exchanges an assertion
signed with its key for an access token (Zitadel's JWT profile grant) and
reuses that token until a minute before it expires.
findByEmailsearchesorganizationIdalone, without regard to case. Two users there with one email are an error rather than a pick.createmakes a human user with a verified email and no password.createAccountSetupLinkreturns a link to the password page of Zitadel's login (v2), with a password code Zitadel returns instead of mailing it. The code is valid as long as the instance's setting for password reset codes says, so ask for the link when the mail is sent; every call creates a new one. The page reads no return address, soreturnUrlis ignored.isFederatedcompares the email's domain with the domains offederatedOrganizationIds, exactly: a subdomain does not count. It caches each organization's domains for ten minutes, so a domain an admin adds counts within that time.- Every email is sent trimmed and in lowercase. Zitadel matches uppercase letters badly in its user search and its domain discovery (Zitadel issue #12025).
provisionMany() runs on the provider's two bulk calls, which send a 429
again, up to five times, after Zitadel's Retry-After (at most 30 seconds) or
after 2, 4, 8, 16 and 32 seconds: Zitadel Cloud blocks for about half a minute
and sends no Retry-After. Every other call fails at once, so a request never
hangs on a rate limit.
findByEmailssearches all emails of the call in one request, and keeps the first user Zitadel answers for an email with several. Zitadel answers at most 1000 users, so an answer that long throws rather than leave users out: pass a page of users, such as a hundred.createManyimports two hundred users per request with Zitadel's import, each under the ididentityIdOfnames or a new random one, with the email as user name and verified, and a bcrypt hash of a random password nobody knows: without a password Zitadel marks the user initial, ignores the verified email and mails its own invitation. The import needs theIAM_OWNERrole; without it Zitadel answers 403, and the provider creates the users one by one withcreate()instead. A user Zitadel refused fails with Zitadel's reason.
The management options are checked at boot when serviceUserKey is given: a
missing organizationId stops the app with a message that names the identity
management. Without the key they go unchecked, so an app on a local machine
may leave both unset; every management call then throws NOT_CONFIGURED,
which the app catches to skip provisioning.
A call Zitadel cannot answer, through a network failure, a timeout of 5
seconds, a 5xx, a 408 or a 429, is PROVIDER_UNREACHABLE (503). So is a 401:
it may only mean Zitadel ended the service user's token early, so the provider
drops that token and the next call fetches a new one; the app tries again, as
for any 503. Any other refusal, such as a key Zitadel rejects when the provider
asks for a token or a service user without a permission, is a plain Error
with Zitadel's status and answer: a fault in the configuration that retrying
does not fix, and that an app skipping NOT_CONFIGURED must not skip
silently.
Entra
EntraProvider from ./entra signs users in with access tokens of one
Entra tenant, and with acceptIdTokens also with its ID tokens (see
ID tokens); without that option an ID token is refused. The app
extends it once per tenant:
@Injectable()
export class ComplianceEntra extends EntraProvider {
constructor(config: ConfigService) {
super({
name: 'entra',
tenantId: config.get('AZURE_AD_TENANT_ID'),
// Without ?., a missing variable fails here instead of in the provider's boot check.
audience: config.get('AZURE_AD_AUDIENCE')?.split(','),
createOnSignIn: true,
});
}
}| Option | Required | Meaning |
| --- | --- | --- |
| name | yes | The provider name; unique in the app |
| tenantId | yes | The GUID of the tenant. It gives the issuers and the URL of the signing keys. common and organizations name no single tenant and stop the app at boot |
| audience | yes | The application ID URI or client id every token carries, or a list of them. Each is trimmed |
| linkByEmail | no, off | Leave it off; see below |
| createOnSignIn | no, off | As for every provider |
| acceptIdTokens | no, off | Also accept an ID token of the tenant; see ID tokens |
One provider per tenant. Both of the tenant's issuers belong to the provider, and two providers may not list one issuer, so a second provider for the same tenant stops the app at boot. Several app registrations of the tenant share one provider through a list of audiences.
The provider accepts both of Entra's token versions: a v2.0 token, issued by
login.microsoftonline.com/<tenant>/v2.0, and a v1.0 token, issued by
sts.windows.net/<tenant>/. Which one Entra issues depends on the app
registration; nothing there has to change. It verifies each token against the
tenant's signing keys (RS256, one of those issuers, one of the audiences) and
caches the keys, as the Zitadel provider does, with the same times. It reads the tenant's keys: an
app registration with a claims-mapping policy gets its tokens signed with a
key of its own, which those keys do not list, so every token of it is refused
as not valid.
Identity.idis theoidclaim, the identity's object id.subdiffers per app registration, so a store that keeps thesubfinds no user once another app registration signs the same person in.- A token without
scpis refused withINVALID_TOKEN(401), unless it is an ID token andacceptIdTokensis on. Only an access token issued to an identity carries scopes; an app's own token, from the client credentials grant, has anoidand may carry app roles, but belongs to no identity. An app that calls the API with such a token is refused. - The email is the
emailclaim, which Entra adds only when the app registration asks for it as an optional claim; without it the email is null. The names aregiven_nameandfamily_name: a v1.0 access token carries them, a v2.0 one only as optional claims. For an access token, those optional claims are set on the app registration of the API, not of the frontend that asks for the token.preferred_usernameandupnlook like an email but need not be one and can change, so the provider does not read them.emailVerifiedis always false: Entra's tokens do not say. - Leave
linkByEmailoff. Theemailclaim is the identity's mail attribute, which an admin sets and Entra does not verify; on a guest it can be any address. A store that links by email would hand the user with that address to whoever carries it. Turn it on only with a store that trusts the tenant's mail attributes, and expectemailVerifiedto be false. - The roles are the app roles in the
rolesclaim. - A first sign-in needs no call to Entra: the token carries all the
provider knows, so
readProfilereturns the identity as it is.
ID tokens
The proper setup is an access token for an API scope the app registration
exposes: the frontend asks for that scope, and the backend accepts what Entra
issued for it. Some frontends send their ID token as the bearer instead,
because they only ask for openid profile email and their access token is
one for Microsoft Graph. acceptIdTokens: true lets such a frontend keep
working while it moves to an API scope. An ID token's audience is the
frontend's client id, so audience lists that client id.
With the option on, a token without scp passes as an ID token only when both
hold:
- It names no client. Every Entra access token names the client it was
issued to,
azpin a v2.0 token andappidin a v1.0 token, an app's own token from the client credentials grant included. An ID token carries neither. A token withidtyp: "app"is refused as well. - It names a person, in
name,preferred_usernameorunique_name. An app's own token has none of them. An ID token with anoiddoes: Entra adds theoidonly with theprofilescope, which brings them.
Signature, issuer, audience, lifetime and oid are checked as for an access
token, and the identity is read the same way. Delegated access tokens, with
scp, are still accepted.
What the option does not protect against:
- An ID token is meant for the frontend, not for an API. Anyone who gets hold of a user's ID token for that client, from the browser's storage or a log line, can call the API with it until it expires, usually after an hour. It cannot be narrowed to this API, and Entra does not end it early when the user signs out or loses access.
- The rule rests on claims as Microsoft documents them today, which it
does not promise to keep. Ask Entra for the
idtypoptional claim on the access tokens of the API's app registration: an app's own token then says so explicitly.
Turn it off once the frontend sends an access token for the API's scope.
Managing Entra users
The management calls are not available yet. findByEmail and create throw
NOT_CONFIGURED, which an app that provisions users catches to skip
provisioning. createAccountSetupLink and isFederated throw NOT_SUPPORTED
(501): the tenant's IT hands employees their password, and an Entra identity never
signs in elsewhere.
Auth0
Auth0Provider from ./auth0 signs users in with access tokens of one
Auth0 tenant for one or more of its APIs. The app extends it once per tenant:
@Injectable()
export class AppAuth0 extends Auth0Provider {
constructor(config: ConfigService) {
super({
name: 'auth0',
domain: config.get('AUTH0_DOMAIN'),
// Without ?., a missing variable fails here instead of in the provider's boot check.
audience: config.get('AUTH0_AUDIENCE')?.split(','),
rolesClaim: '.roles',
createOnSignIn: true,
});
}
}| Option | Required | Meaning |
| --- | --- | --- |
| name | yes | The provider name; unique in the app |
| domain | yes | The tenant's domain as the Auth0 dashboard shows it, such as <tenant>.<region>.auth0.com, or its custom domain. A host only: a scheme or a path stops the app at boot |
| audience | yes | The identifier of the Auth0 API every token carries, or a list of them. Each is trimmed |
| rolesClaim | no, none | The access token claim the post-login Action writes the roles to, such as .roles. Left out, the roles are none |
| linkByEmail | no, off | As for every provider; see below |
| createOnSignIn | no, off | As for every provider |
The provider verifies each token against the tenant's signing keys at
https://<domain>/.well-known/jwks.json (RS256, the issuer
https://<domain>/ with Auth0's trailing slash, one of the audiences) and
caches the keys, as the other providers do, with the same times. A token
names the domain it was requested on: a tenant with a custom domain passes
that domain, and its frontend requests tokens on it, or every token is
refused as one of another issuer.
Identity.idis thesubclaim, such asauth0|<id>. Auth0 keeps it for the identity across every application and API of the tenant.An app's own token is refused with
INVALID_TOKEN(401). A token from the client credentials grant has the same issuer and audience as a user's, but Auth0 marks it withgty: "client-credentials"and names the client as its subject,<client id>@clients. Either one refuses it.The email and names come from the token, through a post-login Action. An Auth0 access token carries no email or names by itself. Add an Action to the tenant's post-login flow that puts them in every access token:
exports.onExecutePostLogin = async (event, api) => { api.accessToken.setCustomClaim('email', event.user.email); api.accessToken.setCustomClaim('email_verified', event.user.email_verified); api.accessToken.setCustomClaim('given_name', event.user.given_name); api.accessToken.setCustomClaim('family_name', event.user.family_name); // Only with rolesClaim: '.roles'. api.accessToken.setCustomClaim('.roles', event.authorization?.roles ?? []); };Auth0 drops
emailandemail_verifiedfrom the token unless the login asks for theemailscope, and the names unless it asks forprofile, even when the Action sets them: the frontend asks foropenid profile email.The provider reads
email,email_verified,given_nameandfamily_nameon every sign-in, sosync()gets the same values each time, and a change in Auth0 reaches the user at the next sign-in. It calls Auth0 for nothing but its signing keys. Without the Action the email and names are null: a first sign-in creates a user without them, andtoProfilelater throwsNO_EMAILfor that user.emailVerifiedis the token'semail_verified, and only next to an email of the same token. A user an admin created in the dashboard has an unverified email unless the admin marked it verified; withlinkByEmail, whether such an email may be linked stays the store's decision.The roles are the text entries of the
rolesClaimlist. Auth0 has no standard roles claim, and silently drops a custom claim namedroles, so the tenant's Action writes them to a claim of its own choosing and the app names it. WithoutrolesClaim, or when the token's claim is missing or not a list, the roles are none. The roles go in the access token: a.rolesclaim the Action writes to the ID token never reaches the backend.
How the frontend gets the token, through Auth0's login page or the password grant on a server of the app, makes no difference to the provider.
Managing Auth0 users
The management calls are not available yet. findByEmail, create,
createAccountSetupLink and isFederated throw NOT_CONFIGURED, which an
app that provisions users catches to skip provisioning; provisionMany()
fails through them as well. Each becomes possible once the provider calls
Auth0's Management API.
Testing an app
./testing gives an app what it needs to test sign-in without an identity
provider:
const provider = new TestIdentityProvider({ name: 'zitadel', issuers: ['https://test-issuer'] });
Test.createTestingModule({ imports: [AppModule] })
.overrideProvider(ComplianceZitadel)
.useValue(provider);
const token = provider.createToken({ id: 'zitadel-1', roles: ['ADMIN'] });Run the store contract against the app's own store, so a store that breaks a rule the types cannot express fails in the app's CI:
for (const check of userStoreContract(() => ({ store, providers: ['zitadel'], createUser, userId: (user) => user.id }))) {
it(check.name, check.run);
}Good to know
A change at the provider takes up to
signInCacheSecondsto arrive. The guard verifies the token on every request, but for an identity it saw recently it answers from its cache, without the store and withoutsync(). A revoked role therefore stays onrequest.useruntil the entry expires: 60 seconds by default. SetsignInCacheSeconds: 0to apply such a change on the next request, at the cost of a store call on every request.A refused sign-in stays refused for up to
signInCacheSeconds. The guard remembers aUSER_NOT_LINKEDrefusal too.provision()drops it when it links the identity. A user the app links by other means is still refused until the entry expires, unlesssignInCacheSecondsis 0, and so is a sign-in that arrives betweenprovision()and the commit of the app's transaction; callingprovision()again after the commit clears it.link()keeps one identity to one user. The library cannot tell two user objects apart, so the store compares users by primary key and checks within the write. On PostgreSQL, a conditional update does both at once, with a unique index on the identity column behind it. The example runs it in a nestedtransaction(), which TypeORM 0.3.22 turns into a savepoint inside the app's transaction; a version without nested transactions throwsTransactionAlreadyStartedErrorthere and needs a savepoint of its own through the query runner:async link(user: User, identityId: string, provider: string, transaction?: EntityManager): Promise<boolean> { try { // Within the app's transaction this is a savepoint, so a unique violation undoes this update alone. return await (transaction ?? this.manager).transaction(async (manager) => { const result = await manager .createQueryBuilder() .update(User) .set({ zitadelId: identityId }) .where('id = :userId', { userId: user.id }) .andWhere('("zitadelId" IS NULL OR "zitadelId" = :identityId)', { identityId }) .andWhere('NOT EXISTS (SELECT 1 FROM "user" other WHERE other."zitadelId" = :identityId AND other.id <> :userId)') .execute(); return result.affected === 1; }); } catch (error) { // The identity column's own unique index: another transaction linked the identity at the same moment. if (error instanceof QueryFailedError && error.driverError?.constraint === 'UQ_user_zitadelId') { return false; } throw error; } }The unique index covers what the
NOT EXISTScannot: two transactions open at the same time do not see each other's writes, so both could pass it. Catching its violation turns it into a refusal rather than the database's own error. Match the index by its name, so a violation of another unique index on the table still surfaces as the data error it is; name it yourself, such as@Index('UQ_user_zitadelId', ['zitadelId'], { unique: true }), since TypeORM otherwise names it after a hash.The savepoint keeps the app's transaction usable after a violation. Without one, PostgreSQL refuses every further query of that transaction, so
provision()'s read of the owner fails, andprovision()throws that database error instead ofIDENTITY_ALREADY_LINKED. A user object the app loaded before another call linked that user links fine, since the update checks the row, not the object.MySQL refuses a subquery on the table an update writes, so a MySQL store leaves out the
NOT EXISTS, relies on the unique index alone and catches itsER_DUP_ENTRY(errno 1062) instead of23505. The quoted table and column names are the database's; match them to the entity's table and the naming strategy.Provision one user one call at a time. Two
provision()calls for the same user that run at once can both miss the identity at the provider and each create one. The first links its identity; the second getsLINK_REFUSED, and its identity stays at the provider, linked to no one. Run provisioning for a user from one place, such as the job that invites them.create()must be safe to run twice for one identity. Within one app instance the guard runs one sign-in per identity at a time, so parallel requests of a new user wait for a singlecreate(). Two app instances can still each sign the same new identity in. Give the identity column a unique index and return the existing user on a conflict; the store contract checks it.Treat
request.useras read-only. While an identity is cached, all its requests share onerequest.userobject. Keep per-request data elsewhere on the request.A guard injects its providers by the class the app registered. It accepts exactly the instances it passes to
super(), so injectComplianceZitadel, the class listed inforRoot(), not a base class such asZitadelProvider, which Nest cannot inject. A test that replacesComplianceZitadelwithoverrideProviderreplaces it in the guard too.A provider tells an unreachable provider apart from a bad token. The guard passes an exception
identityConnectorExceptionmade fromauthenticate()on unchanged, so a provider throwsidentityConnectorException(PROVIDER_UNREACHABLE)(503) when it cannot reach its identity provider. Anything elseauthenticate()throws, another exception of exception-types included, is a token that is not valid (401), so a bad token never reaches the client as a 500 or a 404. This matters only to an app that writes its own provider.The guard links by email only an identity that has an email. Whether the email must be verified is the store's decision, in
linkByEmail().A store implements what its guard's providers allow.
linkByEmail()andcreate()return null unless the store overrides them, which refuses the sign-in. When a provider the guard accepts haslinkByEmailorcreateOnSignInand the store leaves that method out, the app stops at boot with a message that names both. A guard that writes its ownonModuleInitcallssuper.onModuleInit(), or the check does not run.The guard guards HTTP routes. It reads the
Authorizationheader of an HTTP request.
