Skip to content
LogoLogo

SSO with Users and your own authorization (combo B)

You run user-service only. People sign in through their company's identity provider via user-service. Your backend decides what they may do, from the token's SSO claims, a live status check and your own data. Read Enterprise SSO for the concepts first.

Pre-release; names are provisional until the SSO naming review; pricing is not decided. See the status note in Enterprise SSO.

1. Turn SSO on and set up connections

saaslayer deployment settings set --env prod --set user-service.EnableSso=true --reason "enterprise SSO"
saaslayer sso create --tenant <tenant-id> --protocol oidc --issuer https://acme.okta.com/oauth2/default \
  --client-id <okta-client-id> --client-secret-stdin --domain acme.com --scim on < okta-client-secret.txt

The tenant is your own id for the customer company. It comes back in every SSO token as sso_tenant. Configure the provider (Provider setup), verify the domains and activate as in the common flow there.

2. Let your customers' admins manage their connection

Your backend holds the server credential. A browser only ever gets a short-lived management session.

  1. Server key. Introduce a machine key with the sso-management purpose (opt-in local management of the user-service instance):

    saaslayer users admin keys --deployment <dep_id> --service user-service --aws-account <aws-account> --region <region> \
      --caller acme-backend --purpose sso-management --phase introduce --to-file ./sso-management.key
    saaslayer users admin keys --deployment <dep_id> --service user-service --aws-account <aws-account> --region <region> \
      --caller acme-backend --phase activate --key-id <key-id>

    The raw key is written only to --output (mode 0600). Move it into your backend's secret store.

  2. Management session. For a signed-in customer admin, your backend issues one session scoped to their tenant (or one connection). It ends after 1 hour unused or at maxMinutes (5–480, default 480):

    POST /api/sso/management-sessions
    x-api-key: <sso-management machine key>
    X-SaaSLayer-Caller-Id: acme-backend
    Content-Type: application/json
    { "data": { "type": "sso-management-sessions", "attributes": { "tenant": "t_acme", "maxMinutes": 60 } } }
  3. Hand over the session. The 201 answer carries the session token (shown once) and meta.settingsUrl, the instance's hosted settings page with the token in the URL fragment. Either send the admin there, or render <SsoSettings client={…}> from @saaslayer/react with the session token.

A management session can never create a connection, set the owner-only fields or issue another session. Revoke it with DELETE /api/sso/management-sessions/{sessionId}.

3. Authorize requests in your backend

For each request your backend needs four steps:

  1. Verify the ID token locally: signature, issuer (your user pool), expiry, token type id.
  2. Ask the live status (POST /api/auth/status) with a token-status verifier key. This is what makes a SCIM deactivation, a connection disable, the session cap, a sign-out or domain enforcement take effect before the token expires. User-service also checks the token's audience there: your app client, or an active SSO connection's own client the token was federated through.
  3. Accept only your audience: your app client, or the client of the SSO connection the live answer named.
  4. Authorize from your own data. Use the SSO claims (tenant, complete groups) read with readSsoClaims; never trust decoded claims without step 1, or groups that are not complete.

Create the token-status key as the deployment owner. It is written to SSM (or a 0600 file), never printed:

saaslayer users verifier-keys create --purpose token-status --to-ssm /acme/token-status-key

A tested example (Node, aws-jwt-verify and @saaslayer/js):

import { CognitoJwtVerifier } from 'aws-jwt-verify'
import { readSsoClaims } from '@saaslayer/js'
/**
 * @param {{
 *   userPoolId: string,
 *   appClientId: string,
 *   userServiceApiBase: string,
 *   tokenStatusKey: string,
 *   permissionsForGroups: (tenant: string, groups: string[]) => Promise<string[]>,
 *   permissionsForUser: (suid: string, tenant: string) => Promise<string[]>,
 *   verifier?: { verify: (token: string) => Promise<Record<string, any>> },
 *   fetch?: typeof globalThis.fetch,
 * }} options
 */
function createRequestAuthorizer({ userPoolId, appClientId, userServiceApiBase, tokenStatusKey, permissionsForGroups, permissionsForUser,
  verifier = CognitoJwtVerifier.create({ userPoolId, tokenUse: 'id', clientId: null }), fetch = globalThis.fetch }) {
  const statusUrl = `${userServiceApiBase}/api/auth/status`
 
  /** The token's live standing; anything but a well-formed contract-1 `active: true` counts as inactive. */
  async function liveStanding(token) {
    let res
    try {
      res = await fetch(statusUrl, {
        method: 'POST',
        headers: { 'content-type': 'application/json', 'x-api-key': tokenStatusKey },
        body: JSON.stringify({ token }),
        redirect: 'error',
        signal: AbortSignal.timeout(3000),
      })
    } catch {
      return { active: false, reason: 'status_unavailable' }
    }
    if (res.status !== 200) return { active: false, reason: 'status_unavailable' }
    const attributes = (await res.json().catch(() => null))?.data?.attributes
    if (!attributes || attributes.contract !== 1) return { active: false, reason: 'status_malformed' }
    return attributes.active === true ? attributes : { active: false, reason: attributes.reason || 'inactive' }
  }
 
  /**
   * @param {{ token: string, tenant: string, permission: string }} request the bearer ID token, the tenant (org) the
   *   request acts in, and the permission it needs
   * @returns {Promise<{ allowed: boolean, reason?: string }>}
   */
  return async function authorize({ token, tenant, permission }) {
    // 1. Signature, issuer (this user pool only), expiry and token type (ID tokens only).
    let claims
    try {
      claims = await verifier.verify(token)
    } catch {
      return { allowed: false, reason: 'token_invalid' }
    }
 
    // 2. Live standing: SCIM deactivation, connection disable, session cap, sign-out, domain enforcement. User-service
    //    also checks the audience here: your app client, or an active SSO connection's client federated through it.
    const standing = await liveStanding(token)
    if (!standing.active) return { allowed: false, reason: standing.reason }
    if (standing.suid !== claims['custom:suid']) return { allowed: false, reason: 'status_mismatch' }
 
    // 3. The audience this backend accepts: its own app client (native sign-in), or the client of the SSO connection
    //    the live answer named for this very token.
    const sso = readSsoClaims(claims)
    if (!sso.ok) return { allowed: false, reason: sso.reason }
    if (claims.aud !== appClientId && !(sso.sso && standing.connectionId === sso.sso.connectionId)) return { allowed: false, reason: 'audience_not_accepted' }
 
    // 4. Authorization, decided here (a domain or a signed-in session alone grants nothing).
    let permissions
    if (sso.sso) {
      if (sso.sso.tenant !== tenant) return { allowed: false, reason: 'other_tenant' }
      // Truncated or unknown groups are never an empty list: derive nothing from them.
      if (!sso.sso.groupsComplete) return { allowed: false, reason: 'groups_incomplete' }
      permissions = await permissionsForGroups(tenant, sso.sso.groups)
    } else {
      permissions = await permissionsForUser(claims['custom:suid'], tenant)
    }
    return permissions.includes(permission) ? { allowed: true } : { allowed: false, reason: 'not_permitted' }
  }
}

Use it in a request handler:

const authorize = createRequestAuthorizer({
  userPoolId: process.env.USER_POOL_ID,
  appClientId: process.env.APP_CLIENT_ID,
  userServiceApiBase: process.env.USER_SERVICE_API_BASE,
  tokenStatusKey: process.env.TOKEN_STATUS_KEY,
  permissionsForGroups: async (tenant, groups) => rolesTable.permissionsFor(tenant, groups),
  permissionsForUser: async (suid, tenant) => memberships.permissionsFor(suid, tenant),
})
 
const decision = await authorize({ token: bearerToken, tenant: 't_acme', permission: 'invoices:approve' })
if (!decision.allowed) return reply.status(403).send({ reason: decision.reason })
  • Groups come from the connection's group authority. From the first activation, a connection's groups come from each sign-in (every provider except Google), or from SCIM once you run saaslayer sso scim sync-complete <connectionId>. A Google connection's groups are a complete empty list. The example refuses incomplete groups and derives nothing from an empty list.
  • One status request per check. The status check is never cached: a removal is refused at the next request. A 503 (status unreadable) must count as inactive, as the example does.
  • Without the status check, no early cutoff. A backend that only verifies the JWT accepts a removed person until the token expires (5 minutes by default, --token-ttl-minutes). That is your decision to make; the example doesn't.
  • Access-token claims. On the default Lite tier only the ID token carries SSO claims. Access-token claims need the paid-tier opt-in (see Claims).
  • Session expiry. An SSO session past its cap answers session_expired: send the person to sign in again. The SDK (@saaslayer/js, <SignIn>) does this when user-service answers 401 SSO_SESSION_EXPIRED.

4. Get told about changes (push)

To keep your own data in step without polling, subscribe the instance's ssoLifecycle hook:

saaslayer users hooks set ssoLifecycle --url https://api.acme.com/hooks/saaslayer-sso

Each event is signed (Standard Webhooks; verify with @saaslayer/hooks) and carries ids only: connectionId, and suid for a person. React to sso.user.deactivated, sso.user.deleted, sso.groups.changed, sso.connection.disabled and the rest listed in Lifecycle events. Delivery is retried for 24 hours with the same webhook-id, so make your handler idempotent.

Events are a convenience, not the cutoff: delivery can lag or fail. The live status check in step 3 is what refuses a removed person.

What user-service does for you in B

  • Sign-in and email-first routing. User-service runs the SSO sign-in with @saaslayer/react <SignIn> (email first, then the company's provider). It refuses SSO people any password, passkey or reset path.
  • Sessions. It runs sessions of 5-minute tokens, refreshed through the connection's own app client, with the connection's session cap.
  • SCIM, setup and health. It runs SCIM provisioning and deprovisioning, setup links, health and certificate-expiry alerts, and the audit trail.
  • Never an authorization decision. An active status means the person is still signed in. It never authorizes an org operation: that decision is yours.