# SCIM Provisioning & Deprovisioning That Actually Removes Access

> Source: <https://dev.to/muhammadalimughal/scim-provisioning-deprovisioning-that-actually-removes-access-jjo>
> Published: 2026-11-20 16:29:07+00:00

**Recommendation:** Treat IdP deprovisioning as a full access revocation: kill sessions, tokens and invites in one transaction, and scope each tenant's hashed SCIM bearer token to its own users.
More in the playbook "Securing agents and AI tools": <https://wpnews.pro/playbooks/agent-security>

Here is a scenario I now test on every enterprise SSO integration. An employee leaves a customer company. Their IT team disables the account in the identity provider. The next morning, the ex-employee's laptop is still logged in to your SaaS app, because the session cookie is valid for 30 days and nobody told your app anything. Their personal API token, created months ago for a script, still works too. SSO did its job, which is stopping new logins. It never promised to end existing access.

That gap is why enterprise customers ask for SCIM. SCIM (System for Cross-domain Identity Management, RFC 7643 and RFC 7644) lets the customer's IdP create, update and deactivate users in your app automatically. But a SCIM endpoint that flips a database flag and does nothing else gives the customer a false sense of safety. This post is about the part that matters: deprovisioning that actually removes access.

I wrote this with help from AI tools and checked the details against RFC 7644 and the Okta and Microsoft Entra SCIM provisioning documentation. I am a Principal Software Engineer in Karachi with 9+ years building Laravel, Node and .NET SaaS backends, and everything here is defensive configuration of your own application.

**📚 Series Navigation — Enterprise SSO & Identity for B2B SaaS**

**Part 1:** [Enterprise SSO Readiness: SAML vs OIDC for B2B SaaS](https://dev.to/muhammadalimughal/enterprise-sso-readiness-saml-vs-oidc-for-b2b-saas-3jkd)
**Part 2:** [Validating SAML Responses: Signatures, Audience & Clock Skew](https://dev.to/muhammadalimughal/validating-saml-responses-signatures-audience-clock-skew-f2i)
**Part 3 (This Post):** SCIM Provisioning & Deprovisioning That Actually Removes Access
**Part 4:** Multi-Tenant Login Routing: Domain Discovery & Enforced SSO
**Part 5:** Just-in-Time Provisioning & Role Mapping From IdP Groups
**Part 6:** Break-Glass Accounts & SSO Audit Logs
*Related earlier posts:* [Session Lifecycle Hardening: Rotation, Timeouts & Server-Side Revocation](https://dev.to/muhammadalimughal/session-lifecycle-hardening-rotation-timeouts-server-side-revocation-1ep6) · [Webhooks That Stopped Arriving: Gap Detection & Reconciliation](https://dev.to/muhammadalimughal/webhooks-that-stopped-arriving-gap-detection-reconciliation-jo7)

**Direct answer:** When the IdP sends `active: false` or a DELETE for a user, your app must block login, revoke every live session, disable API tokens and pending invites, and log the change, all in one transaction-safe step. Flipping a flag without killing existing sessions and tokens leaves the ex-employee with working access.

A full SCIM server can be large. For user lifecycle, the IdPs mostly call a small set of endpoints under a tenant-specific base URL such as `https://app.example.com/scim/v2/`:

| Operation | HTTP call | Sent by IdP when | What your app must do | 
|---|---|---|---|
| Find user | `GET /Users?filter=userName eq "a@corp.com"` | Before create, to avoid duplicates | Return a ListResponse, empty if none | 
| Create | `POST /Users` | User assigned to your app | Create or link the user, return 201 with `id` | 
| Update | `PATCH /Users/{id}` | Name, email or attribute change | Apply ops, return 200 with the resource | 
| Deactivate | `PATCH /Users/{id}` with`active: false` | User unassigned or disabled | Block login and revoke all access | 
| Delete | `DELETE /Users/{id}` | Some IdPs on hard removal | Same as deactivate, then 204 | 
| Groups | `/Groups` endpoints | Group push enabled | Covered in Part 5 with role mapping | 

Okta and Entra ID both commonly deactivate with a PATCH rather than a DELETE, so the PATCH path is the one you must get right.

Each customer tenant gets its own long random bearer token for SCIM, stored hashed, shown once, and rotatable. Never reuse one global token across tenants: a token must only be able to touch its own tenant's users.

```
// app/Http/Middleware/ScimAuth.php
public function handle(Request $request, Closure $next)
{
    $token = $request->bearerToken();
    $conn = $token ? ScimConnection::where('token_hash', hash('sha256', $token))
                                   ->where('enabled', true)->first() : null;

    if (! $conn) {
        return response()->json([
            'schemas' => ['urn:ietf:params:scim:api:messages:2.0:Error'],
            'status'  => '401', 'detail' => 'Invalid SCIM token',
        ], 401);
    }
    app()->instance('scim.tenant', $conn->tenant_id);   // scope every query to this tenant
    return $next($request);
}
```

A typical deactivation request from an IdP looks like this:

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

Some IdPs send `"path": "active", "value": false` instead, and some send the value as the string `"False"`. Normalize all of these. Then the important part: deactivation calls a single service that removes every kind of access.

```
final class DeprovisionUser
{
    public function handle(User $user, string $source): void
    {
        DB::transaction(function () use ($user, $source) {
            $user->forceFill(['active' => false, 'deactivated_at' => now()])->save();

            // 1. Kill every live session (database or Redis session driver)
            DB::table('sessions')->where('user_id', $user->id)->delete();

            // 2. Revoke API tokens and OAuth grants
            $user->tokens()->delete();                       // Sanctum personal access tokens
            OAuthRefreshToken::where('user_id', $user->id)->update(['revoked' => true]);

            // 3. Cancel invites they sent and pending ones addressed to them
            Invitation::where('invited_by', $user->id)->whereNull('accepted_at')->delete();

            // 4. Record it
            AuditLog::record('user.deprovisioned', $user, ['source' => $source]);
        });

        event(new UserDeprovisioned($user));  // websockets disconnect, cache bust
    }
}
```

Because a refresh token can mint new access tokens, revoking only access tokens is not enough. And because short-lived JWT access tokens cannot be recalled, keep their lifetime short (5 to 15 minutes) and check `active` when refreshing. Part 2 of my session series covers server-side revocation in more depth.

IdPs retry. They may send the same deactivation twice, or a create for a user who already exists. Your endpoints should converge on the same state, not error out:

`POST /Users` for an existing `userName` in the same tenant either links to it or returns 409 `uniqueness`, depending on what the IdP expects; Okta and Entra docs both describe the filter-then-create flow, so support the `GET` filter correctly first.`DELETE` of an unknown id returns 404, not 500.
Match users on the stable `externalId` the IdP sends where possible, not on email, because emails change when people marry or the company renames its domain.

Deprovisioning fails quietly through paths that do not go through SSO at all. I check each of these during review:

Write a test that proves access is actually gone, not just that the flag changed:

```
# 1. Log in as the user, keep the session cookie and create an API token
# 2. Deactivate via SCIM
curl -s -X PATCH https://app.example.test/scim/v2/Users/$USER_ID \
  -H "Authorization: Bearer $SCIM_TOKEN" -H "Content-Type: application/scim+json" \
  -d '{"schemas":["urn:ietf:params:scim:api:messages:2.0:PatchOp"],"Operations":[{"op":"replace","value":{"active":false}}]}'
# 3. Both of these must now return 401
curl -s -o /dev/null -w "%{http_code}\n" -b "session=$COOKIE" https://app.example.test/dashboard
curl -s -o /dev/null -w "%{http_code}\n" -H "Authorization: Bearer $API_TOKEN" https://app.example.test/api/me
```

When I debug a failing provisioning run, I paste the IdP's request body into the [JSON Formatter](https://pixelvalut.com/tools/json-formatter?utm_source=devto&utm_medium=series&utm_campaign=scim-provisioning-deprovisioning) to spot the exact shape of the PATCH, and use the [HTTP Status Checker](https://pixelvalut.com/tools/http-status-checker?utm_source=devto&utm_medium=series&utm_campaign=scim-provisioning-deprovisioning) to confirm the SCIM base URL answers with the right status and no redirect, since some IdPs refuse to follow redirects.

`active: false` is handled in all common shapes (value object, path, string)`active` flag
No. Single logout depends on the user's browser and is unreliable across apps. It also does nothing for API tokens. SCIM is a server-to-server signal you can act on.

Usually not. Deactivate the account and keep its records, because the customer still owns the projects, invoices or tickets the person created. Offer deletion as a separate, explicit admin action.

Give the tenant admin a clear "deactivate user" button that calls the same `DeprovisionUser` service, so the result is identical whatever the trigger.

Your side should act immediately when the request arrives. The IdP's own sync interval is outside your control, which is another reason to keep access tokens short-lived.

Start with Users and the deactivation path. Add Groups when customers ask for role mapping, which Part 5 covers.

A PATCH with `active: true` should restore login only. Do not restore old sessions or tokens; the user signs in fresh and creates new ones.

Next in this series, Part 4 covers multi-tenant login routing: discovering a user's tenant from their email domain and enforcing SSO for it.
