You are currently viewing documentation for v1.8 (Beta)

Clients and registration

Register, manage, and authenticate OAuth clients, by hand or dynamically.

An OAuth client is an app that signs users in with your provider or calls your APIs. You can create clients yourself, let signed-in users create them, or let clients register themselves.

Client types

Two properties of a client are independent:

  • Public or confidential (RFC 6749 §2.1). Set token_endpoint_auth_method to "none" for a public client. For a confidential client, use client_secret_basic, client_secret_post, or private_key_jwt.
  • application_type (OIDC Registration §2). web or native. It controls only which redirect URIs the client may register. It defaults to web. For dynamic registration, clientRegistrationDefaultApplicationType sets the default. The "infer" value picks web or native from the redirect URIs. A CIMD document that omits it may register any web or native redirect URI form.

A native client may be confidential, and a web client may be public. A secret shipped inside a mobile, desktop, or single-page app can be extracted, so register such an app as a public client (RFC 8252 §8.5). Use a confidential client only when the secret stays on a server you run.

Manage clients

To create a client owned by the signed-in user, or by the organization that clientReference returns, send the RFC 7591 §2 client metadata.

POST/oauth2/create-client
const { data, error } = await authClient.oauth2.createClient({    redirect_uris: ["https://client.example.com/callback"], // Redirect URIs for the authorization code flow.    client_name: "My Client", // Display name shown on the consent screen.    token_endpoint_auth_method: "client_secret_basic", // How the client authenticates at the token endpoint. Use `"none"` for a public client.    application_type: "web", // Controls redirect URI validation.    scope, // Space-separated scopes the client may request. When omitted, the client may request every scope the server defines.});
Parameters
redirect_urisstring[]

Redirect URIs for the authorization code flow.

client_namestring

Display name shown on the consent screen.

token_endpoint_auth_method"none" | "client_secret_basic" | "client_secret_post" | "private_key_jwt"

How the client authenticates at the token endpoint. Use "none" for a public client.

application_type"web" | "native"

Controls redirect URI validation.

scopestring

Space-separated scopes the client may request. When omitted, the client may request every scope the server defines.

A client that uses client_secret_basic or client_secret_post gets its client_secret only in this response, so store it now. Clients that use any other method, such as none or private_key_jwt, get only a client_id.

Without grant_types, the client gets the authorization_code grant, which requires redirect_uris. A client that uses only another grant, such as client_credentials, can omit redirect_uris.

Most of the other client endpoints take a client_id. Each requires a session, and the table notes the exceptions:

Server methodPathMethodPurpose
getOAuthClient/oauth2/get-clientGETRead a client the user or organization owns.
getOAuthClientPublic/oauth2/public-clientGETRead the public fields to show on the consent page.
getOAuthClientPublicPrelogin/oauth2/public-client-preloginPOSTThe same, on the login page. No session needed. See below.
getOAuthClients/oauth2/get-clientsGETList the clients the user or organization owns.
updateOAuthClient/oauth2/update-clientPOSTUpdate with { client_id, update }.
adminUpdateOAuthClient/admin/oauth2/update-clientPATCHServer only. Also updates restricted fields.
rotateClientSecret/oauth2/client/rotate-secretPOSTIssue a new secret. The old one stops working at once.
deleteOAuthClient/oauth2/delete-clientPOSTDelete the client.

You cannot change token_endpoint_auth_method after creation, and an update cannot set the secret. To retire a secret, rotate it with rotateClientSecret. The new secret keeps the client's client_secret_expires_at.

An update takes the fields from the create request, except jwks, jwks_uri, and subject_type. It ignores those fields, and any other field it does not accept, without returning an error. Only adminUpdateOAuthClient can change dpop_bound_access_tokens. To let a client replace its own inline jwks, see Rotating client keys. Omitted fields keep their current values, with one exception: an update that removes client_credentials from grant_types also clears client_credentials_scopes. Adding the grant back does not restore them, so set them again with adminUpdateOAuthClient. To remove a logout URI, send null for backchannel_logout_uri or frontchannel_logout_uri. Better Auth also clears the matching backchannel_logout_session_required or frontchannel_logout_session_required flag, and the client stops receiving back-channel or front-channel logout notifications.

To read a client's public fields on the login page, set allowPublicClientPrelogin: true, which turns on getOAuthClientPublicPrelogin. The method needs a valid signed oauth_query, and client_id must match the client in that query; a request for any other client gets a 401. Anyone can get a signed query by starting an authorization request, so a client's public fields, including contacts, are readable without an account by anyone who knows its client_id and a registered redirect URI.

Restricted fields

Only the server-only adminCreateOAuthClient and adminUpdateOAuthClient methods can set these fields:

  • skip_consent: skip the consent screen. Use it for trusted clients.
  • enable_end_session: allow the client to end the user's session.
  • require_pkce: create only. Set false to let a confidential client skip PKCE. This removes the protection against intercepted and injected authorization codes. Keep the default, true.
  • client_credentials_scopes: see Client credentials scopes. Protected dynamic registration can also set it through validateInitialAccessToken.
  • resources: create only. Links the client to resources. When resourcePrivileges is set, it must approve the link action for each one.
  • client_secret_expires_at: when a confidential client's secret expires, as Unix seconds or a time span from now such as "90d". 0, the default, means it never expires. Update it to a later time to extend the expiry, or to 0 to remove it. After that time, the token, introspection, and revocation endpoints reject the secret with invalid_client.
  • disabled: update only. Pauses the client.
  • metadata: data attached to the client. The public endpoints do not return it, but the client's owner can read it, and so can members of an owning organization. Do not store secrets here. Fields that extensions declare, such as the backchannel_token_delivery_mode of CIBA (Client-Initiated Backchannel Authentication), are stored here too. A metadata value in adminUpdateOAuthClient replaces the whole stored object, including those fields. Include every key you want to keep. See Client registration metadata.

Both methods:

  • need a signed-in user's session, and you pass its headers
  • run clientPrivileges
  • do not check that the user is an administrator

So call them only from server code that only administrators can reach. When a browser calls that code with its session cookie, check the request's Origin first. adminUpdateOAuthClient also requires the user to own the client, with one exception described in Client CRUD privileges.

The admin update takes the changes under update:

admin-update-oauth.ts
await auth.api.adminUpdateOAuthClient({
  headers: request.headers,
  body: {
    client_id: "client-id",
    update: {
      skip_consent: true, 
      enable_end_session: true, 
    },
  },
});

To pause a client without deleting it, set disabled: true, and set false to resume. A disabled client cannot obtain new tokens, and introspection reports its existing tokens as inactive. A JWT access token stays valid until it expires. If your resource server verifies JWTs locally and needs an immediate cut-off, it must check the client itself.

Client credentials scopes

A client cannot use the client_credentials grant until you allow it, and its scope does not apply to that grant. To allow it:

  1. Define clientPrivileges so that it approves the configure-client-credentials-scopes action.
  2. Set a non-empty client_credentials_scopes with adminCreateOAuthClient or adminUpdateOAuthClient. The client must be confidential and list client_credentials in grant_types. Each scope must be in scopes, and cannot be openid, profile, email, or offline_access.

A token request can ask for any of these scopes. When it omits scope, it gets all of them.

Besides the admin methods, the only way to set this list is protected dynamic registration: validateInitialAccessToken can return it for the token it accepts. See Enrolling agents and devices. Otherwise, dynamic registration, CIMD, and createOAuthClient can declare the grant but cannot set this list.

Dynamic client registration

To let clients register themselves, set allowDynamicClientRegistration. Better Auth then accepts registrations at POST /oauth2/register (RFC 7591 §3). By default, the caller needs a session and the create privilege.

auth.ts
oauthProvider({
  allowDynamicClientRegistration: true, 
})

To also let clients register without signing in, set allowUnauthenticatedClientRegistration: true next to allowDynamicClientRegistration. Anyone on the internet can then register a client:

  • The registrant chooses the client's name, logo, and redirect URIs.
  • The client has no owner, so nobody can manage it through the client endpoints.
  • The client cannot use client_credentials.

Prefer CIMD or initial access tokens. If you enable open registration, keep rate limiting on.

To register from the client app, call authClient.oauth2.register({ client_name, redirect_uris }). The response holds the new client_id. A client that uses client_secret_basic or client_secret_post also gets its client_secret. Only this response carries it, so store it now.

For public clients that are not registered in advance, such as MCP clients, prefer Client ID Metadata Documents. The client hosts its metadata at an HTTPS URL, and that URL is its client_id.

To let software register without a user session, define validateInitialAccessToken. It receives initialAccessToken (the token from Authorization: Bearer <token>), the request headers, and the requested clientMetadata. Return false to reject the request with 401 invalid_token, or an object to accept it. The object can hold:

  • referenceId: sets the owner, such as an organization ID. Without it, the client is unowned.
  • clientCredentialsScopes: lets the client use the client_credentials grant. The client registers with this list as its client credentials scopes, as if an administrator had assigned it. Return only scopes the token's issuer approved, because the token is the only record of that approval.

Registration with clientCredentialsScopes fails unless:

  • the client registers the client_credentials grant with a confidential authentication method, and
  • every scope is one the provider offers and is not user-delegated (openid, profile, email, or offline_access).

The registration request itself can never set these scopes. While the callback is undefined, a Bearer token sent to /oauth2/register is rejected.

Keep in mind:

  • Compare the token in constant time.
  • Treat clientMetadata as untrusted: it is self-asserted and not yet fully validated.
  • You issue and revoke these tokens in your app (RFC 7591 §3).
  • With the Bearer plugin, a Bearer value that resolves to a session counts as that session, not as an initial access token.

The registration options:

OptionDefaultEffect
clientRegistrationDefaultScopesscopesScopes every registered client may request.
clientRegistrationAllowedScopesnoneExtra scopes added to the defaults.
clientRegistrationClientSecretExpirationneverThe client_secret_expires_at value returned to dynamically registered clients that receive a secret. A string such as "30d" is a duration from registration. A number (Unix seconds) or a Date is a fixed time. After that time, the secret is rejected with invalid_client, so the client must register again unless you extend the expiry with adminUpdateOAuthClient.
clientRegistrationRequirePKCEtrueSet false to let registered confidential clients skip PKCE, which removes the protection against intercepted and injected codes. Public clients always need PKCE.
clientRegistrationDefaultApplicationType"web"application_type for a registration that omits it: "web", "native", or "infer" (native when any redirect URI is a custom scheme or http loopback).

Dynamic and CIMD registrations store the whole set of default and allowed scopes on every client. A scope in the registration request is only checked against that set, not stored. The default is scopes, which is every scope your server defines. When you enable open registration, set clientRegistrationDefaultScopes to the smallest set those clients need.

Registration keeps only the requested grant_types the server supports and returns what it registered (RFC 7591 §3.2.1). createOAuthClient and adminCreateOAuthClient reject an unsupported grant instead. A registration with no supported grant fails with invalid_client_metadata. To fix it, the registrant requests a grant listed in the provider's grant_types_supported metadata, or you add the grant to grantTypes. sector_identifier_uri is not supported.

Resources for registered clients

By default, a registration cannot request resources. To let registered clients request them, use these options:

  • clientRegistrationDefaultResources links every new client to these resources, including CIMD and admin-created clients, without a resourcePrivileges check.
  • clientRegistrationAllowedResources lists extra resources a registration may request.

Every value must also be in resources. A requested resource outside both lists, or one that is missing or disabled, fails with invalid_target. Its error_description names the resource and says which of these applies. The response lists the linked resources.

auth.ts
oauthProvider({
  resources: ["https://api.example.com/default", "https://api.example.com/optional"],
  clientRegistrationDefaultResources: ["https://api.example.com/default"], 
  clientRegistrationAllowedResources: ["https://api.example.com/optional"], 
})

Enrolling agents and devices

Use this when software of yours runs outside your service and must call your API for an organization on its own. Examples are a sync or monitoring agent on a customer's server, a plugin on a self-hosted platform, or a signage screen. Each install gets its own client, owned by the organization, and nobody copies a secret:

  1. The install starts a device authorization and shows the user code.
  2. An organization administrator approves it on your consent page, after picking the organization on your post-login page.
  3. The install receives a short-lived registration token and uses it as the initial access token to register its own client.
  4. The client uses client_credentials from then on, even if the administrator leaves the organization.

Approval creates a credential that acts for the whole organization and outlives the approver. A phished approval or a stolen key therefore costs more than a stolen user token. Don't use this flow for:

  • A tool each person runs for themselves. Use the device code grant directly.
  • An app that serves several organizations. Register one client.
  • AI agents acting for users. Give them each user's own tokens.
  • Machines that run untrusted code, such as CI runners, or devices in public places, such as payment terminals.
  • High-value scopes, such as admin or payment access. Have an administrator issue the initial access token from your app instead.

Add oauthDeviceAuthorization({ expiresIn: "5min" }) and a post-login page whose consentReferenceId returns the chosen organization. Then configure the provider:

auth.ts
const registrationResource = "https://auth.example.com/connector-registration";

oauthProvider({
  allowDynamicClientRegistration: true,
  scopes: ["openid", "connector:register", "invoices:write"],
  // Registration tokens only work here and expire after 5 minutes
  resources: [{
    identifier: registrationResource,
    allowedScopes: ["connector:register", "invoices:write"],
    accessTokenTtl: 300,
  }],
  // Deleting a client does not invalidate tokens it already holds
  m2mAccessTokenExpiresIn: 600,
  validateInitialAccessToken: async ({ initialAccessToken }) => {
    // Your own helpers: verify the token, use it once, recheck the admin
    const token = await verifyRegistrationToken(initialAccessToken);
    if (!token || !(await markRegistrationTokenUsed(token.jti))) return false;
    if (!(await isOrganizationAdmin(token.sub, token.reference_id))) return false;
    return {
      referenceId: token.reference_id, 
      // Only machine scopes the administrator approved
      clientCredentialsScopes: token.scopes.filter((scope) => scope === "invoices:write"), 
    };
  },
})

verifyRegistrationToken verifies the access token as a JWT against auth.api.getJwks(), with your JWT plugin's issuer and registrationResource as audience. It also checks that azp is the installer client and that scope includes connector:register.

Create one public installer client with adminCreateOAuthClient and share its client_id with every install. Give it:

  • token_endpoint_auth_method: "none"
  • the urn:ietf:params:oauth:grant-type:device_code grant
  • scope: "connector:register invoices:write"
  • resources: [registrationResource]. Without the resource link, device requests fail with invalid_target.

The install requests a device code with that client_id, scope: "connector:register invoices:write", and resource: registrationResource. Requesting the machine scopes here lets the administrator see them. The install shows the code and polls the token endpoint. It then registers with:

  • the token as Authorization: Bearer
  • token_endpoint_auth_method: "private_key_jwt", with its public key in jwks
  • grant_types: ["client_credentials"]

Keep the private key in the platform's key store.

Keep these protections:

  • Say what approval does. Your consent page must state that approving creates a credential that acts for the organization with the listed scopes and keeps working after the approver leaves.
  • Approved scopes only. Take machine scopes from the token's scope, never from the registration request.
  • Single use. Reject a registration token whose jti was already used.
  • Recheck the administrator. Their role can change between approval and registration.
  • Tell the organization. Notify its administrators of each new enrollment, and record who approved it (the token's sub).
  • Device code phishing. Every install shares the installer client, so anyone can start a flow and send an administrator its code (RFC 8628 §5.4). Show the user code on your consent page, and tell administrators to approve only a code their own install displays.
  • Copied installs. A copy, such as a staging clone of the install's database, carries the original client's key. Make the copy discard it and enroll again.

Redirect URI forms

application_type decides which redirect URIs a client may register (OIDC Registration §2, RFC 8252 §7):

FormExamplewebnative
HTTPS on a non-loopback hosthttps://app.example.com/callbackYesYes
HTTP loopback, any port (RFC 8252 §7.3)http://127.0.0.1:8787/callbackNoYes
Reverse-domain private-use scheme (RFC 8252 §7.1)com.example.app:/callbackNoYes
Custom scheme with a host and a pathmyapp://example.app/callbackNoYes

An HTTP loopback URI must use exactly localhost, 127.0.0.1, or [::1], so spellings such as 127.1 are rejected. HTTPS on a loopback address and HTTP on any other host are also rejected. To accept HTTP on other hosts, or HTTP loopback for web clients, see HTTP redirect URIs. Better Auth also rejects fragments, credentials, malformed URIs, and reserved schemes such as javascript: and file:.

RFC 8252 §8.4 says to reject private-use schemes without a period, but Better Auth accepts them for native app compatibility. Another app can claim such a scheme and receive the code, so keep PKCE on for these clients.

Custom redirect URI validation

A requested redirect URI must match a registered one exactly. Exact matching keeps an attacker from redirecting the authorization code to a URI the client did not register. The only exception is the port of a native client's loopback URI. For example, a registered http://127.0.0.1:8787/callback also matches http://127.0.0.1:51234/callback, but http://localhost:51234/callback does not.

To change which URIs are accepted, set validateRedirectUri. It receives the requested URI, the client's registered URIs, and defaultResult from the built-in match. It returns true to accept the URI. Its result replaces the built-in match, so return defaultResult for URIs you do not handle:

auth.ts
oauthProvider({
  validateRedirectUri: (uri, registeredUris, defaultResult) => {
    if (defaultResult) return true;
    if (!registeredUris.includes("https://app.example.com/api/auth/callback")) return false;
    try {
      const url = new URL(uri);
      return url.protocol === "https:" && url.port === "" && url.search === "" &&
        url.hostname.endsWith(".preview.example.com") &&
        url.pathname === "/api/auth/callback";
    } catch {
      return false;
    }
  },
})

Before the callback runs, Better Auth rejects only malformed URIs, credentials, fragments, dangerous schemes such as javascript:, and HTTP on hosts other than loopback unless allowInsecureRedirectUri accepts it. The redirect URI form rules do not apply to URIs the callback accepts. The callback applies to every client. Returning false or throwing rejects the URI and sends early authorization errors to the server error page instead of the client.

Accepting extra URIs relaxes the exact matching of RFC 9700 §2.1. Accept only hosts you control that untrusted people cannot deploy to, and pin the scheme, host suffix, port, path, and query. If untrusted clients can register arbitrary URIs, a match in registeredUris does not prove which client it is.

With pairwise subject identifiers, a URI the callback accepts does not change the client's sector, which comes from its registered redirect URIs. The client receives the same sub for a user whichever accepted URI it uses.

HTTP redirect URIs

By default, http redirect URIs and post-logout redirect URIs are accepted only on loopback hosts, and web clients cannot use loopback hosts at all. A deployment served over plain HTTP on a private network, such as http://192.168.1.50:8000 or http://app.homelab.lan, can't register its callbacks, and neither can a web client on localhost during development.

To accept them, set allowInsecureRedirectUri. When the default policy rejects an http URI, it receives the parsed URL and returns true to accept it. Returning anything else, or throwing, keeps the URI rejected:

auth.ts
oauthProvider({
  allowInsecureRedirectUri: (url) => url.origin === "http://192.168.1.50:8000", 
})

To allow localhost callbacks for web clients in development only:

auth.ts
oauthProvider({
  allowInsecureRedirectUri: (url) =>
    process.env.NODE_ENV !== "production" && url.hostname === "localhost", 
})

The callback applies at client registration and updates (redirect_uris and post_logout_redirect_uris), at the authorize endpoint, and at the end-session endpoint. Removing or narrowing it stops redirects to http URIs registered under it. It does not change matching: a web client on a loopback host must use the registered port, and native clients keep the exact loopback host rule. Credentials, fragments, and dangerous schemes are always rejected. backchannel_logout_uri and frontchannel_logout_uri are not affected, so an http logout URI must still be on a loopback host.

When the authorize endpoint rejects an http redirect URI, it shows the server error page with invalid_request instead of sending the error to that URI.

Over plain HTTP, anyone on the network path can read authorization codes and post-logout redirects. Accept only exact origins you control, especially with dynamic client registration, because the callback also decides what registering clients may submit.

Private key JWT

With private_key_jwt, the client authenticates with a JWT signed by its own key instead of a secret (RFC 7523 §3, OIDC Core §9). To use it, register the client's public keys as jwks or jwks_uri, not both:

admin-create-oauth.ts
await auth.api.adminCreateOAuthClient({
  headers: request.headers,
  body: {
    redirect_uris: ["https://app.example.com/callback"],
    token_endpoint_auth_method: "private_key_jwt",
    jwks: { keys: [{ kty: "EC", crv: "P-256", kid: "key-1", x: "...", y: "..." }] },
  },
});

Prefer inline jwks for clients whose host you do not control.

  • jwks must be a JWK Set object with a non-empty keys array of public signing keys. EC keys use P-256, P-384, or P-521, and OKP keys use Ed25519.
  • jwks_uri must be an HTTPS URL on a public host. Its origin must be in trustedOrigins, unless it matches the origin of a CIMD client_id. trustedOrigins applies to the whole app. That origin is then also trusted for redirects and requests.

The client sends client_assertion_type=urn:ietf:params:oauth:client-assertion-type:jwt-bearer and the signed client_assertion instead of a secret. The assertion is signed with RS256, RS384, RS512, PS256, PS384, PS512, ES256, ES384, ES512, or EdDSA, and must contain:

ClaimRequirement
issThe client_id
subThe client_id
audThe URL of the endpoint that receives the assertion, or the provider's issuer
expRequired. At most assertionMaxLifetime (default 300 seconds) from now
jtiRequired. A unique value for each assertion
iatOptional. When present, not older than assertionMaxLifetime

Rotating client keys

To let a client with inline jwks replace them without a user session, set allowClientKeyRotation: true. The client then calls POST /oauth2/client/rotate-keys. The request body holds client_assertion, client_assertion_type, and the complete new jwks. The assertion must be signed by a current key, and its aud must be the rotation endpoint URL.

Any key left out of the new set stops working at once. To roll a key without downtime, first send the old and new keys, then send only the new one. A request that loses a race fails with 409, or 401 if its key was already removed.

The provider refuses to start with this option on the memory adapter or with advanced.database.generateId: "serial", because neither enforces single-use assertions.

Trusted clients

To skip database lookups for first-party apps whose redirect URIs you control, list their client IDs in cachedTrustedClients. To also skip the consent screen, set skip_consent on each client.

A skip_consent client gets authorization codes for any signed-in user without asking them, unless the authorization request sets prompt=consent. Whoever starts the flow chooses prompt, so whoever controls the client's redirect URIs controls those codes. The client's owner can still change redirect_uris through updateOAuthClient. With clientReference, that owner is an organization, and any member of it can make the change. Set skip_consent only on clients in cachedTrustedClients, which the client endpoints cannot change, or deny update for those clients in clientPrivileges. Do not set it on a public native client. Any app on the device can start the flow and receive the redirect, and PKCE does not help when the attacker starts the flow.

  • Each server keeps the listed clients in memory until it restarts.
  • The client endpoints, including the admin methods, cannot change them.
  • To disable one or change its redirect URIs, edit its database row and restart every instance.
auth.ts
oauthProvider({
  cachedTrustedClients: new Set(["internal-dashboard", "mobile-app"]), 
})

Client CRUD privileges

To limit which client actions a signed-in user may take, define clientPrivileges. Without it, every signed-in user may take every action except configure-client-credentials-scopes. When it is set, return true to allow an action and false or undefined to deny it. A denied action fails with 401.

The default lets any signed-in user create OAuth clients, through createOAuthClient or through dynamic registration with a session. If your app allows open sign-up, anyone can then create a client with a name, logo, and redirect URIs they choose and show it on your consent page. A client created without scope may request every scope the server defines. Define clientPrivileges so that only trusted users can create.

It receives action (create, read, update, delete, list, rotate, or configure-client-credentials-scopes), user, session, headers, and, for an existing client, clientId. clientId comes from the request. It does not prove that the client exists or who owns it.

Ownership is checked after this callback, so returning true does not grant access to another owner's client. There is one exception. An adminUpdateOAuthClient call that changes only client_credentials_scopes can change another owner's client when the callback approves both update and configure-client-credentials-scopes.

auth.ts
oauthProvider({
  clientPrivileges: async ({ headers, session }) => {
    if (!session?.activeOrganizationId) return false;
    const member = await auth.api.getActiveMember({ headers });
    return member?.role === "owner";
  },
})

Organizations

To make an organization own new clients instead of the user, set clientReference. It receives the signed-in user and session. It returns the owner's ID, or undefined to make the user the owner. A client's owner is set at creation and never changes. This example returns the active organization:

auth.ts
oauthProvider({
  clientReference: ({ session }) =>
    (session?.activeOrganizationId as string | undefined) ?? undefined,
})

The active organization can outlive membership. clientPrivileges runs first and receives the request headers, so check membership there, as in the example above.

An organization can relate to a client in two ways:

  • It uses the client. Many organizations share one unowned client, such as a third-party app or a CIMD client. Each consent records the organization it was given for.
  • It owns the client. Its members manage the client through the endpoints above, including its redirect URIs. Give ownership only to an organization that controls the client.

An organization uses the client

To record consent per organization, return the organization from postLogin.consentReferenceId, as in Post-login screen. Then customAccessTokenClaims receives it as referenceId, but the ID token and UserInfo callbacks do not:

auth.ts
oauthProvider({
  // postLogin: see Post-login screen
  customAccessTokenClaims: ({ referenceId }) => ({ "https://example.com/org": referenceId }),
})

The provider also puts the organization in the access token as the reference_id claim. A client can also name the organization in its authorization request, or your consent page can ask for it. See Organization from the request or the consent page.

Deleting a consent removes only that organization's consent and does not revoke issued tokens. To add organization claims per client, see Client-specific access token claims.

An organization owns the client

A member who creates a client, or registers one with a session, makes it owned by the organization clientReference returns. For software that registers itself, have an organization admin issue an initial access token in your app and return the organization from validateInitialAccessToken:

auth.ts
oauthProvider({
  allowDynamicClientRegistration: true,
  validateInitialAccessToken: async ({ initialAccessToken }) => {
    const token = await findRegistrationToken(initialAccessToken); // your lookup
    return token ? { referenceId: token.organizationId } : false;
  },
})

A client has no owner in these cases:

  • It came from open registration or a CIMD document.
  • It registered with an initial access token whose validation returned no referenceId.
  • It has a referenceId, but clientReference is not configured.

The client endpoints treat such a client as nobody's:

  • Listing never returns it.
  • Reading, updating, disabling, deleting, or rotating its secret returns 401.
  • Only the client_credentials_scopes admin update in Client CRUD privileges can change it.

Manage it in the database instead.

Software that each organization runs as its own client should register with an initial access token instead, as in Enrolling agents and devices.