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:
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
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.
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
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
Give the IdP the URLs of the connection, or its metadata:
Resolving the user
resolveUser decides who logs in, at each login, with:
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:
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.
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:
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_REQUIREDanddata.connectionId, and recordslogin.failedwith the reasonsso_required(onLoginFailedgets theerrorTypesso_required). Impersonations andgenerateTokensForUser()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:
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 withPOST /auth/mfa/verify(see MFA);?code=<code>: a handoff code (mode=body), to exchange withPOST /auth/token, with the PKCE verifier ofcodeChallenge;?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.
A response is accepted when:
- its status is
Success, and itsDestination, 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 ofidpCertificates, with signature and digest algorithms of SHA-256 or stronger (SHA-1 is refused), and comes fromidpEntityId, for the entity ID of the connection; - a bearer subject confirmation targets the ACS and the request, within its validity,
clockSkewtolerated; - its assertion was never used before;
- its
NameIDis not transient: a transientNameIDchanges 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():
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.
The account gate, beforeSession and MFA errors apply as for a password login.
Events
See Events.