Implementing SCIM 2.0 in FastAPI for Okta and Entra ID

Authentication & Security

Build SCIM 2.0 in FastAPI for Okta and Entra ID with tenant-scoped credentials, users, groups, filters, PATCH, deactivation, and retry-safe updates safely.

TL;DR

  • SCIM is a provisioning protocol that lets an identity provider create, find, update, group, and deactivate accounts in a service provider.
  • Implement the SCIM 2.0 resource schemas and semantics first. A FastAPI route that accepts familiar JSON is not interoperable unless it also handles filters, pagination, PATCH, and error responses.
  • Authenticate each provisioning connection to one customer tenant, then include that tenant in every database lookup and uniqueness constraint.
  • Treat deactivation as an access lifecycle event. Preserve required audit history, revoke sessions, and avoid deleting business records just because the identity provider disabled a user.
  • Test the exact request sequences used by Okta and Microsoft Entra, including retries, duplicate creates, group changes, and reordered updates.

What SCIM provisioning does for a B2B SaaS product

System for Cross-domain Identity Management (SCIM) 2.0 is an HTTP protocol and JSON schema for synchronizing identity records between an identity provider (IdP) and an application. A customer administrator assigns a person to an enterprise application in Okta or Microsoft Entra ID. The provider then sends requests to your service to create, update, group, or deactivate that person's account. SCIM reduces manual account setup and helps customer administrators remove access when employment or application assignments change.

SCIM is separate from single sign-on. SAML or OpenID Connect authenticates someone during a login flow. SCIM provisions directory state before, during, or after that person's login lifecycle. A user can therefore be successfully provisioned yet unable to sign in until SSO is configured, and an SSO identity can exist without SCIM-controlled lifecycle updates. Our Keycloak and Auth0 architecture comparison covers the separate authentication and identity-provider concerns.

In SCIM terminology, the application exposing the API is the service provider, and the IdP calling the API is the client. RFC 7644 defines the protocol and operations, while RFC 7643 defines core resource attributes such as User and Group. Use the current specifications and relevant provider compatibility guidance when defining a supported profile. RFC 7644 SCIM protocol · RFC 7643 SCIM core schema

Define the service-provider contract before writing routes

SCIM requests carry schema identifiers, filters, pagination parameters, and operation semantics that differ from a typical internal REST API. Publish the capability endpoints and response schemas deliberately. An IdP uses the service-provider configuration and schema resources to understand which operations, attributes, and authentication schemes your endpoint supports.

A practical initial resource surface commonly includes:

  • GET /scim/v2/ServiceProviderConfig to report supported features and authentication schemes.
  • GET /scim/v2/Schemas and /ResourceTypes to describe resources and schema extensions.
  • GET, POST /scim/v2/Users for filtered lookup and user creation.
  • GET, PUT, PATCH, DELETE /scim/v2/Users/{id} according to the operations you support.
  • GET, POST /scim/v2/Groups and item operations when group synchronization is part of the product contract.

These routes should return SCIM media types and schemas where the protocol requires them. User records include the core User schema URI, stable server-managed id, optional client-supplied externalId, and attributes such as userName, name, emails, and active. Group membership is a multi-valued relationship, not a comma-separated text field. Define how each supported SCIM value maps into your internal account, organization, and role model.

The SCIM id is the service provider's stable identifier. The externalId belongs to the client namespace and can help the IdP correlate its own record. Do not replace your internal user primary key with an IdP-controlled identifier. Persist the mapping so an IdP can repeat a lookup or update even after email or display name changes. RFC 7643 defines uniqueness and mutability semantics per attribute, while each provider's setup guide documents its own profile-matching behavior. Okta SCIM 2.0 behavior

Bind each SCIM credential to a customer tenant

A SCIM bearer credential is a powerful machine credential. Treat it like a long-lived integration secret with a limited audience, not like a user login token. Store only a slow keyed digest or use a managed secret store, allow rotation, record last use and creation metadata, and revoke it when provisioning is disabled. Avoid exposing credentials in logs, errors, analytics, and support screenshots.

Resolve the credential to a provisioning connection containing the tenant ID and configured policy. Do not accept tenant identity from a request body, filter, user attribute, or untrusted URL parameter. After authenticating the connection, bind its tenant context to every query and write. A request for /Users/123 must mean “the user with provider ID 123 in this connection's tenant,” never “any row whose global ID is 123.”

Database uniqueness should reflect the product's identity boundary. A common design uses a unique mapping for (tenant_id, provisioning_connection_id, external_id) when the provider's external ID is stable within its integration. If userName is the lookup attribute, define normalization and uniqueness inside the SCIM connection boundary and preserve the original value if case or formatting matters. Avoid a global email uniqueness assumption when the SaaS permits the same person to belong to multiple customer organizations. PostgreSQL row-level security for tenant isolation

Credential rotation should allow a controlled overlap if the customer needs to update configuration without downtime. Record which credential version authenticated each request, but never record the secret itself. Rate-limit by connection and protect expensive list filters from unbounded scans. Make all provisioning endpoints TLS-only and separate their authorization policy from interactive user sessions.

Implement filters and pagination as a bounded language

IdPs commonly query for a user before deciding whether to create one. A frequent pattern searches for an exact userName or externalId. SCIM filters are expressions, not SQL snippets. Parse them into a small abstract syntax tree with a grammar for supported attribute paths, operators, and logical combinations. Map each accepted node to a predeclared SQLAlchemy expression and bind values as parameters. Never interpolate attribute names or filter text into SQL.

Return a SCIM ListResponse with schemas, totalResults, startIndex, itemsPerPage, and Resources. Apply a configured maximum page size and deterministic ordering. SCIM indexes pages from 1, while a database query typically uses a zero-based offset. Translate carefully and test boundary values. Count after tenant scoping and policy filtering so total counts cannot reveal other organizations' records.

Do not claim support for every filter operator if the implementation only handles equality. Report unsupported or malformed filters using the SCIM error schema and relevant status. RFC 7644 describes invalidFilter and tooMany cases. A provider can retry or adjust when the capability response and actual behavior agree. RFC 7644 filtering and list response

# Illustrative shape: parsed filters become trusted SQLAlchemy expressions.
def compile_filter(node, tenant_id):
    if node.attribute == "userName" and node.operator == "eq":
        return and_(
            User.tenant_id == tenant_id,
            User.scim_user_name == node.value,
        )
    if node.attribute == "externalId" and node.operator == "eq":
        return and_(
            User.tenant_id == tenant_id,
            User.scim_external_id == node.value,
        )
    raise UnsupportedScimFilter(node.attribute, node.operator)

# Parse the SCIM grammar first. Keep the connection tenant in every branch.
predicate = compile_filter(parsed_filter, connection.tenant_id)
stmt = select(User).where(predicate).order_by(User.id).limit(page_size)

This example intentionally supports only two exact-match filters. A parser should reject unsupported nesting, escaped quotes, attribute paths, case sensitivity, and operators until those behaviors have been implemented and tested. SQLAlchemy turns expression objects into bound SQL parameters, which is a safer building block than constructing query strings from client input. SQLAlchemy expression operators

Make PATCH and deactivation semantics predictable

SCIM PATCH uses an operation list with add, remove, or replace and an optional path. A server must interpret paths against the resource schema, including multi-valued attributes. For example, replacing one email by a path filter should affect only the matching value, while replacing the whole emails attribute changes the collection. Parse operations into typed commands and apply them in one database transaction after checking immutable and read-only attribute rules.

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

Do not equate SCIM DELETE with physically erasing every application record. Providers may deactivate users with active: false, and customers may expect the product to retain audit records or preserve objects owned by that person. Define a lifecycle transition that blocks new authentication, invalidates sessions and refresh tokens, removes effective access, and retains or transfers business data according to policy. If a DELETE endpoint is supported, document whether it performs a soft deactivation or a true deletion and return the protocol-appropriate response.

Group membership changes can drive access changes across many accounts. Keep group operations tenant-scoped and make membership updates transactional. Treat a group removal as a revocation signal, then compute effective roles using a well-defined policy. Do not trust the IdP to send every intermediate change in order. Use idempotent updates and a reconciliation process that can compare source state with the application's current projection.

Return protocol errors without losing useful diagnostics

SCIM errors have a JSON representation with the error schema, status, detail, and sometimes a scimType. Map validation failures to stable protocol responses. Examples include malformed JSON, invalid filter syntax, duplicate uniqueness values, unsupported mutability, and a missing resource. Avoid returning raw Python exceptions, SQL details, bearer credential state, or another tenant's user information.

Operational logs should include a request ID, connection ID, tenant ID, operation, resource ID, outcome category, and latency. Exclude authorization headers and minimize personal data. Keep a durable audit record for high-impact changes such as deactivation, group membership, and credential rotation. Record the before-and-after security-relevant fields or a carefully scoped diff with retention controls.

Return success only after the relevant update is committed. If a request times out after commit, the IdP may retry. A repeated create should resolve using the configured stable lookup attribute and return the existing SCIM resource where provider semantics expect it. Unique database constraints protect concurrent duplicates that pass a prior lookup at the same time.

Test compatibility with real provisioning sequences

Begin with the provider's lifecycle rather than isolated route unit tests. Okta documents that assignment can trigger lookup by userName, create when no match exists, and follow-up updates; group import changes which group requests are issued. Microsoft Entra also supports SCIM 2.0 provisioning to SaaS applications and documents its own request and capability behavior. Build a compatibility matrix for the actual integrations you intend to support. Microsoft Entra SCIM support

At minimum, exercise a connection lifecycle: authenticate a tenant-specific token, list matching users, create a user, repeat the create lookup, patch names and emails, add and remove a group member, deactivate an account, rotate the credential, and retry a request after a simulated timeout. Verify that a token from tenant A cannot read, modify, or enumerate tenant B, including through filters and group references.

Use contract tests against provider documentation and, where available, a development integration. Assert response schemas, content types, pagination boundaries, stable IDs, error bodies, and the behavior of unsupported features. Add property-based tests for filter parsing so arbitrary strings cannot turn into SQL expressions. Test concurrent duplicate creates with the same provider identity and ensure one internal mapping wins without a server error that leaves the IdP unable to recover.

Finally, run provisioning against a sandbox tenant through both successful and failed lifecycle paths. A test that only creates users can miss the most consequential requirement, which is taking access away reliably. Store a periodic reconciliation result or alert on connection failures and long gaps since successful sync. Review tenant boundaries against IDOR patterns

Frequently asked questions

Does SCIM replace SAML or OpenID Connect single sign-on?

No. SCIM provisions user and group records between an identity provider and an application. SAML and OpenID Connect authenticate a person during sign-in. Many enterprise deployments use both, with SCIM managing lifecycle and SSO handling authentication.

Should SCIM DELETE permanently erase a user?

Not by default. Define the contract for your product and provider. Deactivation should block authentication, invalidate sessions, and remove effective access while preserving business records or audit evidence when policy requires it. Implement physical erasure only when the data-retention and customer lifecycle rules call for it.

Can a SCIM API accept every filter expression from RFC 7644?

Only if it implements and tests those expressions. Report supported capabilities honestly, parse filters into a constrained syntax tree, and return protocol errors for unsupported combinations. Never insert filter text into SQL. Provider behavior should be verified against its current compatibility guide.

How should one SaaS SCIM endpoint serve multiple customer tenants?

Authenticate each provisioning connection with a tenant-bound credential, derive the tenant from that connection, and include it in every read, update, relationship, and uniqueness check. Do not accept tenant ownership from a SCIM attribute or caller-controlled filter.

Ship SCIM as an identity lifecycle boundary

SCIM support is more than a collection of CRUD routes. The service provider must preserve protocol semantics, constrain filtering, apply tenant isolation to every operation, handle retries, and remove access in a way that matches the product's data lifecycle. Start with the smallest provider profile you can support reliably, document it through the capability endpoints, and expand only when tests and customer integrations require more.

If enterprise provisioning is on your roadmap, talk with our engineering team about a SCIM contract, tenant credential model, and lifecycle tests that fit your product.

Dumb Potato Editorial

Putting this into practice?

Share the problem you’re solving and the tradeoffs you’re weighing with our engineering team.

See how we help with application security

Discuss your project