Software Crafting

Unlocking Enterprise B2B Deals: Architecting SAML SSO and Automated Identity Provisioning (SCIM) in a Node.js SaaS

DDeepak RajputSecurity17 min read04 Apr 2026Updated 2026-10-27
A glowing key with circuit-board patterns standing upright on a central hexagonal node, connected by lines to a network of green user-icon nodes on a dark background

TL;DR: You can add multi-tenant SAML 2.0 SSO and SCIM 2.0 provisioning to a Node.js SaaS without an identity broker, but only if you get the security details right. This guide uses @node-saml/passport-saml 5.x (on @node-saml/node-saml 5.2) with Express and Prisma. It covers per-tenant IdP configuration, issuer, signature, InResponseTo and replay validation, account linking keyed on (tenantId, idpIssuer, nameID), session delivery through an HttpOnly cookie instead of a URL token, hashed SCIM bearer tokens, and the PATCH-based deprovisioning that Okta actually sends.

Key Takeaways

  • Keep SAML authentication (URL-encoded XML POSTs from the browser) and SCIM provisioning (server-to-server JSON from the IdP) in separate routers with separate authentication.
  • In @node-saml v5 the IdP certificate option is idpCert (not cert), and callbackUrl, issuer and idpCert are required. Set idpIssuer, wantAssertionsSigned, wantAuthnResponseSigned, validateInResponseTo, acceptedClockSkewMs and maxAssertionAgeMs explicitly per tenant.
  • Assertion age and replay are Service Provider checks. Your code enforces them with maxAssertionAgeMs, validateInResponseTo plus a shared cache, and (in node-saml 5.2+) rejectReplayedAssertions.
  • Identify federated users by (tenantId, idpIssuer, nameID) with a composite unique constraint. Never look users up by a globally unique email, or one tenant's IdP can sign in as another tenant's user.
  • Deliver the application session as an HttpOnly cookie set on the ACS response. Never put a JWT in a redirect query string.
  • Store only a SHA-256 hash of each tenant's SCIM bearer token and compare with crypto.timingSafeEqual.
  • Okta deprovisions with PATCH active=false, not DELETE. Support both, and make sure an inactive user's existing sessions stop working.

Picture a common upmarket scenario: the demo went well, the budget is approved, and then the vendor security questionnaire arrives with two requirements:

  1. Your SaaS must integrate with the customer's Okta or Microsoft Entra ID tenant via SAML 2.0 (Security Assertion Markup Language) for authentication.
  2. It must support automated onboarding and offboarding via SCIM 2.0 (System for Cross-domain Identity Management).

If your only option is email and password, or if their IT team has to invite and remove users by hand, the review stalls.

Managed identity platforms solve this, and for many teams they are the right answer. They do charge for it: WorkOS, for example, lists SSO and Directory Sync priced per connection, starting at $125 per connection for the first 15 connections (WorkOS pricing page, accessed 27 October 2026). Other vendors package enterprise SSO into higher plan tiers. Costs scale with the number of enterprise customers, which is why "SSO tax" became a common complaint.

This guide walks through the in-house alternative: a multi-tenant SAML and SCIM pipeline in Node.js. It is a reference implementation, not a drop-in product. If you are still deciding whether to build at all, read our buy vs. build guide for B2B SaaS authentication first.

The Architecture of Enterprise Identity (SAML + SCIM)

Enterprise identity is split into two separate flows: authentication (SAML) and provisioning (SCIM).

In the SAML flow, the customer's Okta or Entra ID acts as the Identity Provider (IdP) and your SaaS acts as the Service Provider (SP). When a user signs in, your SP redirects the browser to the IdP with an AuthnRequest. The IdP authenticates the user and the browser POSTs a signed XML Response back to your Assertion Consumer Service (ACS) URL.

In the SCIM flow, the IdP is an API client. It calls your REST endpoints directly to create, update and deactivate users when assignments change in the directory. SCIM 2.0 is defined by RFC 7643 (schema) and RFC 7644 (protocol), and clients send application/scim+json bodies.

These two flows have different callers, different payload formats and different credentials, so isolate them in the Express app:

// src/app.ts
import express from 'express';
import passport from 'passport';
import { samlRouter } from './routes/saml.routes';
import { scimRouter } from './routes/scim.routes';
import { authenticateScimBearer } from './middleware/scimAuth';
import { multiSamlStrategy } from './auth/samlStrategy';

const app = express();
app.set('trust proxy', 1); // behind a TLS-terminating load balancer

passport.use('saml', multiSamlStrategy);
app.use(passport.initialize());

// SAML: the IdP's HTML form posts SAMLResponse as application/x-www-form-urlencoded.
// Signed responses can be large, so raise the default 100kb limit modestly.
app.use('/api/auth/sso', express.urlencoded({ extended: false, limit: '512kb' }), samlRouter);

// SCIM: IdPs send application/scim+json, which express.json() ignores by default.
app.use(
  '/scim/v2',
  express.json({ type: ['application/json', 'application/scim+json'] }),
  authenticateScimBearer,
  scimRouter,
);

export default app;

Two details here prevent real bugs. First, without the type option, express.json() leaves req.body empty for application/scim+json requests, and every SCIM create silently produces a user with no fields. Second, mounting the body parsers per router keeps the SAML form parser away from your JSON API and vice versa.

Production note: SCIM endpoints can create and deactivate users, so treat them like an admin API. Put a rate limiter (for example express-rate-limit) in front of /scim/v2, log every mutation to an audit trail, and offer IP allowlisting for customers whose IdP publishes egress ranges.

Terminology You Will Meet in Every IdP Console

TermWho owns itWhat it isWhere it lives in this design
SP Entity ID (issuer in node-saml)YouA stable URI that names your app to the IdPApp config, same for every tenant
ACS URL (callbackUrl)YouWhere the IdP posts the SAML responseOne per tenant: /sso/:slug/callback
IdP SSO URL (entryPoint)CustomerWhere your app sends the AuthnRequestSamlConfig.entryPoint
IdP Entity ID (idpIssuer)CustomerThe Issuer value the IdP puts in its responsesSamlConfig.idpIssuer
IdP signing certificate (idpCert)CustomerX.509 certificate used to verify signaturesSamlConfig.idpCert
NameIDCustomer IdPThe subject identifier for the user, scoped to that IdPUser.nameId
SCIM base URL and bearer tokenYou generate, customer pastes inEndpoint and credential the IdP uses for provisioning callsURL is global, token hash per tenant

Multi-Tenant Configuration and a Safe Identity Model

Every enterprise customer brings its own IdP, so the SP must load the right SSO URL, issuer and certificate per tenant. The user model matters just as much, because it decides whose account a valid assertion unlocks.

// schema.prisma (Prisma 5/6, PostgreSQL)

model Tenant {
  id            String      @id @default(uuid())
  slug          String      @unique // e.g. "acme-corp"
  name          String
  users         User[]
  samlConfig    SamlConfig?

  // SCIM credential: a public lookup id plus a SHA-256 hash of the secret.
  // The plaintext token is shown to the customer once and never stored.
  scimTokenId   String?     @unique
  scimTokenHash String?
}

model SamlConfig {
  id         String  @id @default(uuid())
  tenantId   String  @unique
  tenant     Tenant  @relation(fields: [tenantId], references: [id])

  // Values copied from the customer's IdP metadata
  entryPoint String  // IdP SSO URL
  idpIssuer  String  // IdP entity ID, validated on every response
  idpCert    String  // PEM or base64 X.509 signing certificate

  isActive   Boolean @default(true)
}

model User {
  id             String   @id @default(uuid())
  tenantId       String
  tenant         Tenant   @relation(fields: [tenantId], references: [id])
  email          String
  firstName      String?
  lastName       String?

  // SAML federation key: unique per tenant and per IdP
  idpIssuer      String?
  nameId         String?

  // SCIM linkage: the IdP's own id for this user
  scimExternalId String?

  isActive       Boolean  @default(true)

  @@unique([tenantId, email])
  @@unique([tenantId, idpIssuer, nameId])
  @@unique([tenantId, scimExternalId])
}

Why the composite key matters: account takeover across tenants

The original version of this schema declared email String @unique and matched SAML users by email. That is a classic multi-tenant SSO vulnerability. Any customer who configures SSO controls their own IdP, and an IdP will happily assert any email address its admin types in. If your ACS looks up users by a global email, the admin of Tenant A can create a user [email protected] in their IdP, sign in through Tenant A's SSO connection, and land in the Tenant B user's account. The signature is valid; it is simply a valid statement from an issuer that has no authority over that user.

The fix has three parts:

  1. Scope every lookup to the tenant whose connection received the response. The tenant comes from the ACS URL and its stored config, never from the assertion.
  2. Key federated identities on (tenantId, idpIssuer, nameID). NameID is only meaningful relative to the IdP that issued it, and @@unique([tenantId, idpIssuer, nameId]) enforces that in the database rather than in application code.
  3. Treat email as a mutable profile attribute, not an identifier. Emails get reassigned and renamed. When a federated identity does not exist yet, only link it to an existing account in the same tenant, and only when that tenant has verified ownership of the email domain.

The multi-tenant API isolation guide covers the same principle for the rest of your API surface.

Configuring MultiSamlStrategy with @node-saml v5

Do not write XML signature validation yourself. @node-saml/passport-saml wraps @node-saml/node-saml, which handles canonicalization, signature verification and the timing and audience checks. For multiple tenants, MultiSamlStrategy resolves options per request through getSamlOptions(req, callback), and the returned options are merged over the constructor options.

The examples below target @node-saml/passport-saml 5.1 with @node-saml/node-saml 5.2. Version 5 renamed several options from the older passport-saml 1.x/3.x line, most visibly cert to idpCert, and makes callbackUrl, issuer and idpCert mandatory. Code copied from older tutorials that passes cert will throw at startup.

// src/auth/samlStrategy.ts
// Tested against @node-saml/passport-saml 5.1.x and @node-saml/node-saml 5.2.x
import { MultiSamlStrategy, ValidateInResponseTo } from '@node-saml/passport-saml';
import type { Profile } from '@node-saml/passport-saml';
import { prisma } from '../db';
import { samlCache } from './samlCache';

const SP_ENTITY_ID = 'https://app.yoursaas.com/saml/metadata';
const APP_ORIGIN = 'https://app.yoursaas.com';

export const multiSamlStrategy = new MultiSamlStrategy(
  {
    passReqToCallback: true,
    getSamlOptions: async (req, done) => {
      try {
        const tenantSlug = req.params.tenantSlug;
        const tenant = await prisma.tenant.findUnique({
          where: { slug: tenantSlug },
          include: { samlConfig: true },
        });
        const config = tenant?.samlConfig;
        if (!config?.isActive) {
          return done(new Error(`No active SAML connection for tenant "${tenantSlug}"`));
        }

        return done(null, {
          callbackUrl: `${APP_ORIGIN}/api/auth/sso/${tenantSlug}/callback`,
          entryPoint: config.entryPoint,
          issuer: SP_ENTITY_ID,
          audience: SP_ENTITY_ID,

          // Trust anchors for this tenant only
          idpCert: config.idpCert,
          idpIssuer: config.idpIssuer, // rejects responses from any other issuer

          // Both default to true in v5; set explicitly so a refactor cannot weaken them
          wantAssertionsSigned: true,
          wantAuthnResponseSigned: true,

          // Replay and freshness checks, all enforced by the SP
          validateInResponseTo: ValidateInResponseTo.always,
          requestIdExpirationPeriodMs: 10 * 60 * 1000,
          cacheProvider: samlCache,
          rejectReplayedAssertions: true, // node-saml 5.2+, needs saveIfAbsentAsync
          acceptedClockSkewMs: 60 * 1000,
          maxAssertionAgeMs: 5 * 60 * 1000,

          signatureAlgorithm: 'sha256', // used when signing AuthnRequests
        });
      } catch (error) {
        return done(error as Error);
      }
    },
  },
  // Sign-on verify: hand the validated profile to the route handler
  (req, profile: Profile | null, done) => {
    if (!profile) return done(new Error('Empty SAML profile'));
    return done(null, profile as unknown as Record<string, unknown>);
  },
  // Logout verify: required by the constructor; implement SLO later if needed
  (req, profile, done) => done(null, profile as unknown as Record<string, unknown>),
);

What each security option does, and why it is set here:

OptionDefault in v5Setting hereProtects against
idpCertnone (required)per tenantForged responses signed by anyone else
idpIssuerunset (not checked)per tenantA response from a different IdP that happens to be trusted elsewhere
audiencevalue of issuerSP entity IDAssertions minted for another service provider
wantAssertionsSignedtruetrueUnsigned assertions inside a signed envelope
wantAuthnResponseSignedtruetrueUnsigned top-level responses
validateInResponseTo"never""always"Responses your SP never requested, and request ID reuse
rejectReplayedAssertionsofftrueThe same assertion being posted twice
acceptedClockSkewMs060 secondsSpurious failures from small clock drift between IdP and SP
maxAssertionAgeMs0 (no extra limit)5 minutesOld but still-unexpired assertions being reused

Two trade-offs to decide consciously:

  • validateInResponseTo: always disables IdP-initiated SSO, where the user clicks your app tile in the Okta dashboard without your SP sending a request first. Many enterprise customers expect the tile to work. A common pattern is to make the tile point at your /login route (SP-initiated), which most IdPs support as a "bookmark" or "initiate login URI" setting. If you must accept IdP-initiated responses, use ifPresent and rely on rejectReplayedAssertions and maxAssertionAgeMs for replay protection.
  • Clock skew should be small. A minute absorbs normal NTP drift; several minutes widens the replay window.

A shared cache for request IDs and assertion IDs

The default InMemoryCacheProvider lives in one Node.js process. Behind a load balancer, the login request may be generated on one instance and the response arrive at another, which fails InResponseTo validation, and replay detection only sees its own process. Use a shared store. This Redis implementation covers the CacheProvider interface in node-saml 5.2, including the atomic methods used for replay protection:

// src/auth/samlCache.ts
// Requires Redis 6.2+ for GETDEL. Uses ioredis.
import Redis from 'ioredis';
import type { CacheProvider, CacheItem } from '@node-saml/passport-saml';

const redis = new Redis(process.env.REDIS_URL!);
const TTL_SECONDS = 10 * 60; // match requestIdExpirationPeriodMs
const key = (k: string) => `saml:${k}`;

export const samlCache: CacheProvider = {
  async saveAsync(k, value): Promise<CacheItem | null> {
    const createdAt = Date.now();
    await redis.set(key(k), value, 'EX', TTL_SECONDS);
    return { value, createdAt };
  },
  async getAsync(k) {
    return redis.get(key(k));
  },
  async removeAsync(k) {
    if (!k) return null;
    const value = await redis.get(key(k));
    await redis.del(key(k));
    return value;
  },
  // Atomic consume: of two concurrent copies of a response, only one wins
  async consumeAsync(k) {
    return redis.getdel(key(k));
  },
  // Atomic set-if-absent, used by rejectReplayedAssertions
  async saveIfAbsentAsync(k, value, expiresAtMs) {
    const ttlMs = Math.max(1, expiresAtMs - Date.now());
    const result = await redis.set(key(k), value, 'PX', ttlMs, 'NX');
    return result === 'OK';
  },
};

When the IdP posts back, passport.authenticate('saml') runs the strategy, validates the response with the tenant's options, and places the profile on req.user. The route handler then resolves the local user and issues your own session.

The earlier version of this post redirected to https://app.yoursaas.com/auth/callback?token=<jwt>. That leaks a bearer token into browser history, server and proxy logs, analytics tools and potentially Referer headers, and it contradicts the approach in our HttpOnly cookie JWT guide. Set the cookie directly on the ACS response instead and redirect with no secret in the URL. If your API runs on a different site than the ACS, use a short-lived, single-use code in the redirect and exchange it server to server for the session.

// src/routes/saml.routes.ts
import { Router } from 'express';
import passport from 'passport';
import jwt from 'jsonwebtoken';
import type { Profile } from '@node-saml/passport-saml';
import { prisma } from '../db';

const router = Router();

const EMAIL_CLAIM = 'http://schemas.xmlsoap.org/ws/2005/05/identity/claims/emailaddress';

// SP-initiated login: redirects to the tenant's IdP and caches the request ID for InResponseTo checks
router.get('/:tenantSlug/login', passport.authenticate('saml', { session: false }));

// ACS endpoint: receives the POST from Okta / Entra ID
router.post(
  '/:tenantSlug/callback',
  passport.authenticate('saml', { session: false, failureRedirect: '/login?error=sso' }),
  async (req, res, next) => {
    try {
      const profile = req.user as unknown as Profile;
      const tenant = await prisma.tenant.findUniqueOrThrow({
        where: { slug: req.params.tenantSlug },
        include: { samlConfig: true },
      });

      // Defense in depth: node-saml already enforced idpIssuer, check it again before linking
      if (profile.issuer !== tenant.samlConfig?.idpIssuer) {
        return res.status(403).send('Unexpected SAML issuer');
      }

      const attributes = profile as unknown as Record<string, unknown>;
      const email = String(profile.email ?? profile.mail ?? attributes[EMAIL_CLAIM] ?? '')
        .trim()
        .toLowerCase();
      if (!profile.nameID || !email) return res.status(400).send('Missing NameID or email');

      const identity = {
        tenantId: tenant.id,
        idpIssuer: profile.issuer,
        nameId: profile.nameID,
      };

      // Look up by the federation key, never by global email
      let user = await prisma.user.findUnique({
        where: { tenantId_idpIssuer_nameId: identity },
      });

      if (!user) {
        // JIT provisioning, scoped to this tenant. If a same-tenant user with this email
        // already exists, the create fails on @@unique([tenantId, email]); link it only
        // through an explicit, domain-verified flow rather than silently here.
        user = await prisma.user.create({ data: { ...identity, email } });
      }

      if (!user.isActive) return res.status(403).send('Account deactivated');

      const session = jwt.sign({ sub: user.id, tid: tenant.id }, process.env.JWT_SECRET!, {
        expiresIn: '15m',
      });

      res.cookie('__Host-session', session, {
        httpOnly: true,
        secure: true,
        sameSite: 'lax', // the follow-up redirect is a top-level GET, so Lax is sent
        path: '/',
        maxAge: 15 * 60 * 1000,
      });
      return res.redirect(303, '/app');
    } catch (error) {
      return next(error);
    }
  },
);

export { router as samlRouter };

Notes on the important lines:

  • profile.issuer check. With idpIssuer configured, node-saml rejects mismatched issuers before your handler runs. The explicit comparison documents the invariant and protects against a future config change that drops idpIssuer.
  • tenantId_idpIssuer_nameId is the compound unique input Prisma generates from @@unique([tenantId, idpIssuer, nameId]).
  • Claim names vary by IdP. node-saml populates profile.email from email or mail attributes; Entra ID typically sends the long emailaddress claim URI. Map attributes per IdP in configuration, not with growing || chains.
  • __Host- cookie prefix forces Secure, Path=/ and no Domain attribute, so a sibling subdomain cannot overwrite it.
  • A 15 minute session keeps the window short after deprovisioning; pair it with a refresh flow that rechecks isActive.

Security warning: SAML implementations have a long history of XML Signature Wrapping (XSW) bugs. Keep @node-saml/node-saml updated, subscribe to its GitHub security advisories, and never read user data from the raw response XML. node-saml's own type docs warn that response-level data outside the signed assertion must not be treated as authenticated.

Testing Locally Without a Customer IdP

You do not need a customer's Okta tenant to develop this. The community image kristophjunge/test-saml-idp runs SimpleSAMLphp as an IdP. It is a testing tool, not something to deploy.

# docker-compose.yml for local SAML testing
services:
  saml-idp:
    image: kristophjunge/test-saml-idp
    ports:
      - '8080:8080'
      - '8443:8443'
    environment:
      SIMPLESAMLPHP_SP_ENTITY_ID: https://app.yoursaas.com/saml/metadata
      SIMPLESAMLPHP_SP_ASSERTION_CONSUMER_SERVICE: http://localhost:3000/api/auth/sso/acme-corp/callback
      SIMPLESAMLPHP_SP_SINGLE_LOGOUT_SERVICE: http://localhost:3000/api/auth/sso/acme-corp/logout

Steps:

  1. Run docker compose up -d.
  2. Open http://localhost:8080/simplesaml/saml2/idp/metadata.php and copy the entityID into SamlConfig.idpIssuer, the SingleSignOnService location into entryPoint, and the signing certificate into idpCert.
  3. Point APP_ORIGIN at http://localhost:3000 in development so the callbackUrl matches the ACS URL configured above. Set secure cookies only behind HTTPS, or test over a local TLS proxy.
  4. Visit http://localhost:3000/api/auth/sso/acme-corp/login and sign in as user1 / user1pass (the image's default test user).

Then write negative tests, which matter more than the happy path:

  • Swap idpCert for a different certificate and confirm the login fails.
  • Change idpIssuer and confirm the login fails.
  • Replay a captured SAMLResponse POST and confirm the second attempt is rejected.
  • Configure a second tenant whose IdP asserts the same email as a user in the first tenant, and confirm it creates a separate user rather than signing into the existing one.

Automating Onboarding with SCIM 2.0 Provisioning

SAML signs people in. SCIM keeps the user list in sync so IT does not manage your app by hand.

Authenticating the IdP with a hashed bearer token

Generate a token per tenant as <tokenId>.<secret>, show it to the customer once, and store only the token ID and a SHA-256 hash of the secret. A plaintext token in the database means any read-only database leak, backup or log export grants write access to every customer's user directory.

// src/middleware/scimAuth.ts
import { createHash, randomBytes, timingSafeEqual } from 'node:crypto';
import type { Request, Response, NextFunction } from 'express';
import { prisma } from '../db';

const sha256 = (value: string) => createHash('sha256').update(value).digest();

export function generateScimToken() {
  const tokenId = randomBytes(9).toString('base64url');
  const secret = randomBytes(32).toString('base64url');
  return {
    plaintext: `${tokenId}.${secret}`, // show once, never store
    tokenId,
    tokenHash: sha256(secret).toString('hex'),
  };
}

function scimError(res: Response, status: number, detail: string) {
  return res.status(status).json({
    schemas: ['urn:ietf:params:scim:api:messages:2.0:Error'],
    status: String(status), // RFC 7644 section 3.12: status is a JSON string
    detail,
  });
}

export async function authenticateScimBearer(req: Request, res: Response, next: NextFunction) {
  const header = req.get('authorization') ?? '';
  const [scheme, token] = header.split(' ');
  const [tokenId, secret] = (token ?? '').split('.');
  if (scheme !== 'Bearer' || !tokenId || !secret) return scimError(res, 401, 'Unauthorized');

  const tenant = await prisma.tenant.findUnique({ where: { scimTokenId: tokenId } });
  const expected = tenant?.scimTokenHash ? Buffer.from(tenant.scimTokenHash, 'hex') : null;
  const actual = sha256(secret);

  // Both buffers are 32 bytes, so timingSafeEqual never throws on length mismatch
  if (!tenant || !expected || !timingSafeEqual(expected, actual)) {
    return scimError(res, 401, 'Unauthorized');
  }

  res.locals.tenantId = tenant.id;
  return next();
}

A fast hash is appropriate here because the secret is 256 bits of randomness; slow password hashes such as bcrypt exist to protect low-entropy human passwords. Rotation is simple: generate a new token, let the customer update their IdP, then overwrite the stored ID and hash.

Creating and looking up users

Before creating a user, Okta sends GET /Users?filter=userName eq "<value>" and links to an existing record if one matches. RFC 7644 section 3.3 requires a 409 Conflict with scimType: "uniqueness" when a create would duplicate a unique attribute. Implement both, or the IdP will report errors on every re-sync.

// src/routes/scim.routes.ts
import { Router } from 'express';
import { Prisma, type User } from '@prisma/client';
import { prisma } from '../db';

const router = Router();

const toScimUser = (user: User) => ({
  schemas: ['urn:ietf:params:scim:schemas:core:2.0:User'],
  id: user.id,
  externalId: user.scimExternalId ?? undefined,
  userName: user.email,
  name: { givenName: user.firstName ?? '', familyName: user.lastName ?? '' },
  emails: [{ primary: true, value: user.email }],
  active: user.isActive,
  meta: { resourceType: 'User' },
});

const listResponse = (users: User[]) => ({
  schemas: ['urn:ietf:params:scim:api:messages:2.0:ListResponse'],
  totalResults: users.length,
  startIndex: 1,
  itemsPerPage: users.length,
  Resources: users.map(toScimUser),
});

router.get('/Users', async (req, res) => {
  const tenantId = res.locals.tenantId as string;
  // Supports the userName eq "..." filter IdPs use before creating a user
  const match = /^userName eq "([^"]+)"$/.exec(String(req.query.filter ?? ''));
  const users = await prisma.user.findMany({
    where: { tenantId, ...(match ? { email: match[1].toLowerCase() } : {}) },
    take: 100, // add startIndex/count paging (RFC 7644 section 3.4.2.4) for large tenants
  });
  res.type('application/scim+json').json(listResponse(users));
});

router.post('/Users', async (req, res) => {
  const tenantId = res.locals.tenantId as string;
  const body = req.body;
  const email = String(
    body.emails?.find((e: { primary?: boolean }) => e.primary)?.value ?? body.userName ?? '',
  )
    .trim()
    .toLowerCase();
  if (!email) return res.status(400).json({ detail: 'userName is required', status: '400' });

  try {
    const user = await prisma.user.create({
      data: {
        tenantId,
        email,
        firstName: body.name?.givenName,
        lastName: body.name?.familyName,
        scimExternalId: body.externalId,
        isActive: body.active ?? true,
      },
    });
    res.status(201).type('application/scim+json').json(toScimUser(user));
  } catch (error) {
    if (error instanceof Prisma.PrismaClientKnownRequestError && error.code === 'P2002') {
      return res.status(409).json({
        schemas: ['urn:ietf:params:scim:api:messages:2.0:Error'],
        status: '409',
        scimType: 'uniqueness',
        detail: 'User already exists in this tenant',
      });
    }
    throw error;
  }
});

export { router as scimRouter };

Notice that the SCIM externalId is stored in scimExternalId, not in the SAML nameId column. They often hold different values: Okta's externalId is its internal user ID, while the SAML NameID is commonly the user's email. Mixing them breaks the link between a provisioned user and their first SSO login. When the first SAML login arrives for a SCIM-created user, the JIT create hits @@unique([tenantId, email]); resolve that by attaching idpIssuer and nameId to the existing same-tenant user, which is safe here because SCIM proved the tenant's directory owns that account.

Deprovisioning: PATCH active=false and DELETE

Offboarding is the requirement security teams check most carefully. Okta's SCIM guide states that it does not send DELETE for users: it deactivates them with a PATCH that replaces active with false (or a PUT for some custom integrations). Other clients do use DELETE, which RFC 7644 section 3.6 says returns 204 No Content. Support both, and soft-delete in both cases so foreign keys on the user's documents and audit logs stay intact.

// src/routes/scim.routes.ts (continued)

router.patch('/Users/:id', async (req, res) => {
  const tenantId = res.locals.tenantId as string;
  const ops: Array<{ op: string; path?: string; value?: unknown }> = req.body.Operations ?? [];

  // Okta sends { op: "replace", value: { active: false } }; others send path: "active"
  let active: boolean | undefined;
  for (const op of ops) {
    if (op.op.toLowerCase() !== 'replace') continue;
    if (op.path === 'active') active = Boolean(op.value);
    else if (typeof op.value === 'object' && op.value && 'active' in op.value) {
      active = Boolean((op.value as { active: unknown }).active);
    }
  }

  // Tenant scoping on every read and write
  let user = await prisma.user.findFirst({ where: { id: req.params.id, tenantId } });
  if (!user) return res.status(404).json({ status: '404', detail: 'User not found' });

  if (active !== undefined) {
    user = await prisma.user.update({ where: { id: user.id }, data: { isActive: active } });
  }
  res.type('application/scim+json').json(toScimUser(user));
});

router.delete('/Users/:id', async (req, res) => {
  const tenantId = res.locals.tenantId as string;
  const { count } = await prisma.user.updateMany({
    where: { id: req.params.id, tenantId },
    data: { isActive: false },
  });
  if (count === 0) return res.status(404).json({ status: '404', detail: 'User not found' });
  res.status(204).send();
});

Filtering on both id and tenantId means a token for Tenant A can never deactivate a user in Tenant B, even with a guessed ID.

Making deactivation take effect immediately

Flipping isActive does nothing if existing sessions stay valid. A stateless JWT stays valid until it expires, so either keep access tokens short (the 15 minutes above) and recheck isActive on refresh, or check it on every request:

// src/middleware/requireUser.ts
import jwt from 'jsonwebtoken';
import type { Request, Response, NextFunction } from 'express';
import { prisma } from '../db';

export async function requireUser(req: Request, res: Response, next: NextFunction) {
  try {
    const token = req.cookies['__Host-session']; // requires cookie-parser
    const claims = jwt.verify(token, process.env.JWT_SECRET!) as { sub: string; tid: string };
    const user = await prisma.user.findFirst({
      where: { id: claims.sub, tenantId: claims.tid, isActive: true },
    });
    if (!user) return res.status(401).end();
    res.locals.user = user;
    return next();
  } catch {
    return res.status(401).end();
  }
}

A per-request lookup costs one indexed query; cache it briefly in Redis if it shows up in profiles. That is what lets you answer the questionnaire item "access is revoked within N minutes of offboarding" with a concrete number.

Build vs. Buy: Making the Decision Honestly

Building is not free. You take on certificate rotation (IdPs roll signing certificates, so idpCert should accept multiple values during a rollover), per-IdP attribute quirks, customer onboarding support, and security patching for a component attackers target. Buying moves that work to a vendor for a recurring fee.

FactorManaged provider (WorkOS, Auth0, Clerk, etc.)In-house with node-saml
Time to first enterprise SSOShortest; admin portal and IdP guides includedLonger; you build onboarding and docs
Cost modelRecurring, often per connection or plan tierEngineering time plus ongoing maintenance
IdP quirks and cert rotationVendor handlesYou handle
Data residency and controlIdentity data passes through the vendorStays in your infrastructure
Security patchingVendor's responsibilityYours: watch node-saml advisories

Check current vendor pricing pages before modelling cost; they change. A useful rule: if enterprise SSO is a blocker for your first one or two deals, buying is usually faster; if it is core to your product and you have engineers comfortable owning security-critical code, building gives you control. Our buy vs. build authentication guide goes deeper on this decision.

When identity federation becomes part of a larger platform effort, it tends to touch tenancy, sessions and audit logging at once; that cross-cutting API work is what our backend development services team focuses on.

Common Mistakes and Failure Modes

  • Global email lookup on SAML login. Enables cross-tenant account takeover. Use the tenant-scoped federation key.
  • No idpIssuer. Without it, any response signed with the configured certificate is accepted regardless of the issuer it claims.
  • Passing cert to v5. Throws because idpCert is required.
  • In-memory cache behind a load balancer. Produces intermittent InResponseTo failures and per-process replay detection.
  • Token in the redirect URL. Leaks sessions to logs and history. Use an HttpOnly cookie or a one-time code exchange.
  • Plaintext SCIM tokens. A database read becomes directory write access.
  • Only implementing SCIM DELETE. Okta deactivates with PATCH, so offboarding silently does nothing.
  • Ignoring application/scim+json. Leaves req.body empty.
  • Hard deletes. Break foreign keys and destroy audit history.
  • Long-lived JWTs with no isActive check. Deprovisioned users keep access until expiry.

Production Readiness Checklist

  • @node-saml/passport-saml 5.x and @node-saml/node-saml 5.2+ pinned, with security advisories watched
  • Per-tenant idpCert, idpIssuer and entryPoint, editable by tenant admins with an audit log entry
  • wantAssertionsSigned and wantAuthnResponseSigned explicitly true
  • validateInResponseTo, rejectReplayedAssertions, maxAssertionAgeMs and acceptedClockSkewMs set deliberately, with a shared Redis cache
  • Users keyed on (tenantId, idpIssuer, nameId); no global email uniqueness
  • Session delivered as an HttpOnly, Secure __Host- cookie; no tokens in URLs
  • SCIM tokens stored as SHA-256 hashes, compared with timingSafeEqual, rotatable
  • SCIM GET with userName eq filter, POST with 409 uniqueness, PATCH active, DELETE
  • Rate limiting and audit logging on /scim/v2
  • isActive enforced on every request or on short-lived token refresh
  • Negative tests for wrong cert, wrong issuer, replay and cross-tenant email collision
  • SP metadata endpoint published for customers, and a runbook for certificate rollover

For teams that also want phishing-resistant sign-in for users outside SSO, see our guide to passkeys and WebAuthn in B2B SaaS. For proving offboarding to auditors, the SOC 2 audit log guide pairs well with the SCIM endpoints above.

Sources

Available for Work

Need help building this in production?

SoftwareCrafting is a full-stack dev agency - we ship fast, scalable React, Next.js, Node.js, React Native & Flutter apps for global clients.

Get a Free Consultation

Frequently Asked Questions

What is the difference between SAML SSO and SCIM?

SAML handles sign-in: the customer identity provider, such as Okta or Microsoft Entra ID, authenticates users and tells your app who they are. SCIM handles provisioning: the identity provider creates, updates, and deactivates user accounts in your app automatically.

How do I support SAML for many customers in one Node.js app?

Store a SAML configuration per tenant (IdP entity ID, SSO URL and signing certificate), resolve it from the ACS URL with MultiSamlStrategy, and pass it as idpIssuer, entryPoint and idpCert. Validate signatures, issuer, audience, timestamps and InResponseTo on every login, and key users on tenant, issuer and NameID.

Why can't I match SAML users by email?

Each customer controls their own IdP and can assert any email address. If your lookup is not scoped to the tenant and issuer that sent the response, one customer's IdP can sign in as another customer's user.

Does Okta send SCIM DELETE requests?

According to Okta's SCIM documentation, no. Okta deactivates users with a PATCH that sets active to false (or a PUT for some custom integrations). Other SCIM clients may send DELETE, so support both.

Should I build SAML and SCIM or use a provider?

A provider gets you to market faster and usually charges per connection or by plan tier. Building in-house avoids that recurring cost and keeps identity data in your infrastructure, but you own security patching, certificate rotation and each IdP's quirks.

About the author

Deepak Rajput

Founder and CEO of SoftwareCrafting

Deepak Rajput is the Founder and CEO of SoftwareCrafting in Delhi and writes about web, mobile, backend, cloud, security, and engineering leadership.

Writes about Next.js, Node.js, React Native, PostgreSQL, AWS, Kubernetes.

View author profile

Last updated: 2026-10-27