For AI agents: the complete documentation index is available at https://dotpress.dev/llms.txt, the full documentation bundle is available at https://dotpress.dev/llms-full.txt, and this page is available as Markdown at https://dotpress.dev/auth/sso.md.

Enterprise SSO (OIDC and SAML)

sso logs the users of a tenant in with the identity provider (IdP) of their organization: Okta, Microsoft Entra ID, Google Workspace, Keycloak, ADFS… over OpenID Connect or SAML 2.0. The app owns the connections, one or more per tenant, and decides which user each login resolves to; Dotpress runs the flows, checks the answers of the IdPs, links the IdP accounts to the users (the identities) and opens the sessions. A connection can also be enforced for an email domain: its addresses then log in with their IdP only.

OpenID Connect is built in, with oauth4webapi; SAML comes from createSamlProtocol() of @dotpress/auth/saml, with @node-saml/node-saml, on Node.js only. Both are optional peer dependencies:

pnpm add oauth4webapi
pnpm add @node-saml/node-saml # for SAML connections

sso needs secrets.keys (the state of a flow is encrypted), redirects.allowed (the pages the flows end on), rateLimits (its store remembers the states already used), the identities, users.findAccount(), users.setPasswordHash() and users.markEmailVerified() stores, the delete methods of the optional stores the data provider has (passkeys.list() and delete(), mfa.listFactors(), deleteFactor() and deleteRecoveryCodes(), trustedDevices.revokeAll(): the claim of an unverified account), and, with SAML, a replayStore.

Setup

Static connections

import { createMemoryRateLimitStore } from '@dotpress/core'
import { createSamlProtocol } from '@dotpress/auth/saml'
import { createSso, ssoRejected } from '@dotpress/auth/sso'

createAuth({
  // …
  secrets: { keys: [{ id: '1', key: process.env.SECRET_KEY }] },
  redirects: { allowed: ['https://app.example.com'] },
  sso: createSso({
    baseUrl: 'https://api.example.com/auth',
    connections: [
      {
        id: 'acme-okta',
        protocol: 'oidc',
        issuer: 'https://acme.okta.com',
        clientId: process.env.ACME_CLIENT_ID,
        clientSecret: process.env.ACME_CLIENT_SECRET,
        enabled: true,
      },
      {
        id: 'globex-adfs',
        protocol: 'saml',
        idpEntityId: 'http://adfs.globex.com/adfs/services/trust',
        idpSsoUrl: 'https://adfs.globex.com/adfs/ls/',
        idpCertificates: [process.env.GLOBEX_IDP_CERTIFICATE],
        trustEmail: true, // the IdP verifies the addresses it sends
        enabled: true,
      },
    ],
    protocols: [createSamlProtocol()],
    replayStore: createMemoryRateLimitStore(), // of @dotpress/core; a shared store with several instances
    resolveUser: async ({ connection, profile, existingUserId }) => {
      if (existingUserId) return { userId: existingUserId }
      // Trust an address only when the IdP verified it, in the domain of the connection.
      const domain = { 'acme-okta': 'acme.com', 'globex-adfs': 'globex.com' }[connection.id]
      if (!profile.email || !profile.emailVerified) throw ssoRejected('EMAIL_NOT_VERIFIED')
      if (profile.email.split('@')[1] !== domain) throw ssoRejected('FOREIGN_DOMAIN')
      const user = await db.users.upsertMember(connection.id, profile.email)
      return { userId: user.id, created: user.created }
    },
  }),
})

Connections per tenant

A SaaS keeps its connections in a table, edited by the admins of each tenant: findConnection loads one per login, instead of connections. It returns undefined for an unknown id.

createSso({
  baseUrl: 'https://api.example.com/auth',
  findConnection: (id) => db.ssoConnections.find(id),
  discover: async (email) => {
    const domain = await db.ssoDomains.find(email.split('@')[1])
    return domain && { connectionId: domain.connectionId, enforced: domain.enforced }
  },
  resolveUser,
  protocols: [createSamlProtocol()],
  replayStore: redisStore,
  fetch: safeFetch, // the tenants choose the issuers: see "Issuers chosen by the tenants"
})
OptionDefaultDescription
connections—The connections, with distinct ids. Give connections or findConnection, not both.
findConnection—(connectionId) => Promise<SsoConnection | undefined>: the connection of an id, loaded per login.
resolveUser—The user of a login. See Resolving the user. Required.
baseUrl—Public URL of the auth routes, like https://api.example.com/auth: https, or http for localhost and 127.0.0.1 only; no query nor hash. The routes of a connection are under <baseUrl>/sso/<connectionId>. Required.
discover—(email) => Promise<{ connectionId, enforced } | undefined>: the connection of an address, usually by its domain, and its enforcement. Receives a trimmed, lowercase address. See Discovery and enforcement.
trustIdpMfafalseA multi-factor authentication reported by the IdP counts as MFA. See MFA of the IdP.
replayStore—A RateLimitStore that remembers the SAML assertions already used, each until its end. Required with createSamlProtocol(): a shared store with several instances, createMemoryRateLimitStore() for a single one. See Replays.
protocols—The protocols besides OpenID Connect: [createSamlProtocol()] for SAML connections.
fetchfetchThe fetch of the requests to the OpenID Connect IdPs: a proxy, the tests, or a fetch restricted to public addresses when the tenants choose the issuers.

A connection id has 1 to 128 letters, digits, _ and -, like acme-okta: it appears in the URLs. Only an enabled connection logs in; the others answer SSO_NOT_CONFIGURED, as an unknown id does.

createSso() throws a TypeError for an invalid or unknown option, and without replayStore when protocols has SAML; it checks the static connections at startup. A connection of findConnection is checked at each load: an unknown field, an invalid value or another id throw a TypeError. The errors name the fields, never their values. createAuth() throws without secrets.keys or redirects.allowed, and with rateLimits: false: turn the limits off one by one instead (rateLimits: { sso: { ip: false, callbackIp: false } }).

Connections

OpenID Connect

FieldDescription
idThe connection id.
protocol'oidc'
issuerThe issuer of the IdP (https), discovered from <issuer>/.well-known/openid-configuration.
clientId, clientSecretThe client registered at the IdP.
scopesDefaults to ['openid', 'email', 'profile']; must include openid.
trustEmailThe IdP verifies the addresses it sends, but its ID tokens have no email_verified claim: the profile gets emailVerified: true with an email when the claim is absent. An email_verified other than true still leaves the address unverified. Defaults to false.
enabledWhether the connection logs in.

Register the redirect URI <baseUrl>/sso/<id>/oidc/callback at the IdP: https://api.example.com/auth/sso/acme-okta/oidc/callback.

Every flow uses the authorization code with PKCE, a state and a nonce. The ID token comes from the token endpoint, and its signature (the JWKS of the issuer), issuer, audience, expiration and nonce are checked. The profile has the sub as subject, the email claim, emailVerified only when the email_verified claim is true (or absent, with trustEmail), and the amr claim for the MFA of the IdP.

The requests to the IdP (discovery, JWKS, token endpoint) follow no redirect, time out after 5 seconds and read 256 KiB at most; the jwks_uri must be https. The discovery documents and the key sets are cached 1 hour, for 100 issuers at most.

Issuers chosen by the tenants

With findConnection, the admins of a tenant may enter the issuer: the API then sends requests to an address of their choice. Give createSso() a fetch that refuses the private, loopback and link-local addresses (server-side request forgery), like src/safe-fetch.ts of the SaaS authentication example, or a proxy that restricts the egress.

SAML 2.0

FieldDefaultDescription
id—The connection id.
protocol—'saml'
idpEntityId—The entity ID (issuer) of the IdP.
idpSsoUrl—The single sign-on URL of the IdP (HTTP-Redirect binding), https.
idpCertificates—The signing certificates of the IdP, PEM or base64. Several during a rotation.
signRequestsfalseSigns the AuthnRequests, with the signingKey of createSamlProtocol().
wantAssertionsSignedtrueRequires a signed assertion; false also accepts an assertion covered by a signed response.
allowIdpInitiatedfalseAccepts the responses without AuthnRequest (IdP-initiated). See IdP-initiated logins.
trustEmailfalseThe IdP verifies the addresses it sends: the profile gets emailVerified: true with an email.
enabled—Whether the connection logs in.

Give the IdP the URLs of the connection, or its metadata:

URL
Assertion Consumer Service (HTTP-POST)<baseUrl>/sso/<id>/saml/acs
Entity ID (audience) of the service provider<baseUrl>/sso/<id>/saml/metadata
MetadataGET <baseUrl>/sso/<id>/saml/metadata

Resolving the user

resolveUser decides who logs in, at each login, with:

FieldDescription
connectionThe connection of the login.
profileThe user at the IdP: subject (sub, or a persistent NameID), email (trimmed, lowercase), emailVerified (email_verified for OpenID Connect, or its absence with trustEmail; trustEmail for SAML), name, attributes (the claims of the ID token, or the SAML attributes), mfa.
existingUserIdThe user already linked to this IdP account, if any.
providerThe provider id of the identity: sso:<connectionId>.

It returns { userId, created? }: the linked user, an account of the tenant with this address, or a new account (just-in-time provisioning), with created: true to record user.signed_up. The app creates the accounts itself, in its tenant, with its roles: the sign-up settings of the auth do not apply. An existing account returned without this identity is claimed when it is unverified, as by a magic link: its password is removed, its sessions are revoked (reason account_claimed), and its passkeys, linked identities, second factors, recovery codes and trusted devices are removed. It throws ssoRejected(reason) to refuse the login, answered 403 SSO_REJECTED with data.reason:

import { ssoRejected } from '@dotpress/auth/sso'

const resolveUser: SsoOptions['resolveUser'] = async ({ connection, profile, existingUserId }) => {
  const tenant = await db.tenants.findByConnection(connection.id)
  if (existingUserId) return { userId: existingUserId }
  if (!profile.email || !profile.emailVerified) throw ssoRejected('EMAIL_NOT_VERIFIED')
  // A domain whose ownership the tenant proved (DNS record), never one it only typed.
  if (profile.email.split('@')[1] !== tenant.verifiedDomain) throw ssoRejected('FOREIGN_DOMAIN')
  const member = await db.members.findByEmail(tenant.id, profile.email)
  if (member) return { userId: member.userId }
  if (!tenant.provisioning) throw ssoRejected('NOT_A_MEMBER')
  const user = await db.users.create({ tenantId: tenant.id, email: profile.email, name: profile.name })
  return { userId: user.id, created: true }
}

An IdP account links to one user. When resolveUser returns another user than the linked one, the identity moves to it; an IdP account already linked elsewhere answers SSO_REJECTED with the reason IDENTITY_TAKEN.

Trust an address only for the domains the connection owns

An IdP vouches for its own users, not for any address: the IdP of a tenant can send ceo@other-company.com. Match an existing account by its address only when the IdP verified it (profile.emailVerified) and its domain belongs to the tenant of the connection. When the tenants enter their own domains or IdPs, prove the ownership of each domain (a DNS record, an email to the domain) before trusting it: otherwise a tenant can claim the domain of another one, and log in to its accounts.

Discovery and enforcement

With discover, the login page asks the connection of an address before asking a password:

RouteBodyAnswer
POST /auth/sso/discover{ email }{ connectionId, enforced }, or { connectionId: null }. 30 per 15 minutes per IP (rateLimits.sso.ip).
const { connectionId } = await post('/auth/sso/discover', { email })
if (connectionId) location.href = `${api}/auth/sso/${connectionId}/start?redirectTo=${app}/home`

A routing with enforced: true blocks the other ways in for its addresses:

  • A login with another method (password, magic link, passkey, OAuth…) is refused after its first factor with 403 SSO_REQUIRED and data.connectionId, and records login.failed with the reason sso_required (onLoginFailed gets the errorType sso_required). Impersonations and generateTokensForUser() are not blocked.
  • The password reset, the magic link and the sign-up of such an address answer 403 SSO_REQUIRED, instead of their neutral answer: the routing of a domain is public. So do the email change to or from such an address, and the social login that would link or create its account.
  • The sessions opened before the enforcement go on, and their refreshes too: revoke them (auth.revokeUserSessions(userId)) when you enforce a domain.

Login

A link to the start route begins the flow:

<a href="https://api.example.com/auth/sso/acme-okta/start?redirectTo=https://app.example.com/home">Log in with Acme</a>
RouteQuery or bodyAnswer
GET /auth/sso/:connectionId/start?redirectTo&mode&codeChallenge302 to the IdP. 30 per 15 minutes per IP (rateLimits.sso.ip). 404 SSO_NOT_CONFIGURED for an unknown or disabled connection. With mode=body and handoff.pkce: 'required', 400 CODE_CHALLENGE_REQUIRED without a valid codeChallenge.
GET /auth/sso/:connectionId/oidc/callbackThe parameters of the IdPA redirect to redirectTo. The callbacks without a valid state (missing, invalid, expired or already used) count against 30 per 15 minutes per IP (rateLimits.sso.callbackIp), before the connection is loaded, then answer 429 TOO_MANY_REQUESTS; the callbacks of valid flows are not counted, so that clients sharing an address (no getIp behind a proxy) never block each other's logins.
POST /auth/sso/:connectionId/saml/acsThe form of the IdP (SAMLResponse)A redirect to redirectTo, limited as the OpenID Connect callback: an IdP-initiated response, which has no state, counts before it is read
GET /auth/sso/:connectionId/saml/metadata—The metadata of the service provider (application/samlmetadata+xml)

redirectTo must match redirects.allowed; otherwise the flow ends on the first allowed URL. A flow lasts 10 minutes. The callback redirects to redirectTo with:

  • the auth cookies (mode=cookie);
  • ?challenge=<challengeToken>: the user has a second factor, to verify with POST /auth/mfa/verify (see MFA);
  • ?code=<code>: a handoff code (mode=body), to exchange with POST /auth/token, with the PKCE verifier of codeChallenge;
  • ?error=<CODE>: the flow failed, like ?error=SSO_REJECTED. An invalid, expired or already used state ends on the first allowed URL with ?error=OAUTH_STATE_INVALID.

The page that reads ?challenge= or ?code= removes it from the address bar (history.replaceState()).

mode is cookie with the cookie mode, body with handoff; it defaults to cookie when both are on. Without either, the start route is not registered. The flow works as the social login one.

The session has the method sso and the amr fed. The account gate, beforeSession and MFA apply as for a password login. A trusted device skips the second factor of an OpenID Connect login; a SAML response is a cross-site POST, which the trusted device cookie does not follow: SAML logins ask the second factor.

MFA of the IdP

With trustIdpMfa: true, a login whose IdP reports a multi-factor authentication gets the amr fed and mfa: requireMfa() accepts it. The IdP reports it with the amr claim of the ID token (mfa, otp, hwk…), or the AuthnContextClassRef of the SAML assertion (https://refeds.org/profile/mfa, http://schemas.microsoft.com/claims/multipleauthn, or a class with MultiFactor). Turn it on only for IdPs that enforce their MFA. Without it, profile.mfa stays available to resolveUser.

SAML

createSamlProtocol() of @dotpress/auth/saml adds the SAML connections, on Node.js only. The AuthnRequests use the HTTP-Redirect binding; the responses, the HTTP-POST binding.

import { createSamlProtocol } from '@dotpress/auth/saml'

createSamlProtocol({
  signingKey: process.env.SAML_SIGNING_KEY,
  signingCertificate: process.env.SAML_SIGNING_CERTIFICATE,
  clockSkew: '2m',
})
OptionDefaultDescription
signingKey—RSA private key of the service provider (PKCS#8 PEM): signs the AuthnRequests of the connections with signRequests.
signingCertificate—The certificate of signingKey (PEM), published in the metadata of the connections with signRequests.
clockSkew'2m'The clock difference tolerated with the IdPs.

A response is accepted when:

  • its status is Success, and its Destination, when present, is the ACS of the connection;
  • it answers the AuthnRequest of the flow (InResponseTo), or none for an allowed IdP-initiated login;
  • its assertion is signed (or covered by a signed response, with wantAssertionsSigned: false) with a certificate of idpCertificates, with signature and digest algorithms of SHA-256 or stronger (SHA-1 is refused), and comes from idpEntityId, for the entity ID of the connection;
  • a bearer subject confirmation targets the ACS and the request, within its validity, clockSkew tolerated;
  • its assertion was never used before;
  • its NameID is not transient: a transient NameID changes at each login, and cannot identify an account.

Anything else answers SSO_ASSERTION_INVALID. Document type declarations are refused.

The profile has the NameID as subject. The email is the NameID with the emailAddress format, or the email, mail or emailaddress claim attribute; it counts as verified (emailVerified) only with the trustEmail field of the connection, for an IdP that verifies the addresses it sends. The name comes from displayName or name, or givenName and sn.

Certificate rotation

idpCertificates takes several certificates: add the new one of the IdP before its switch, and remove the old one after it.

Signed requests

With signRequests: true, the AuthnRequests are signed with signingKey, and the metadata publishes signingCertificate. A connection with signRequests and no signingKey throws a TypeError at its start, and its metadata throws without signingCertificate.

IdP-initiated logins

A login started from the portal of the IdP posts a response without AuthnRequest and without state cookie. Only a connection with allowIdpInitiated: true accepts it, and it ends on the first URL of redirects.allowed, in the cookie mode when it is on, with a handoff code otherwise. A handoff code without codeChallenge needs handoff.pkce: 'optional': with 'required', the response ends with ?error=CODE_CHALLENGE_REQUIRED. These responses cannot be tied to a browser: keep the option off unless a tenant needs it.

Replays

Each assertion is accepted once: its ID is kept in replayStore until its end. createSso() requires it with SAML, and does not fall back to rateLimits.store: a memory store evicts its oldest keys, and the counters of the rate limits could push the IDs out. With several instances, use a shared store: see A shared store.

Cookies

The state cookie, dotpress_sso_state (__Host-dotpress_sso_state with secure cookies), is encrypted with secrets.keys, HttpOnly, on Path=/, valid 10 minutes, used once (remembered in the store of rateLimits until it expires: a shared store with several instances) and cleared by the callback. Its SameSite is Lax for OpenID Connect, and None (secure) for SAML, whose ACS receives a cross-site POST. A callback that sets the auth cookies answers 303, so that the browser follows the SAML POST with a GET; the other redirects (?code=, ?challenge=, ?error=) answer 302.

The identities

An IdP account is an identity, in the identities store of the social login, with the provider sso:<connectionId> and its subject: sso:acme-okta. A login updates its email and lastUsedAt, and the first one records identity.linked.

Services

auth.sso.discover(email), auth.sso.start({ connectionId, mode, redirectTo?, codeChallenge? }) (the URL of the IdP and the encrypted state), auth.sso.finish({ connectionId, protocol, parameters, state, meta?, trustedDeviceToken?, onInvalidState? }) and auth.sso.metadata(connectionId) run the flows outside the routes; onInvalidState runs first for a callback without a valid state (the routes count rateLimits.sso.callbackIp there). routes: { ssoDiscover: false } turns off POST /sso/discover, routes: { sso: false } the start, the callbacks and the metadata.

In tests

createFakeOidcProvider() of @dotpress/auth/testing plays the IdP of an OpenID Connect connection, without network; give an https issuer, and its fetch to createSso():

import { createSso } from '@dotpress/auth/sso'
import { createFakeOidcProvider } from '@dotpress/auth/testing'

const idp = createFakeOidcProvider({ issuer: 'https://idp.acme.com', clientSecret: 'secret' })
const sso = createSso({
  baseUrl: 'http://localhost/auth',
  connections: [
    { id: 'acme', protocol: 'oidc', issuer: idp.issuer, clientId: 'client', clientSecret: 'secret', enabled: true },
  ],
  resolveUser: async ({ profile, existingUserId }) => ({ userId: existingUserId ?? profile.subject }),
  fetch: idp.fetch,
})

const started = await fetch('/auth/sso/acme/start?redirectTo=https://app.example.com', { redirect: 'manual' })
const stateCookie = started.headers.getSetCookie()[0]!.split(';')[0]!
const parameters = idp.authorize(started.headers.get('location')!, { subject: 'u1', email: 'ada@acme.com' })
const res = await fetch(`/auth/sso/acme/oidc/callback?${parameters}`, {
  redirect: 'manual',
  headers: { cookie: stateCookie },
})

authorize() also takes claims, like { amr: ['pwd', 'mfa'] } for the MFA of the IdP.

Errors

The callbacks carry the code in ?error=; the other routes answer it.

StatusCodeWhen
404SSO_NOT_CONFIGUREDAn unknown or disabled connection, or a callback of another protocol
400OAUTH_STATE_INVALIDA missing, expired, already used or foreign state cookie
400CODE_CHALLENGE_REQUIREDmode=body without codeChallenge, or an IdP-initiated response ending with a handoff code, with handoff.pkce: 'required'
429TOO_MANY_REQUESTSOver rateLimits.sso.ip, or rateLimits.sso.callbackIp (callbacks without a valid state)
401SSO_ASSERTION_INVALIDAn invalid answer of the IdP: signature, issuer, audience, expiration, request, replay…
403SSO_REJECTEDssoRejected(reason) of resolveUser, or an IdP account linked to another user (IDENTITY_TAKEN), with data.reason
403SSO_REQUIREDAnother way in for an address of an enforced domain, with data.connectionId
503PROVIDER_UNAVAILABLEThe OpenID Connect IdP does not answer, or answers a 5xx

The account gate, beforeSession and MFA errors apply as for a password login.

Events

EventFields
sso.login_succeededuserId, connectionId
sso.login_failedconnectionId, reason: the error code (SSO_ASSERTION_INVALID, SSO_REJECTED…)
user.signed_upmethod: 'sso', provider: 'sso:<id>', when resolveUser returns created: true
identity.linkedidentityId, provider: 'sso:<id>', at the first login of an IdP account
login.failedreason: 'sso_required', for another method on an enforced address

See Events.