Skip to content
Get started
Bastionary › Knowledge base › Enterprise SSO and provisioning

Provision users with SCIM 2.0

By Bastionary · Enterprise SSO and provisioning

SCIM 2.0 lets enterprise customers push user and group changes from their directory to your application. Without it, offboarding depends on manual cleanup and stale accounts accumulate. This guide shows how to add a SCIM service provider to a self-hosted Bastionary deployment.

Understand the SCIM contract

SCIM is a REST API over HTTPS. The customer's identity provider is the client; your application is the service provider. The protocol covers users, groups, and membership changes using standard schemas and filters.

Focus on these operations first:

  • POST /Users to create a user.
  • PUT /Users/{id} or PATCH /Users/{id} to update attributes or status.
  • DELETE /Users/{id} to deactivate or remove a user.
  • GET /Users with filters to reconcile state during initial sync.

Group endpoints follow the same pattern. Start with users; add groups once the basics are solid. Always return the standard SCIM schemas so identity providers can parse your responses without custom logic.

Expose and secure the SCIM endpoints

SCIM traffic must be authenticated and encrypted. Use a unique bearer token per tenant and reject plain HTTP. A typical setup routes requests under /scim/v2 and validates a tenant-scoped token from the Authorization header.

Example Python middleware for tenant token validation:

def require_scim_token(handler):
    def wrapper(request):
        auth = request.headers.get('Authorization', '')
        token = auth.replace('Bearer ', '').strip()
        tenant = lookup_scim_token(token)
        if not tenant:
            return Response(status=401)
        request.tenant = tenant
        return handler(request)
    return wrapper

Rotate tokens through your admin UI and log every SCIM request with the tenant ID and actor. Rate-limit endpoints to prevent a misconfigured identity provider from overwhelming your service. Return 429 with a Retry-After header when limits are exceeded.

Handle user lifecycle events

The biggest value of SCIM is reliable deactivation. When the identity provider sends a DELETE or sets active to false, suspend the matching user in your database. Do not hard-delete immediately; preserve audit history and allow reactivation if the change was accidental.

Recommended mapping:

  • userName → unique username or email.
  • name.givenName + name.familyName → display name.
  • externalId → the directory's immutable identifier.
  • active → account status: true for active, false for suspended.

Example handler for creating a user:

@app.route('/scim/v2/Users', methods=['POST'])
def create_user():
    data = request.json
    user = User.create(
        tenant_id=request.tenant.id,
        email=data['userName'],
        name=f"{data['name']['givenName']} {data['name']['familyName']}",
        external_id=data['externalId'],
        active=data.get('active', True)
    )
    return jsonify(user.to_scim()), 201

Return the standard SCIM user resource so the identity provider can store your identifier for future updates. Make creation idempotent: if the same externalId already exists under the tenant, return the existing user with 200 instead of duplicating it.

Support groups and role mapping

Many enterprises manage access through directory groups. Map SCIM group membership to application roles by keeping a join table between SCIM group IDs and your roles.

  • On PUT /Groups/{id}, update the group record and its membership list.
  • On membership changes, add or remove rows in the tenant membership table.
  • Never grant roles that exceed the tenant's configured maximum permissions.

Keep an audit log entry for every membership change with the SCIM operation ID and timestamp. When a group is deleted, revoke the related roles but do not delete the underlying users unless the identity provider also sends DELETE requests for them.

Some identity providers send group membership changes inside a PATCH operation with add or remove paths. Parse these patches instead of requiring a full replacement, because large groups would otherwise generate oversized requests.

Test and reconcile state

Before enabling SCIM for a customer, verify behavior with representative scenarios:

  • Create a user, update their department, then deactivate them.
  • Change group membership in the identity provider and confirm role changes in your app.
  • Send malformed requests and confirm your service returns proper SCIM error schemas.
  • Run a full reconcile query with GET /Users?filter=... to test pagination.
  • Send duplicate creation requests for the same externalId and confirm idempotency.

Support common filter expressions such as userName eq "alice@example.com" and externalId eq "12345". Verify that pagination works by requesting small page sizes and walking the startIndex offsets. Most identity providers issue full reconciles at least daily, so inefficient pagination will cause timeouts.

Monitor SCIM health

Log the outcome of every SCIM request with enough detail to debug without exposing secrets. Track error rates by tenant, unexpected attribute values, and the age of the last successful sync. Set alerts for repeated authentication failures and for tenants that have not received a request in an unusually long time. Review these logs during tenant onboarding and after any identity provider upgrade.

Identity providers often send custom schema extensions. Store unknown attributes in a raw JSON column rather than rejecting the request, unless the attribute conflicts with a reserved field. This prevents minor directory changes from breaking provisioning.

Next steps

  • Document your SCIM base URL, bearer token setup, and supported schemas for customer admins.
  • Add SCIM group support if you have not already.
  • Automate token rotation and certificate monitoring.
  • Pair SCIM with SAML or OIDC SSO for a complete customer identity flow.

Run it yourself

Bastionary is free, open-source software. Follow the quick start to have it running on your own server, or browse the releases on Git.

Get started