Skip to content

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.

  • A working setup of organizations. sso needs organizations.
  • 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.
  1. Add sso to the config, with oidc, saml, or both.
  2. Give sso.dns two resolvers. Core has no default resolver.
  3. Give an operator secret the scope sso, for the override in the last step.
The SSO config and the setup by the app
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 };
}
  1. Add the domain: client.sso.domains.add({ organizationId, domain }) on the owner’s page.
  2. Show the owner the record of the answer: a TXT record at _authtempo-challenge.<domain>.
  3. When the owner has published it, call client.sso.domains.verify({ id }).
  4. Add a connection with client.sso.connections.create(...) and the values of the provider.
  5. Give the provider the values of the connection: spEntityId and acsUrl for SAML, or the callback for OIDC.
  6. Route the domain to the connection: client.sso.domains.update({ id, connectionId }).
  7. Test one sign-in. Then set enforce: true on the domain when the organization asks for it.

The Entra ID, Okta, and Google Workspace pages give the steps in each admin console.

A domain proof, a SAML sign-in, the enforce flag, and the override as a test
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.

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.

  • Every resolver of sso.dns must 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: true also 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 enforce flag.

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.

  • client.sso.discover({ email, next }) answers the connectionId of an address and its start, or { sso: false }. It reads no user, so it tells nothing about a person.
  • start is an absolute URL on the origin of baseURL, with next as 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 jit is on. With jit: false, the sign-in answers sso_not_provisioned, so only SCIM creates users.
  • The person gets a member row with the connection’s defaultRole. Core never gives owner or the platform role.
  • hooks.sso.beforeSignIn may refuse a sign-in before the first write, for example for a contractor domain.

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.

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.

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.

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 subjectAttribute names. With no subjectAttribute, core asks for the persistent NameID and refuses a transient one.
  • The address comes from the attribute of attributes.email, by default email. A NameID of 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.
  • SessionNotOnOrAfter caps the session, also through each sliding refresh.
  • A connection takes idpMetadata, the metadata XML of the provider, or idpEntityId, ssoUrl, and certificates. Core never fetches a metadata URL.