{"slug": "scim-provisioning-deprovisioning-that-actually-removes-access", "title": "SCIM Provisioning & Deprovisioning That Actually Removes Access", "summary": "A principal software engineer in Karachi published a technical guide on implementing SCIM (RFC 7643/7644) provisioning and deprovisioning for B2B SaaS backends, arguing that deactivation must do more than flip a database flag. The guide specifies that when an identity provider sends active: false or a DELETE, the app must block login, revoke all live sessions, disable API tokens and pending invites, and log the change in a transaction-safe step, with per-tenant hashed bearer tokens scoped to a single tenant.", "body_md": "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.\n\nThat 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.\n\nI 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.\n\n**📚 Series Navigation — Enterprise SSO & Identity for B2B SaaS**\n\n**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)\n**Part 2:** [Validating SAML Responses: Signatures, Audience & Clock Skew](https://dev.to/muhammadalimughal/validating-saml-responses-signatures-audience-clock-skew-f2i)\n**Part 3 (This Post):** SCIM Provisioning & Deprovisioning That Actually Removes Access\n**Part 4:** Multi-Tenant Login Routing: Domain Discovery & Enforced SSO\n**Part 5:** Just-in-Time Provisioning & Role Mapping From IdP Groups\n**Part 6:** Break-Glass Accounts & SSO Audit Logs\n*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)\n\n**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.\n\nA 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/`:\n\n| Operation | HTTP call | Sent by IdP when | What your app must do | \n|---|---|---|---|\n| Find user | `GET /Users?filter=userName eq \"a@corp.com\"` | Before create, to avoid duplicates | Return a ListResponse, empty if none | \n| Create | `POST /Users` | User assigned to your app | Create or link the user, return 201 with `id` | \n| Update | `PATCH /Users/{id}` | Name, email or attribute change | Apply ops, return 200 with the resource | \n| Deactivate | `PATCH /Users/{id}` with`active: false` | User unassigned or disabled | Block login and revoke all access | \n| Delete | `DELETE /Users/{id}` | Some IdPs on hard removal | Same as deactivate, then 204 | \n| Groups | `/Groups` endpoints | Group push enabled | Covered in Part 5 with role mapping | \n\nOkta and Entra ID both commonly deactivate with a PATCH rather than a DELETE, so the PATCH path is the one you must get right.\n\nEach 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.\n\n```\n// app/Http/Middleware/ScimAuth.php\npublic function handle(Request $request, Closure $next)\n{\n    $token = $request->bearerToken();\n    $conn = $token ? ScimConnection::where('token_hash', hash('sha256', $token))\n                                   ->where('enabled', true)->first() : null;\n\n    if (! $conn) {\n        return response()->json([\n            'schemas' => ['urn:ietf:params:scim:api:messages:2.0:Error'],\n            'status'  => '401', 'detail' => 'Invalid SCIM token',\n        ], 401);\n    }\n    app()->instance('scim.tenant', $conn->tenant_id);   // scope every query to this tenant\n    return $next($request);\n}\n```\n\nA typical deactivation request from an IdP looks like this:\n\n```\n{\n  \"schemas\": [\"urn:ietf:params:scim:api:messages:2.0:PatchOp\"],\n  \"Operations\": [\n    { \"op\": \"replace\", \"value\": { \"active\": false } }\n  ]\n}\n```\n\nSome 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.\n\n```\nfinal class DeprovisionUser\n{\n    public function handle(User $user, string $source): void\n    {\n        DB::transaction(function () use ($user, $source) {\n            $user->forceFill(['active' => false, 'deactivated_at' => now()])->save();\n\n            // 1. Kill every live session (database or Redis session driver)\n            DB::table('sessions')->where('user_id', $user->id)->delete();\n\n            // 2. Revoke API tokens and OAuth grants\n            $user->tokens()->delete();                       // Sanctum personal access tokens\n            OAuthRefreshToken::where('user_id', $user->id)->update(['revoked' => true]);\n\n            // 3. Cancel invites they sent and pending ones addressed to them\n            Invitation::where('invited_by', $user->id)->whereNull('accepted_at')->delete();\n\n            // 4. Record it\n            AuditLog::record('user.deprovisioned', $user, ['source' => $source]);\n        });\n\n        event(new UserDeprovisioned($user));  // websockets disconnect, cache bust\n    }\n}\n```\n\nBecause 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.\n\nIdPs 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:\n\n`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.\nMatch 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.\n\nDeprovisioning fails quietly through paths that do not go through SSO at all. I check each of these during review:\n\nWrite a test that proves access is actually gone, not just that the flag changed:\n\n```\n# 1. Log in as the user, keep the session cookie and create an API token\n# 2. Deactivate via SCIM\ncurl -s -X PATCH https://app.example.test/scim/v2/Users/$USER_ID \\\n  -H \"Authorization: Bearer $SCIM_TOKEN\" -H \"Content-Type: application/scim+json\" \\\n  -d '{\"schemas\":[\"urn:ietf:params:scim:api:messages:2.0:PatchOp\"],\"Operations\":[{\"op\":\"replace\",\"value\":{\"active\":false}}]}'\n# 3. Both of these must now return 401\ncurl -s -o /dev/null -w \"%{http_code}\\n\" -b \"session=$COOKIE\" https://app.example.test/dashboard\ncurl -s -o /dev/null -w \"%{http_code}\\n\" -H \"Authorization: Bearer $API_TOKEN\" https://app.example.test/api/me\n```\n\nWhen 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.\n\n`active: false` is handled in all common shapes (value object, path, string)`active` flag\nNo. 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.\n\nUsually 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.\n\nGive the tenant admin a clear \"deactivate user\" button that calls the same `DeprovisionUser` service, so the result is identical whatever the trigger.\n\nYour 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.\n\nStart with Users and the deactivation path. Add Groups when customers ask for role mapping, which Part 5 covers.\n\nA PATCH with `active: true` should restore login only. Do not restore old sessions or tokens; the user signs in fresh and creates new ones.\n\nNext in this series, Part 4 covers multi-tenant login routing: discovering a user's tenant from their email domain and enforcing SSO for it.", "url": "https://wpnews.pro/news/scim-provisioning-deprovisioning-that-actually-removes-access", "canonical_source": "https://dev.to/muhammadalimughal/scim-provisioning-deprovisioning-that-actually-removes-access-jjo", "published_at": "2026-11-20 16:29:07+00:00", "updated_at": "2026-11-20 16:44:44.084664+00:00", "lang": "en", "topics": ["developer-tools", "ai-tools"], "entities": ["Okta", "Microsoft Entra", "SCIM", "Laravel"], "also_reported_by": [], "takeaway": "On SCIM deactivation (active: false or DELETE), block login, revoke every live session, disable API tokens and pending invites, and log it in one transaction-safe step, since SSO alone only stops new logins.", "recommendation": {"advice": "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.", "playbook": "agent-security", "playbook_url": "https://wpnews.pro/playbooks/agent-security"}, "alternates": {"html": "https://wpnews.pro/news/scim-provisioning-deprovisioning-that-actually-removes-access", "markdown": "https://wpnews.pro/news/scim-provisioning-deprovisioning-that-actually-removes-access.md", "text": "https://wpnews.pro/news/scim-provisioning-deprovisioning-that-actually-removes-access.txt", "jsonld": "https://wpnews.pro/news/scim-provisioning-deprovisioning-that-actually-removes-access.jsonld"}}