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
- Part 2: Validating SAML Responses: Signatures, Audience & Clock Skew
- 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 ยท Webhooks That Stopped Arriving: Gap Detection & Reconciliation
What does SCIM deprovisioning need to do?
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.
The SCIM endpoints you actually need
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.
Step 1: authenticate the IdP per tenant
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);
}
Step 2: handle PATCH active=false properly
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.
Step 3: make every call idempotent
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:
- Deactivating an already inactive user returns 200 with the current resource.
- A
POST /Usersfor an existinguserNamein the same tenant either links to it or returns 409uniqueness, depending on what the IdP expects; Okta and Entra docs both describe the filter-then-create flow, so support theGETfilter correctly first. -
DELETEof 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.
Step 4: block the side doors
Deprovisioning fails quietly through paths that do not go through SSO at all. I check each of these during review:
- Password login. If SSO is enforced for the tenant, local password login must be disabled for its users, or a deactivated user can reset a password and walk back in.
- Magic links and email invites already sent before deactivation.
- Mobile apps holding long-lived refresh tokens.
- Integrations the user connected, such as a Slack bot or a webhook that runs as them. Reassign or pause them, and tell the tenant admin.
Step 5: test it end to end
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 to spot the exact shape of the PATCH, and use the HTTP Status Checker to confirm the SCIM base URL answers with the right status and no redirect, since some IdPs refuse to follow redirects.
Diagnostic checklist
- [ ] SCIM tokens are per tenant, stored hashed and rotatable
- [ ] Every SCIM query is scoped to the authenticated tenant
- [ ]
active: falseis handled in all common shapes (value object, path, string) - [ ] Deactivation deletes sessions, API tokens, refresh tokens and pending invites
- [ ] Access tokens are short-lived and refresh checks the
activeflag - [ ] Password and magic-link login are blocked for SSO-enforced tenants
- [ ] Repeated calls are idempotent and return SCIM-shaped errors
- [ ] An automated test proves the old cookie and token return 401 after deactivation
- [ ] Every provisioning change lands in the audit log with its source
FAQ
Is SAML or OIDC single logout enough instead of SCIM?
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.
Should deprovisioning delete the user's data?
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.
What if a customer has no SCIM-capable IdP?
Give the tenant admin a clear "deactivate user" button that calls the same DeprovisionUser service, so the result is identical whatever the trigger.
How fast does deprovisioning need to happen?
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.
Should I support SCIM Groups from day one?
Start with Users and the deactivation path. Add Groups when customers ask for role mapping, which Part 5 covers.
How do I handle reactivation?
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.
Follow & Connect
- Website: PixelValut Tools
- Watch on YouTube: Resume Boost AI ยท PixelValut ยท Daily AI News By Ali
- TikTok: PixelValut (@pixelvalut007)
- GitHub: Muhammad Ali Mughal (@ali111887)
- LinkedIn: Muhammad Ali Mughal

Top comments (0)