Enterprise SSO
For: an app developer whose customers want their staff to sign in through the company’s own provider, such as Entra ID, Okta, or Google Workspace.
What it does: an organization proves an email domain by a TXT record. Core then signs each address of that domain in through the organization’s OIDC or SAML connection. Core is the service provider.
Before you start
Section titled “Before you start”- A working setup of organizations.
ssoneedsorganizations. - A second factor for each owner who manages SSO. The owner routes refuse an owner with no second factor.
- A shared limiter in production. The SSO limits count per isolate without one.
- Add
ssoto the config, withoidc,saml, or both. - Give
sso.dnstwo resolvers. Core has no default resolver. - Give an operator secret the scope
sso, for the override in the last step.
import { type Auth, createAuth, type DnsTxtPort, dohCloudflare, dohGoogle, type MailPort, type StorageAdapter,} from "@authtempo/core";
/** * Enterprise SSO on. An organization proves its email domain by a TXT record, * then signs its staff in through its own OIDC or SAML provider. `sso` * needs `organizations`. With a setup, the operator secret with the scope * `sso` turns `enforce` off when the provider of a domain is down. */export function createSsoAuth( deps: { storage: StorageAdapter; mail: MailPort; secret: string }, setup: { /** The SHA-256 of the operator secret, as `authtempo secret --operator` prints it. */ operatorHash?: string; /** The resolvers of the domain proof. A test passes its own. */ dns?: DnsTxtPort[]; } = {},) { return createAuth({ baseURL: "https://api.example.com", appURL: "https://app.example.com", trustedOrigins: ["https://app.example.com"], secret: deps.secret, storage: deps.storage, mail: deps.mail, organizations: {}, sso: { oidc: true, // A SAML condition may pass by at most this many seconds of clock skew. saml: { clockSkewSeconds: 120 }, // Every resolver must give the record. One wrong resolver cannot give a domain away. dns: setup.dns ?? [dohCloudflare(fetch), dohGoogle(fetch)], }, ...(setup.operatorHash !== undefined && { operator: { secrets: [{ name: "sso-desk", secretHash: setup.operatorHash, scopes: ["sso"] }], }, }), });}
/** The app's admin page as the actor of each SSO call. Each audit row names it. */export const ADMIN = { kind: "app", name: "admin-page" } as const;
/** Step 1: add the domain. Show the record to the owner, who publishes it at the DNS host. */export async function addDomain(auth: Auth, organizationId: string, domain: string) { const sso = auth.api.sso; if (!sso) throw new Error("sso is off"); const added = await sso.domains.add({ actor: ADMIN, organizationId, domain }); if (!added.ok) throw new Error(added.code); // { name: "_authtempo-challenge.<domain>", type: "TXT", value: "authtempo-domain=…" } return added.value;}
/** * Steps 2 to 4: verify the domain, add a SAML connection with the values of * the provider, and route the domain to it with `enforce` on. */export async function connectSaml( auth: Auth, input: { organizationId: string; domainId: string; idpEntityId: string; ssoUrl: string; certificatePem: string; },) { const sso = auth.api.sso; if (!sso) throw new Error("sso is off"); const verified = await sso.domains.verify({ actor: ADMIN, id: input.domainId }); if (!verified.ok) throw new Error(verified.code); const connection = await sso.connections.create({ actor: ADMIN, organizationId: input.organizationId, kind: "saml", label: "Acme staff", idpEntityId: input.idpEntityId, ssoUrl: input.ssoUrl, certificates: [input.certificatePem], }); if (!connection.ok) throw new Error(connection.code); // The values that the provider needs: the SP entity id and the ACS URL. const { spEntityId, acsUrl } = connection.value.saml ?? { spEntityId: "", acsUrl: "" }; const routed = await sso.domains.update({ actor: ADMIN, id: input.domainId, connectionId: connection.value.id, enforce: true, }); if (!routed.ok) throw new Error(routed.code); return { connectionId: connection.value.id, spEntityId, acsUrl };}- Add the domain:
client.sso.domains.add({ organizationId, domain })on the owner’s page. - Show the owner the
recordof the answer: a TXT record at_authtempo-challenge.<domain>. - When the owner has published it, call
client.sso.domains.verify({ id }). - Add a connection with
client.sso.connections.create(...)and the values of the provider. - Give the provider the values of the connection:
spEntityIdandacsUrlfor SAML, or the callback for OIDC. - Route the domain to the connection:
client.sso.domains.update({ id, connectionId }). - Test one sign-in. Then set
enforce: trueon the domain when the organization asks for it.
The Entra ID, Okta, and Google Workspace pages give the steps in each admin console.
import { createHash } from "node:crypto";import type { DnsTxtPort } from "@authtempo/core";import { createTestIdp } from "@authtempo/core/testing";import { describe, expect, it } from "vitest";import { API, call, harness, sessionCookieOf, signIn } from "../support/harness.ts";import { addDomain, connectSaml, createSsoAuth } from "./sso.ts";
const OPERATOR = "sso-desk-secret-0123456789abcdef0123456789";const BIND = "__Secure-tempo_session_oauth";
/** Two resolvers of a test: each answers the records that `zone` holds. */function resolvers(zone: Map<string, string[]>): DnsTxtPort[] { return ["a", "b"].map((name) => ({ name, txt: async (n: string) => zone.get(n) ?? [] }));}
/** base64 of a UTF-8 text, the form of `SAMLResponse`. */function b64(xml: string): string { let bin = ""; for (const b of new TextEncoder().encode(xml)) bin += String.fromCharCode(b); return btoa(bin);}
function setup() { const h = harness(); const zone = new Map<string, string[]>(); const auth = createSsoAuth(h, { operatorHash: createHash("sha256").update(OPERATOR).digest("hex"), dns: resolvers(zone), }); return { h, zone, auth };}
describe("enterprise SSO", () => { it("proves a domain, signs a person in through SAML, enforces SSO, and lets the operator turn it off", async () => { const { h, zone, auth } = setup(); // The owner signs in from another domain, so the enforce flag below does not shut the owner out. const owner = await signIn(auth, h, "owner@owner.example"); const made = await call( auth, "POST", "/auth/organizations/create", { slug: "acme", name: "Acme" }, { cookie: owner }, ); const { organization } = (await made.json()) as { organization: { id: string } };
// Step 1: the record to publish. Steps 2 to 4: the owner publishes it, and the app verifies. const domain = await addDomain(auth, organization.id, "acme.example"); expect(domain.record?.name).toBe("_authtempo-challenge.acme.example"); expect(domain.record?.value).toMatch(/^authtempo-domain=/); zone.set(domain.record?.name ?? "", [domain.record?.value ?? ""]); const idp = await createTestIdp({ alg: "rsa", entityId: "https://idp.acme.example" }); const { connectionId, spEntityId, acsUrl } = await connectSaml(auth, { organizationId: organization.id, domainId: domain.id, idpEntityId: idp.entityId, ssoUrl: "https://idp.acme.example/sso", certificatePem: idp.certificatePem, }); expect(spEntityId).toBe(`${API}/auth/sso/${connectionId}/metadata`); expect(acsUrl).toBe(`${API}/auth/sso/${connectionId}/acs`);
// The start sends the browser to the provider with the AuthnRequest and a binding cookie. const start = await call(auth, "GET", `/auth/sso/${connectionId}/start?next=/home`); expect(start.status).toBe(302); const location = new URL(start.headers.get("location") ?? ""); expect(location.origin + location.pathname).toBe("https://idp.acme.example/sso"); const bind = start.headers .getSetCookie() .find((c) => c.startsWith(`${BIND}=`)) ?.split(";")[0]; const inflated = await new Response( new Blob([ Uint8Array.from(atob(location.searchParams.get("SAMLRequest") ?? ""), (c) => c.charCodeAt(0), ), ]) .stream() .pipeThrough(new DecompressionStream("deflate-raw")), ).text(); const requestId = /\bID="([^"]+)"/.exec(inflated)?.[1] ?? "";
// The provider posts a signed Response to the ACS. A persistent NameID names the person. const now = new Date(); const xml = await idp.response({ audience: spEntityId, recipient: acsUrl, inResponseTo: requestId, nameId: "ada-1", attributes: { email: ["ada@acme.example"] }, notBefore: new Date(now.getTime() - 60_000), notOnOrAfter: new Date(now.getTime() + 5 * 60_000), now, }); const acs = await auth.handle( new Request(acsUrl, { method: "POST", headers: { "content-type": "application/x-www-form-urlencoded", origin: "https://idp.acme.example", "sec-fetch-site": "cross-site", cookie: bind ?? "", }, body: new URLSearchParams({ SAMLResponse: b64(xml), RelayState: location.searchParams.get("RelayState") ?? "", }).toString(), }), ); expect(acs.status).toBe(302); expect(acs.headers.get("location")).toBe("https://app.example.com/home"); const session = sessionCookieOf(acs); const me = await call(auth, "GET", "/auth/session", undefined, { cookie: session }); expect(((await me.json()) as { user: { email: string } }).user.email).toBe("ada@acme.example");
// With enforce on, a magic link request gives its normal answer and sends no mail. const before = h.sent.length; const link = await call(auth, "POST", "/auth/magic-link/request", { email: "ada@acme.example", }); expect(link.status).toBe(200); expect(h.sent).toHaveLength(before);
// The provider is down: the operator turns enforce off with a reason. const off = await call( auth, "POST", "/auth/operator/sso/enforce-off", { domainId: domain.id, reason: "the provider of acme.example is down" }, { authorization: `Operator ${OPERATOR}` }, ); expect(off.status).toBe(200); expect(((await off.json()) as { enforce: boolean }).enforce).toBe(false); await call(auth, "POST", "/auth/magic-link/request", { email: "ada@acme.example" }); expect(h.sent).toHaveLength(before + 1); });});An app with no owner page calls the same steps through auth.api.sso, with the app as the actor. The sample does that.
How it behaves
Section titled “How it behaves”The trust of a verified domain
Section titled “The trust of a verified domain”A verified domain of an organization can sign in as any existing user whose current address is in that domain. A proof of a domain is the same trust as a mailed link: the owner of the domain controls its mail. Core never reads email_verified of the provider. The address of each sign-in must be in a verified domain of the connection’s organization, else sso_domain_mismatch.
The same rule holds for the user that an identity names. A user can change the account address after the first SSO sign-in. When the new address is outside the verified domains of the organization, the identity answers sso_domain_mismatch and opens no session. The address that the provider sends does not change this.
The domain proof
Section titled “The domain proof”- Every resolver of
sso.dnsmust give the exact value. One wrong or compromised resolver cannot give a domain to an organization. - A pending domain lives 7 days.
- One domain belongs to one organization. A second organization that verifies it gets
domain_taken. includeSubdomains: truealso claims each address of a subdomain.- The sweep checks each verified domain again every 30 days. Three failures that span at least 72 hours lose the domain, with its claim and its
enforceflag.
Who manages SSO
Section titled “Who manages SSO”An owner of the organization manages its domains, connections, and SCIM tokens. A platform operator manages every organization. The owner needs a second factor and a fresh session, so wrap each call in client.withFresh. An impersonation session cannot manage SSO. Each write writes one audit row.
The sign-in
Section titled “The sign-in”client.sso.discover({ email, next })answers theconnectionIdof an address and itsstart, or{ sso: false }. It reads no user, so it tells nothing about a person.startis an absolute URL on the origin ofbaseURL, withnextas its query. Send the browser there as it is, also when the app is on another origin.client.sso.signIn({ connectionId })sends the browser to the start of a connection. An app button may name a connection.- The sign-in page of core has a “Sign in with SSO” form that posts the address to the discovery.
- A known identity signs in its user, while the user’s current address is in a verified domain of the organization. A user at the address gets the identity of the connection.
- A new address gets a new user with a verified address and no password, when
jitis on. Withjit: false, the sign-in answerssso_not_provisioned, so only SCIM creates users. - The person gets a member row with the connection’s
defaultRole. Core never givesowneror the platform role. hooks.sso.beforeSignInmay refuse a sign-in before the first write, for example for a contractor domain.
The second factor
Section titled “The second factor”The second factor gate applies to an SSO sign-in, by totp.gate.sso (on by default). A connection may name a pass list in mfa: amr, acr, and authnContext. When the provider asserts one listed value, the provider did the second factor, and the gate passes. An amr value of the ID token, an equal acr, or an equal SAML AuthnContextClassRef passes. With no list, a person with a second factor gets the challenge.
The enforce flag
Section titled “The enforce flag”With enforce: true on a domain, only SSO signs in an address of that domain. Each first factor answers sso_required, with the start URL in detail. That is the password at its sign-up, sign-in, verify link, reset, and change. It is also the magic link, the email code, social, the ID token, the passkey, the phone code, and the sign-up code. The start URL is absolute, on the origin of baseURL, as the discovery answers it, so send the browser there as it is. A magic link request, an email code request, a password reset request, and a phone code request give their normal answer and send nothing. enforce needs a verified domain routed to an enabled connection.
The operator’s override
Section titled “The operator’s override”When the provider is down, nobody of an enforced domain can sign in. A platform operator, or an operator secret with the scope sso, then posts POST /operator/sso/enforce-off with { domainId, reason }. The flag goes off, and one audit row sso_enforce_off holds the reason.
The provider calls
Section titled “The provider calls”sso.fetch carries each call to the provider: the discovery, the token request, and the read of the key set. The token request sends the client secret by the tokenEndpointAuthMethod of the connection: client_secret_post (the default) or client_secret_basic. Core caps the size of each answer and follows no redirect. Each issuer and endpoint host must be public: no IP literal, no local name, and not the host of baseURL. The DNS presets take the fetch that you give them.
Core accepts one narrow profile and refuses any construct outside it.
- The sign-in starts at core. Core refuses an unsolicited Response.
- The Assertion must be signed with RSA-SHA256 or ECDSA-SHA256, and a SHA-256 digest. Core refuses SHA-1.
- A connection holds one or two certificates, so a provider can roll its key over. Core reads no key from the document.
- The subject is the attribute that
subjectAttributenames. With nosubjectAttribute, core asks for the persistentNameIDand refuses a transient one. - The address comes from the attribute of
attributes.email, by defaultemail. ANameIDof the email address format also gives it. - Core does not sign its AuthnRequest. It refuses an encrypted assertion, and it serves no SAML single sign-out.
SessionNotOnOrAftercaps the session, also through each sliding refresh.- A connection takes
idpMetadata, the metadata XML of the provider, oridpEntityId,ssoUrl, andcertificates. Core never fetches a metadata URL.
If it fails
Section titled “If it fails”domain_unverified: a resolver did not give the value. Wait for the DNS change, then verify again.token_expired: the pending domain is older than 7 days. Add the domain again for a new record.domain_taken: another organization holds the domain.domain_limitandconnection_limit: the organization holdssso.limitsdomains or connections.unauthorized: the call to a manager route has no session.invalid_body: the body or the query does not match the route.conflict: a write at the same time changed the domain, the connection, or the member. Read the row again, and retry.second_factor_required: the owner has no second factor.session_not_fresh: prove it again, then call once more.forbidden_rank: the caller is not an owner of the organization.operator_required: a platform operator failed the operator guard.impersonation_session: an impersonation session cannot manage SSO.sso_not_configured: no connection or kind serves the request.setup_link_invalid: the setup link is unknown, expired, revoked, or ended. Mint a new one.setup_link_limit: the organization holds its limit of open setup links. Revoke one first.setup_not_tested: no test sign-in passed for the current draft. Run the test, then activate again.sso_failed: a step of the OIDC or SAML check failed. The log line names the step.sso_domain_mismatch: the address is outside the verified domains of the organization.sso_not_provisioned:jitis off, and SCIM did not create the person.account_disabled: the directory deactivated the person.sso_required: the domain enforces SSO. Send the browser to the start URL indetail.email_required: the provider sent no address.oauth_denied: the person said no at the provider.sign_up_closed:signUpdoes not let the address become a user, sojitcreates no user.member_limit: the organization holds its maximum of members, so the person gets no member row.role_not_found: thedefaultRoleof the connection names a role that is gone. Update the connection.account_banned: an operator banned the user.hook_refused:hooks.sso.beforeSignInrefused the sign-in.hook_failed: a hook threw. Read the log line of the hook.rate_limited: see the SSO keys of Limits.