SAML SP integration
The current state of SAML support in ulex: neither direction is served yet, what to use instead today, and what is already built underneath.
ulex does not serve SAML in either direction yet. Both metadata endpoints refuse, because publishing either document would be worse than refusing:
GET /saml/metadata— ulex cannot be a SAML IdP. It can verify XML signatures but not produce one, so it cannot sign an assertion.GET /saml/sp/metadata— ulex is not yet a SAML SP either. There is no mounted Assertion Consumer Service, so there is nothing for your IdP to send an assertion to.
This matters more than a missing feature usually does, because a metadata import is one-way. An administrator who imports either document gets no error from their console, and the breakage appears later as a failed sign-in that looks like a certificate or clock problem on their side.
#What to use instead
For enterprise federation today, create an OpenID connection — ulex as a relying party against your customers' identity providers:
curl -sS -X POST "$BASE/connections" \
-H "$AUTH" -H 'Content-Type: application/json' -d '{
"name": "Acme SSO",
"strategy": "okta_oidc",
"organization_id": "'"$ORG"'",
"config": { "oidc": { "client_id": "…", "client_secret_encrypted": "…" } }
}'oidc, google_oidc, microsoft_oidc, entra_oidc, okta_oidc, github_oidc, apple_oidc and generic_oauth2 all federate today, over a single implementation. See OIDC client integration.
#What is already built
The cryptography is largely present and tested in packages/protocol/src/saml/: parseAuthnRequest, parseSamlResponse, verifyXmlSignature (with InMemoryReplayCache for assertion replay), mapSamlAttributes, and buildAuthnRequestXml. What is missing is the HTTP leg — an ACS route and an SSO route — not the protocol handling. The same signature-verification and attribute-mapping code the OIDC path uses is what an SP implementation would use.
#Historical guide
The two directions below describe the intended design. Both are unimplemented, and the endpoint tables name routes that do not exist. Kept for the design record; do not configure against it.
| You want to… | You are the… | ulex is the… | Part |
|---|---|---|---|
| Have Okta/Entra/ADFS log users into your app | SP | IdP | Part 1 |
| Log users into your app's customers' IdPs and map their users | IdP | SP | Part 2 |
#Part 1 — ulex is the IdP, your app is the SP (not implemented)
#1. Fetch ulex's metadata
curl -sS "$BASE/applications/app_01M3PSV7J8TBSPHG95CYSEX32B/metadata"<?xml version="1.0" encoding="UTF-8"?>
<EntityDescriptor xmlns="urn:oasis:names:tc:SAML:2.0:metadata" entityID="https://ulexid.com/api/v1/applications/app_01M3PSV7J8TBSPHG95CYSEX32B">
<IDPSSODescriptor WantAuthnRequestsSigned="false" protocolSupportEnumeration="urn:oasis:names:tc:SAML:2.0:protocol">
<KeyDescriptor use="signing">
<ds:KeyInfo xmlns:ds="http://www.w3.org/2000/09/xmldsig#">
<ds:X509Data>
<ds:X509Certificate>MIIDQjCCAiqgAwIBAgIGATz/FuLiMA0GCSqGSIb3DQ…</ds:X509Certificate>
</ds:X509Data>
</ds:KeyInfo>
</KeyDescriptor>
<NameIDFormat>urn:oasis:names:tc:SAML:2.0:nameid-format:persistent</NameIDFormat>
<SingleSignOnService Binding="urn:oasis:names:tc:SAML:2.0:bindings:HTTP-Redirect" Location="https://ulexid.com/api/v1/auth/app_01M3PSV7J8TBSPHG95CYSEX32B/sso"/>
<SingleSignOnService Binding="urn:oasis:names:tc:SAML:2.0:bindings:HTTP-POST" Location="https://ulexid.com/api/v1/auth/app_01M3PSV7J8TBSPHG95CYSEX32B/sso"/>
<SingleLogoutService Binding="urn:oasis:names:tc:SAML:2.0:bindings:HTTP-Redirect" Location="https://ulexid.com/api/v1/auth/app_01M3PSV7J8TBSPHG95CYSEX32B/slo"/>
<AttributeConsumingService index="1">
<ServiceName xml:lang="en">Acme Support</ServiceName>
<RequestedAttribute Name="email" NameFormat="urn:oasis:names:tc:SAML:2.0:attrname-format:basic" isRequired="1"/>
<RequestedAttribute Name="firstName" isRequired="0"/>
<RequestedAttribute Name="lastName" isRequired="0"/>
<RequestedAttribute Name="displayName" isRequired="0"/>
<RequestedAttribute Name="title" isRequired="0"/>
<RequestedAttribute Name="department" isRequired="0"/>
<RequestedAttribute Name="groups" isRequired="0"/>
</AttributeConsumingService>
</IDPSSODescriptor>
</EntityDescriptor>| Property | Value |
|---|---|
entityID | https://ulexid.com/api/v1/applications/{applicationId} |
| SSO URL (Redirect) | https://ulexid.com/api/v1/auth/{applicationId}/sso |
| SSO URL (POST) | the same URL |
| SLO URL | https://ulexid.com/api/v1/auth/{applicationId}/slo |
Point your SP library at the metadata URL and let it parse. Hand-typed entity ids fail often enough to be worth avoiding.
#2. The signing certificate
curl -sS "$BASE/applications/app_01M3PSV7J8TBSPHG95CYSEX32B/secret" -H "Authorization: Bearer $ULEX_API_KEY"{
"client_id": "client_01M3PSV7J8TBSPHG95CYSEX32B",
"saml_signing_certificate": "-----BEGIN CERTIFICATE-----\nMIIDQjCCAiqgAwIBAgIGATz/FuLiMA0GCSqGSIb3D…\n-----END CERTIFICATE-----",
"saml_signing_certificate_expires_at": "2027-03-11T00:00:00.000Z",
"saml_signing_kid": "key_01M3PSVJA0YP2WDPM2RDR15MGH"
}Cache it and refresh on a schedule. It rotates with the tenant's signing keys, and a stale certificate in your SP config is the number-one cause of saml_signature_invalid a year after everything worked.
#3. What your SP must enforce
| Check | Requirement | Why |
|---|---|---|
| XML signature | required on the assertion | an unsigned assertion is a free-for-all |
| Signature algorithm | RSA-SHA256 | SHA-1 is rejected |
Destination | must equal your ACS URL exactly | stops assertion replay at a different endpoint |
InResponseTo | must match your AuthnRequest | stops unsolicited assertion injection |
Issuer | must equal the metadata entityID | stops a different IdP's assertion being accepted |
Audience | must equal your SP entity id | stops cross-application replay |
NotBefore / NotOnOrAfter | 5-minute window, 30 s clock tolerance | stops replay after the fact |
Assertion/@ID | remember it; reject duplicates | the second layer of replay defence |
Recipient on SubjectConfirmation | must equal your ACS URL | same as Destination |
The NameID is the ulex usr_… id and is stable across email changes. Key your local user table on it, never on email or on displayName.
#4. Example SP handler
import * as saml from "samlify";
import * as fs from "node:fs";
import { XMLValidator } from "fast-xml-parser";
const APP_ID = "app_01M3PSV7J8TBSPHG95CYSEX32B";
const ENV_HOST = "https://ulexid.com";
const SEEN = new Set<string>(); // Assertion/@ID replay cache
const SEEN_TTL_MS = 10 * 60_000;
const idp = await saml.IdentityProvider({
metadata: await (await fetch(`${ENV_HOST}/api/v1/applications/${APP_ID}/metadata`)).text(),
wantAuthnRequestsSigned: false,
wantMessageSigned: false, // we sign the assertion, not the Response
signatureConfig: {
certificate: process.env.ULEX_SAML_CERT!, // from /applications/{id}/secret
privateKey: process.env.ULEX_SAML_KEY!, // your SP key
signAuthnRequest: false,
},
idpCert: process.env.ULEX_SAML_CERT!,
});
const sp = new saml.ServiceProvider({
entityID: "https://app.example.com/saml/metadata",
assertionConsumerService: [
{ Binding: saml.Constants.namespace.binding.post, Location: "https://app.example.com/saml/acs" },
],
singleLogoutService: [
{ Binding: saml.Constants.namespace.binding.redirect, Location: "https://app.example.com/saml/slo" },
],
requestSignatureAlgorithm: saml.Constants.namespace.alg.rsa_sha256,
signatureAlgorithm: saml.Constants.namespace.alg.rsa_sha256,
});
export async function handleAcs(xml: string, relayState: string) {
if (!XMLValidator.validate(xml)) {
return { status: 400, error: "malformed_xml" };
}
const { extract } = await saml.saml2PostBindingAsync(sp, "post", {
request: "post",
SAMLResponse: xml,
});
// DTDs and external entities must be off. XMLValidator + samlify does this
// for you; if you hand-parse, do not forget.
const { nameID, attributes } = extract;
// Replay: an Assertion/@ID may be consumed exactly once.
const assertionId = extract.attributes?.assertionId ?? xml.match(/Assertion[^>]*ID="([^"]+)"/)?.[1] ?? "";
const now = Date.now();
for (const id of SEEN) if (now - Number(id.split(":")[1]!) > SEEN_TTL_MS) SEEN.delete(id);
if (SEEN.has(`seen:${assertionId}:${now}`)) return { status: 400, error: "replayed_assertion" };
SEEN.add(`seen:${assertionId}:${now}`);
return {
status: 200,
nameID,
email: attributes["email"]?.[0],
firstName: attributes["firstName"]?.[0],
lastName: attributes["lastName"]?.[0],
orgId: attributes["org_id"]?.[0],
orgRole: attributes["org_role"]?.[0],
groups: attributes["groups"] ?? [],
relayState,
};
}#5. Group and role claims
ulex emits:
| Attribute | Example | Notes |
|---|---|---|
email | dana@acme.example | primary, required |
firstName / lastName / displayName | ||
title | Support Lead | maps to user.job_title |
department | Customer Success | |
groups | engineering | group slugs, repeated |
org_id | org_01M3PSV8HGTKQFCAYF9GDWGN3C | |
org_role | owner | owner/admin/member/guest |
sid | ses_01M3PSVFC8MAB38QYAA8Q1K9MG | the ulex session, for logout correlation |
auth_time | epoch seconds | |
acr | urn:ulex:acr:mfa | in AuthnContextClassRef |
groups are slugs, not display names, and they are scoped to the organization. engineering in Acme and engineering in Globex are different groups with different members. Join on (org_id, group) if you need a global view.
#6. IdP-initiated login
Send the user to the SSO URL with a login_hint or straight in:
GET /api/v1/auth/app_01M3PSV7J8TBSPHG95CYSEX32B/sso?login_hint=dana%40acme.example&RelayState=st_9Kq2WmB7yLt4NxZFor genuine IdP-initiated SSO, ulex also accepts an unsolicited POST /connections/{id}/saml/sso, and returns a session plus an acs_redirect you can follow:
{
"name": "ulex_simulate_login",
"arguments": { "application_id": "app_01M3PSV7J8TBSPHG95CYSEX32B", "email": "dana@acme.example", "protocol": "saml", "return_assertion": true }
}{
"session_id": "ses_01M3PSVFC8MAB38QYAA8Q1K9MG",
"outcome": "success",
"protocol": "saml",
"in_response_to": "_4Kq9WmB2yLt7NxZ1pRc6HdE0sJg3AuV8",
"name_id": "usr_01M3PSV9GRT8GQGEG686AR1W9S",
"attributes": { "email": "dana@acme.example", "firstName": "Dana", "lastName": "Okafor", "groups": ["engineering"] },
"assertion_b64": "PHNhbWw6UmVzcG9uc2UgeG1sbnM6c2FtbHA6UmVzcG9uc2U…",
"not_on_or_after": "2026-09-29T14:45:17.000Z"
}Feed assertion_b64 into your ACS handler in a test. It is a real, signed, correctly-timed assertion with real attributes — no IdP, no browser, no fixtures.
#7. Single logout
export async function handleSlo(requestType: "logoutRequest" | "logoutResponse", xml: string) {
if (XMLValidator.validate(xml) !== true) return { status: 400 };
const { extract } = await saml.saml2RedirectBindingAsync(sp, "redirect", { request: "redirect", SAMLRequest: xml });
// Terminate your local session, then return the signed LogoutResponse so
// ulex can terminate the upstream session too.
await destroyLocalSession(extract.nameID);
return saml.logoutResponseAsync({ request: "redirect", SAMLResponse: extract.logoutResponse });
}Configure singleLogoutService on your SP side, or SLO will not be offered. Not every IdP supports it; that is a customer IdP property, not something you control.
#Part 2 — ulex is the SP, your customer's IdP is the IdP
#8. Register the upstream IdP
curl -sS -X POST "$BASE/connections" \
-H "Authorization: Bearer $ULEX_API_KEY" -H "Content-Type: application/json" \
-H "Idempotency-Key: 1f4c9e2a-3b7d-4a1e-9c58-0f2a6b3d81cc" \
-d '{
"name": "Globex SAML",
"organization_id": "org_01M3PSVT404FMFWPN6QAMM2R4P",
"domains": ["globex.example"],
"config": {
"strategy": "saml",
"saml": {
"entity_id": "https://globex.okta.com/app/exk9r2mz1hRtXQ2N5s0d7",
"sso_url": "https://globex.okta.com/app/exk9r2mz1hRtXQ2N5s0d7/sso/saml",
"slo_url": "https://globex.okta.com/app/exk9r2mz1hRtXQ2N5s0d7/slo/saml",
"x509_certificate": "MIIE1DCCA3CgAwIBAgIULSJ…",
"x509_certificate_expires_at": "2027-04-18T00:00:00.000Z",
"name_id_format": "urn:oasis:names:tc:SAML:2.0:nameid-format:persistent",
"binding": "saml_redirect",
"want_response_signed": true,
"want_assertion_signed": true,
"want_authn_request_signed": false,
"signature_algorithm": "rsa-sha256",
"digest_algorithm": "sha256",
"signature_validation": "strict",
"allowed_clock_skew_seconds": 120,
"name_id_transformations": "email",
"allow_create": true,
"allow_update": true,
"allow_link": true,
"group_attribute": "groups",
"groups_attribute": "groups",
"group_name_template": "{name}",
"active_attribute": "active",
"active_value": "true",
"acs_allowed_urls": [],
"attribute_mapping": {
"email": "email",
"first_name": "firstName",
"last_name": "lastName",
"display_name": "displayName",
"job_title": "title",
"department": "department",
"external_id": "userId",
"groups": "groups"
}
}
}
}'{
"id": "con_01M3PSVY108K5TEHHQ82WN30YK",
"object": "connection",
"name": "Globex SAML",
"state": "draft",
"config": { "strategy": "saml" },
"domains": ["globex.example"],
"domains_state": "pending",
"last_auth_result": null
}state is draft. Every login on it is refused with connection_not_active until you verify and activate.
#9. Verify before you activate
curl -sS -X POST "$BASE/connections/con_01M3PSVY108K5TEHHQ82WN30YK/verify" -H "Authorization: Bearer $ULEX_API_KEY"{
"connection_id": "con_01M3PSVY108K5TEHHQ82WN30YK",
"valid": true,
"checks": [
{ "check": "entity_id present", "status": "passed", "detail": "https://acme.okta.com/app/exkxxxx/sso/saml/metadata" },
{ "check": "sso_url present", "status": "passed", "detail": "https://acme.okta.com/app/exkxxxx/sso/saml" },
{ "check": "certificate parses", "status": "passed", "detail": "pinned certificate yields a usable public key" },
{ "check": "signature algorithm", "status": "passed", "detail": "rsa-sha256 — ulex verifies the algorithm the IdP names, it does not choose it" },
{ "check": "clock skew budget", "status": "passed", "detail": "120s" },
{ "check": "sso_url reachable", "status": "passed", "detail": "HTTP 200" }
]
}verify always returns 200, because an unreachable IdP is an answer and not an exception. Read valid and checks[]. Never activate on valid: false.
certificate parses is the one worth reading. ulex asks whether the pinned value actually yields a public key — a field that is present is not the same as one that is usable, and a certificate the verifier cannot read passes an emptiness check and then fails every sign-in.
curl -sS -X POST "$BASE/connections/con_01M3PSVY108K5TEHHQ82WN30YK/activate" -H "Authorization: Bearer $ULEX_API_KEY"#10. Configure the customer's IdP to POST to ulex
Give your customer these three values from GET /connections/{id}/saml/metadata:
| IdP field | Value |
|---|---|
| Single sign-on URL (ACS) | acs_url |
| Audience URI | ulex's own entity id (or leave blank for the default) |
| Name ID format | urn:oasis:names:tc:SAML:2.0:nameid-format:persistent |
| Sign assertions | yes |
| Signature algorithm | RSA-SHA256 |
| Single logout URL | slo_url |
acs_allowed_urls defaults to the connection's own ACS URL only. Add more only if you are terminating SAML at a second endpoint, and never add a wildcard.
#11. Attribute mapping, in practice
| The customer's IdP does this | You get | Fix |
|---|---|---|
Entra returns preferred_username, not email | 400 access_denied, user not found | attribute_mapping.email = "preferred_username" |
NameID is an opaque id | cannot link to an existing user | name_id_transformations: "email" (requires an email attribute) or "saml_subject_hash" plus allow_link: true |
groups are object ids | groups claim full of GUIDs | map through your own lookup table, or set group_name_template: "{name}" and slug them |
active is the string "false" | deactivated users can still log in | active_value: "false" — ulex compares as a string, so this works |
| Assertion is unsigned | saml_signature_invalid | tick "signed assertions" on the IdP app |
| IdP clock is 4 minutes fast | saml_clock_skew | fix NTP. Only then raise allowed_clock_skew_seconds, max 600 |
#12. The link decision
ulex must decide which user an assertion refers to, in this order:
external_id—config.saml.attribute_mapping.external_idmatched againstuser.external_id(set by a previous assertion)email—config.saml.attribute_mapping.emailmatched againstuser.emaildirectory— a user already provisioned from the organization's linkeddirectory- create — if
allow_create: trueand the organization allows it - fail —
400 saml_nameid_mismatch
allow_create | allow_update | allow_link | Behaviour |
|---|---|---|---|
true | true | true | JIT provisioning and linking. The normal production setting |
true | false | false | SCIM-only. Every user must arrive over SCIM; SAML never creates anyone |
false | true | true | The directory is the only source of users; SAML refreshes their profile |
false | false | false | Read-only assertions. Unusual, and it means the profile can never change |
For a customer with SCIM, set allow_create: false. It turns "user not found" from a support ticket into a data-quality signal, which is where it belongs.
#13. Certificate rotation
- Download the new signing certificate from the customer's IdP. ulex does not read certificate expiry dates — the certificate is only ever used as a public key, and a key does not expire — so nothing warns you in advance.
PATCH /connections/{id}with the newconfig.saml.x509_certificate. The connection drops todraft.POST /connections/{id}/verify→ confirmvalid: trueand thatcertificate parsespassed.POST /connections/{id}/activate.GET /audit-events?action=connection.updated&connection_id={id}to confirm.
Between steps 2 and 4 the connection is unusable. If the old certificate has not yet expired, the customer can serve both certificates for an overlap window, which removes the downtime entirely — worth asking for.
#14. Debugging order
1. ulex_verify_connection → is the certificate valid and the IdP reachable?
2. GET /connections/{id} → last_auth_result and last_auth_error, from the last real attempt
3. GET /connections/{id}/auth-attempts?outcome=failure
→ stage, error_code, error_message, duration_ms
4. ulex_simulate_login with return_assertion
→ does a synthetic assertion work when the customer's does not?
5. ulex_explain_error with the error_codestage tells you where it died: initiated → redirected → callback → validated → provisioned → mfa → complete. A failure at redirected means the IdP would not accept your AuthnRequest. A failure at callback means the Response arrived and was rejected. A failure at provisioned means the user does not exist and allow_create is false.