TL;DR: Single sign-on proves who someone is at login. It says nothing about what happens when that person leaves the customer's company at 9:05 on a Friday. For B2B SaaS, enterprise readiness means three separate mechanisms working together: SCIM to create, update and deactivate accounts, a session and token revocation path that makes deactivation take effect in seconds, and an audit trail that proves it. This article walks through the architecture, the protocol details that matter (all traced to the RFCs and OpenID specifications), working code for the two hardest endpoints, and the mistakes that turn up in enterprise security reviews.

Why SSO alone leaves a gap

Most teams add SAML or OpenID Connect (OIDC) first because the first enterprise prospect demands it. That solves authentication: the customer's identity provider (IdP) vouches for the user, and your application starts a session.

Three things stay unsolved:

  1. Account lifecycle. With just-in-time (JIT) provisioning, your app creates a user the first time they sign in. Nothing ever tells your app that the user has since left, changed teams or lost a role. The account simply sits there, active, in your database.
  2. Live sessions. If an employee is removed from the IdP at 09:05, their browser session in your app is still valid until your own timeouts expire. Their API keys and refresh tokens may outlive that by days.
  3. Evidence. Security questionnaires ask how quickly access is removed after termination. "When they next try to log in" is an answer that ends deals.

This is engineering judgement rather than a quotation from any spec, but it matches how the standards divide the work: SCIM (RFC 7643 and RFC 7644) handles the lifecycle, OIDC and SAML handle authentication, and the OpenID Foundation's back-channel logout and Continuous Access Evaluation Profile (CAEP) handle the session side. You need pieces from each.

The reference architecture

mermaid
sequenceDiagram
    participant HR as HR system
    participant IdP as Customer IdP
    participant SCIM as Your SCIM endpoint
    participant Core as Identity service
    participant Sess as Session and token stores
    participant App as Your application

    HR->>IdP: Employee terminated
    IdP->>SCIM: PATCH /Users/{id} active=false
    SCIM->>Core: deactivate(user)
    Core->>Sess: revoke sessions, refresh tokens, API keys
    Core->>Core: append audit event
    IdP->>App: Back-channel logout token (sid or sub)
    App->>Sess: revoke matching session
    App-->>IdP: 200 OK

Three components carry the weight:

  • A tenant-scoped SCIM service that translates SCIM resources into your internal user and role model. It should never be a thin wrapper that lets the IdP write directly to your user table.
  • An identity service that owns a single "deactivate" operation. SCIM PATCH, SCIM DELETE, an admin clicking "suspend" and a back-channel logout all call the same code path, so no route forgets to kill a token type.
  • A revocation layer that every request passes through: session lookups, access-token checks and API-key checks all consult the user's state.

SCIM: the parts that matter in practice

SCIM 2.0 is defined by RFC 7643 (the schema) and RFC 7644 (the protocol). You do not need every feature. You do need to get the following right.

Identifiers: id, externalId and userName

RFC 7643 section 3.1 says id is issued by the service provider (you), is unique, stable and read-only, and that clients must not specify it. externalId is the identifier from the provisioning client and is scoped to the client's provisioning domain. RFC 7643 section 4.1.1 requires userName on every User, defines it as case-insensitive, and requires it to be unique across all Users on the provider.

Practical consequences:

  • Store externalId per tenant and index it, because IdPs often look users up by it.
  • Enforce userName uniqueness per tenant, not globally. Two customers may both have alex@... style names. A duplicate within a tenant must return HTTP 409 with scimType of uniqueness (RFC 7644 section 3.3).
  • Treat userName as mutable. Employees change names. Your internal primary key must be your own id, never the email address.

Deactivation: PATCH active=false versus DELETE

RFC 7643 section 4.1.1 defines active as "a Boolean value indicating the user's administrative status", and leaves its exact meaning to the provider, with false typically meaning suspended. RFC 7644 section 3.6 says that on DELETE the provider may choose not to permanently delete the resource, but must return 404 for all subsequent operations on it, must omit it from query results, and on success returns 204 No Content.

In our experience, IdPs differ in which they send for a leaver. Some send PATCH with active: false, others send DELETE. This is judgement drawn from integration work, not something the RFCs mandate, so build your endpoint to treat both as "this person must lose access now":

  • active=false: keep the record for audit and re-hire, block login, revoke everything.
  • DELETE: respond 204, then apply the same revocation. If your retention policy needs the data, soft-delete internally and honour the 404 rule externally.

RFC 7644 section 3.6 also says a later CREATE with the same userName should not fail with a 409 because of a deleted resource. That matters for rehires: if your soft-deleted row still holds the unique constraint, the re-hire fails and someone raises a support ticket. Scope the unique index to non-deleted rows, or tombstone the username on delete.

PATCH semantics

RFC 7644 section 3.5.2 defines PATCH. Each request carries the schema urn:ietf:params:scim:api:messages:2.0:PatchOp and an Operations array. Every operation has an op of add, remove or replace. path is optional for add and replace but required for remove, and a remove without a path fails with 400 and scimType noTarget. The request is atomic: if one operation fails, the resource is restored to its original state.

A deactivation request looks like this:

json
{
  "schemas": ["urn:ietf:params:scim:api:messages:2.0:PatchOp"],
  "Operations": [
    { "op": "replace", "path": "active", "value": false }
  ]
}

Be liberal in what you accept. Some IdPs send the value as the string "False", or send active inside a value object with no path. Both are variations of the same intent. Normalise them in one place, and log the raw body for the first few weeks of any new integration so you can see what a given IdP does.

Groups and roles

RFC 7643 section 4.1.2 marks the groups attribute on a User as read-only. Membership is changed through the Group resource. So if your role model hangs off group membership, you must implement PATCH /Groups/{id} with add and remove operations on members, and recompute effective permissions when membership changes.

A design that works well: map IdP groups to your roles through an explicit per-tenant mapping table, rather than treating group display names as roles. A group renamed in the IdP then does not silently remove admin rights, and an unmapped group grants nothing.

Filtering, pagination and discovery

IdPs reconcile by asking "do you already have this user?" using a filter such as userName eq "[email protected]". RFC 7644 section 3.4.2.2 defines the operators (eq, ne, co, sw, ew, pr, gt, ge, lt, le, plus and, or, not). Filtering is optional, but in practice you need at least eq on userName and externalId; unsupported operators must return 400 with scimType invalidFilter.

Pagination uses startIndex (1-based) and count. The server must not return more than count but may return fewer (section 3.4.2.4). Pagination is not stateful, so results can shift between pages. Publish what you support at /ServiceProviderConfig (RFC 7644 section 4), including whether PATCH, filter and ETag are available, so clients adapt rather than guess.

Authentication of the SCIM endpoint itself

RFC 7644 section 2 leaves authentication to TLS and standard HTTP schemes, recommends bearer tokens used with TLS and a framework such as OAuth 2.0, and says Basic authentication should be avoided. It also says the provider must map each authenticated client to an access control policy. This is the part teams skip: a SCIM token that can create users and assign groups is effectively an admin credential for that tenant. Issue it per tenant, scope it to that tenant's data only, make it rotatable, and alert when it is used from an unexpected network.

Session revocation: where deprovisioning actually succeeds or fails

SCIM changes a database row. A person's browser, mobile app and scripts do not care about that row until something checks it. The work is making every credential type consult user state, or die when the user is deactivated.

Inventory your credentials

List every way a human identity can reach your system. A typical B2B SaaS has:

CredentialTypical lifetimeWhat kills it on deactivation
Browser session cookieIdle and absolute timeoutsServer-side session delete
OIDC refresh token you issuedDays to monthsRevoke family of tokens (RFC 7009)
JWT access tokenMinutesWait for expiry, or check a deny list or introspect
Personal API keyUntil revokedOwner deactivation cascades to key
OAuth grants to third-party appsUntil revokedRevoke grants held by that user
Long-lived export or webhook tokens created by the userOften foreverDecide: re-own to a service account, or revoke

The last two rows cause most real incidents. A departed employee's personal API key, still running an integration, is a classic finding.

Server-side sessions are the foundation

The OWASP Session Management Cheat Sheet says an application must invalidate the session at least on the server side at logout, and that deleting the cookie client-side is not enough because a stolen session ID would still work. It also recommends both idle and absolute timeouts, enforced on the server. The cheat sheet does not specifically cover revoking sessions when an account is disabled, so that requirement is our judgement, but it follows directly: disabling an account is a logout you perform on the user's behalf, and it needs the same server-side kill.

That implies a server-side session store you can query by user. Pure stateless cookies make deactivation depend on timeouts alone.

Access tokens: choose your window deliberately

Stateless JWT access tokens are fast to verify and impossible to revoke before expiry unless you add state. There are three honest options:

  1. Short lifetimes. Accept that a deactivated user keeps access for the remaining life of the token. Pick a lifetime your customers' security teams will accept, and write the number into your security documentation.
  2. Introspection. RFC 7662 lets a resource server ask the authorization server whether a token is active. It is exact, at the cost of a network call or a cache.
  3. A deny list keyed by user and token version. Embed a per-user token_version or sid, increment it on deactivation, and have the verifier compare against a fast cache. This gives near-immediate revocation without a call per request.

RFC 7009 defines the revocation endpoint for clients to invalidate access and refresh tokens, which is the interface you should expose and use internally when revoking a refresh-token family.

A single deactivation function

Here is a compact sketch of the core operation. The point is the structure: one transaction, one place, every credential type.

python
from datetime import datetime, timezone

def deactivate_user(tenant_id: str, user_id: str, actor: str, reason: str) -> None:
    """Called by SCIM PATCH/DELETE, admin UI, and logout events alike."""
    with db.transaction() as tx:
        user = tx.users.get_for_update(tenant_id, user_id)
        if user is None or not user.active:
            return  # idempotent: the IdP will retry

        user.active = False
        user.token_version += 1            # invalidates JWTs checked against it
        user.deactivated_at = datetime.now(timezone.utc)

        tx.sessions.delete_where(user_id=user_id)
        tx.refresh_tokens.revoke_where(user_id=user_id)
        tx.api_keys.revoke_where(owner_id=user_id)
        tx.oauth_grants.revoke_where(user_id=user_id)

        tx.audit.append(
            tenant_id=tenant_id,
            event="user.deactivated",
            subject=user_id,
            actor=actor,          # e.g. "scim:<token id>" or "admin:<id>"
            reason=reason,
        )
        # Enqueued in the same transaction so it only fires if we commit.
        tx.outbox.enqueue("cache.evict_user", {"tenant": tenant_id, "user": user_id})

Three details here earn their keep. The function is idempotent, because IdPs retry and may send both a PATCH and a DELETE. The audit entry is written in the same transaction as the state change, so you can never have a deactivation with no evidence or evidence without a deactivation. And cache eviction goes through a transactional outbox rather than an inline call, so a Redis blip cannot leave a revoked user cached as active.

Closing the loop with logout signals from the IdP

SCIM tells you the account is gone. Back-channel logout and CAEP tell you the session should end, including cases where the account is not deleted at all (a forced sign-out after a risk event, for example).

OIDC Back-Channel Logout

OpenID Connect Back-Channel Logout 1.0 has the OP (your customer's IdP) POST a signed Logout Token to a URI you register as backchannel_logout_uri. Per section 2.4, the token must contain iss, aud, iat, exp, jti and an events claim holding the member http://schemas.openid.net/event/backchannel-logout. It must contain sub, sid or both. It must not contain nonce. Section 2.6 lists the validation steps: verify the signature, reject alg of none, validate iss, aud, iat and exp, confirm sub or sid is present, confirm the events member, confirm nonce is absent, and optionally check jti for replay. On failure you return HTTP 400; on success, 200 (the OP should also accept 204), and the response should carry Cache-Control: no-store.

A working validation sketch with PyJWT:

python
import jwt
from jwt import PyJWKClient

BCL_EVENT = "http://schemas.openid.net/event/backchannel-logout"

def handle_backchannel_logout(logout_token: str, tenant) -> tuple[int, dict]:
    try:
        key = PyJWKClient(tenant.jwks_uri).get_signing_key_from_jwt(logout_token).key
        claims = jwt.decode(
            logout_token,
            key,
            algorithms=["RS256", "ES256"],          # never "none"
            audience=tenant.client_id,
            issuer=tenant.issuer,
            options={"require": ["iss", "aud", "iat", "exp", "jti"]},
        )
    except jwt.PyJWTError:
        return 400, {"error": "invalid_request"}

    if BCL_EVENT not in claims.get("events", {}):
        return 400, {"error": "invalid_request"}
    if "nonce" in claims:
        return 400, {"error": "invalid_request"}
    if not (claims.get("sid") or claims.get("sub")):
        return 400, {"error": "invalid_request"}

    # Replay protection: jti must be new (store with TTL >= token lifetime).
    if not replay_cache.set_if_absent(f"bcl:{tenant.id}:{claims['jti']}", ttl=600):
        return 400, {"error": "invalid_request"}

    if claims.get("sid"):
        sessions.revoke_by_idp_session(tenant.id, claims["iss"], claims["sid"])
    else:
        sessions.revoke_all_for_subject(tenant.id, claims["iss"], claims["sub"])
    return 200, {}

Two things to note. First, you need to have stored the IdP's sid against your own session when the user logged in (from the ID Token), otherwise there is nothing to match. Second, the backchannel_logout_session_required registration metadata lets you demand that the IdP include sid; setting it makes revocation precise to one session rather than every session for the subject.

Front-channel logout and SAML Single Logout both depend on the user's browser to carry the message, which means a closed tab or an offline laptop breaks them. That is our engineering judgement, not a spec statement. SAML 2.0 does define a Single Logout profile in the OASIS profiles specification, so support it if a customer insists, but do not rely on it as your only mechanism.

CAEP: continuous access evaluation

The OpenID Continuous Access Evaluation Profile 1.0, published on 29 August 2025, defines security events that transmitters can send to receivers over the Shared Signals Framework. The Session Revoked event type is https://schemas.openid.net/secevent/caep/event-type/session-revoked. It has no event-specific claims; optional common claims include event_timestamp, initiating_entity (admin, user, policy or system) and the reason fields, and the subject can be identified in several ways, including opaque session IDs and complex subjects combining user, session, device and tenant. The spec says the event means the session identified by the subject has been revoked, and does not prescribe further receiver behaviour, so what you do in response is your design decision.

Adoption varies by IdP, so treat CAEP as an additional channel to implement when a customer asks, not a replacement for SCIM and back-channel logout. If you do implement it, route it into the same deactivate_user or revoke_sessions functions described above.

Trade-offs at a glance

MechanismStrengthWeaknessUse it for
SCIM active=false / DELETEAuthoritative lifecycle, works without a user presentDoes not itself kill sessions or tokensJoiner, mover, leaver
Short-lived access tokensSimple, statelessRevocation delay equals token lifetimeAPI traffic where delay is tolerable
Introspection or deny listNear-immediate revocationExtra latency or cache to runHigh-risk APIs, admin actions
OIDC Back-Channel LogoutServer-to-server, no browser neededRequires sid bookkeeping, IdP supportSession termination from the IdP
CAEP session-revokedStandard risk and policy signalsLess widely deployedEnterprises with continuous access evaluation
SAML Single LogoutPresent in many legacy IdPsBrowser-dependent, fragileCustomer-mandated fallback

Compliance angle for UK, EU and US buyers

Regulators rarely name SCIM, but they do care about timely removal of access. In the EU and UK, GDPR Article 32 requires appropriate technical and organisational measures for security of processing, and access removal on role change or departure is a standard way to demonstrate it. SOC 2 and ISO 27001 audits typically sample leavers and ask for timestamps. Because the exact control wording differs by framework and auditor, map your deprovisioning evidence to the specific controls your customers cite rather than assuming one design satisfies all of them. The practical point is that your audit events, with actor, timestamp and reason, are the evidence.

Common mistakes

  1. Using email as the primary key. Names change, and an IdP-side rename then creates a duplicate user or locks the person out.
  2. Letting JIT provisioning resurrect deactivated users. If a SAML login for a deactivated user quietly re-activates or recreates them, SCIM deprovisioning is meaningless. A login for a user with active=false must fail.
  3. Forgetting non-browser credentials. Personal API keys, refresh tokens and OAuth grants outlive the cookie.
  4. Group names as roles. A renamed or shared group changes permissions without anyone deciding to.
  5. Non-idempotent handlers. IdPs retry. A second deactivation should be a no-op, not a 500 that makes the IdP back off and retry for hours.
  6. One global SCIM token. Tokens must be per tenant and scoped to that tenant.
  7. Soft-deleted rows holding unique constraints. Rehires then fail with 409, against the spirit of RFC 7644 section 3.6.
  8. Ignoring the shape of real PATCH bodies. Test against each IdP your customers use; do not rely only on spec examples.
  9. Revoking on user state but never testing it. The only proof is an automated test that deactivates a user and then asserts every credential type fails.

Implementation checklist

  • [ ] Tenant-scoped SCIM base URL and per-tenant, rotatable bearer tokens
  • [ ] /ServiceProviderConfig accurately advertises PATCH, filter and ETag support
  • [ ] GET /Users?filter=userName eq "..." and externalId eq "..." supported
  • [ ] POST, PUT, PATCH, DELETE on Users; POST, PATCH, DELETE on Groups
  • [ ] 409 with scimType uniqueness on duplicates; 404 after delete
  • [ ] One deactivate_user path used by SCIM, admin UI and logout events
  • [ ] Sessions stored server-side and queryable by user and by IdP sid
  • [ ] Refresh tokens, API keys and OAuth grants revoked on deactivation
  • [ ] Access-token revocation window chosen, documented and tested
  • [ ] Back-channel logout endpoint validates all required claims and jti replay
  • [ ] Login for active=false users always fails, including via JIT
  • [ ] Idle and absolute session timeouts enforced server-side
  • [ ] Audit event for every create, update, role change and deactivation, with actor and reason
  • [ ] Automated end-to-end test: deactivate, then assert every credential type is rejected
  • [ ] Time-to-revoke measured and reportable to customers

How Syslabs can help

Syslabs designs and builds identity and access architecture for B2B products: SCIM services, tenant-aware session and token revocation, audit trails and the test harnesses that prove deactivation works across every credential type. If you are preparing for enterprise security reviews, a short architecture review of your current lifecycle and revocation paths is usually the fastest way to find the gaps. Book a conversation at https://www.syslabs.in/book/meeting.

References