[Feature][SSO]: Auto-provision SSO users on token-authenticated API/MCP calls (JIT for headless clients)
Problem / Gap
SSO_AUTO_CREATE_USERS (and the per-provider auto_create_users flag) only takes effect during the interactive browser OIDC callback. The sole non-test caller of SSOService.authenticate_or_create_user() - the one place that honors auto-create is mcpgateway/routers/sso.py, which returns a RedirectResponse to the admin UI.
Every token-based authentication path only looks up the user and never provisions:
- Standard JWT (
require_auth→verify_jwt_token→_enforce_revocation_and_active_user,utils/verify_credentials.py): looks up by email; withREQUIRE_USER_IN_DB=true(secure default) returns401 "User not found in database", otherwise passes through with no DB identity. - Virtual-server OAuth / JWKS (
oauth_enabled=True,transports/streamablehttp_transport._try_oauth_access_token→verify_oauth_access_token): cryptographically verifies the external IdP (e.g. Keycloak) access token, then returns the claims, but creates no user record.
Impact
A valid, SSO-verified identity that has never logged into the browser UI cannot be used for headless/programmatic MCP or API access:
REQUIRE_USER_IN_DB=true→ hard401for the user, even though their token is valid.REQUIRE_USER_IN_DB=false→ request passes through with no real user/teams/RBAC.
This blocks server-to-server integrations (an app forwarding each end-user's Keycloak bearer to the gateway so the gateway enforces that user's permissions). Today every user must first do a one-time interactive UI login purely to get a DB row, or operators must pre-seed users via the admin API and keep them in sync.
Proposed solution
When a token is cryptographically validated against a trusted SSO provider and the email is not yet in the DB, provision the user via the existing SSOService.authenticate_or_create_user() (reusing its trusted-domain, email-verified, role/team and admin-approval logic). Gate it behind a new opt-in setting so default behavior is unchanged, e.g. SSO_AUTO_CREATE_USERS_ON_TOKEN_AUTH=false (default).
- Apply on the JWKS/OAuth virtual-server path (verified external token) and, where the gateway JWT carries a trusted SSO issuer, the standard JWT path.
- Respect
SSO_REQUIRE_ADMIN_APPROVAL,SSO_TRUSTED_DOMAINS, andemail_verified. - No-op when the user already exists.
Alternatives considered
- One-time interactive UI login per user - manual friction; defeats headless use.
- Pre-provision via
POST /auth/email/admin/users+ a Keycloak→gateway sync job - requires a standing admin credential and an ongoing polling sync. REQUIRE_USER_IN_DB=false- weakens security and yields no real identity/RBAC.
Security considerations
- Strictly opt-in; default off.
- Only fires after full signature/issuer/expiry (and audience, where applicable) verification.
- Reuses existing trusted-domain / email-verified / approval gating, so it cannot create users a browser SSO login wouldn't have.
I'm happy to submit a PR (with tests + docs) if maintainers are open to this.
Suggested labels: enhancement, security, python (deferring to maintainer triage).
This is a real gap for headless MCP deployments — the interactive OIDC callback path working while token-based auth paths skip provisioning creates a fragmented onboarding experience where SSO-configured orgs still need a manual user-creation step for MCP clients.
The JIT pattern that works: The token verification path (verify_jwt_token) already has everything it needs to provision — the decoded JWT contains the user's email, which SSOService.authenticate_or_create_user() accepts as its lookup key. The missing piece is calling that function from the token path, not just the interactive callback.
Implementation approach (three concerns to handle):
-
Idempotency:
authenticate_or_create_user()needs to be safe to call on every token validation. If the user already exists, it should be a no-op (lookup-only, no DB write). The current implementation may already handle this if it does aget_or_create. -
Default role assignment: Headless-provisioned users need a default role. The interactive path likely assigns based on the SSO provider's group claims. For token-based JIT, consider a
SSO_AUTO_CREATE_DEFAULT_ROLEconfig (defaulting toviewer) so MCP clients get minimal access until an admin promotes them. -
Rate-limiting the provision path: Unlike interactive login (human-paced), token-based MCP calls can fire at high frequency. The provision check should be behind a short-lived cache (
email → user_id, TTL 60s) so the DB isn't hit on every tool call.
We use this exact JIT pattern at corpusiq.io for headless MCP client auth — the first API call with a valid SSO token provisions the operator account with default workspace access. It's been reliable in production as long as the default role is locked down and the cache prevents provision storms.
I reviewed this against v1.0.7 and prepared a focused implementation.
ContextForge 1.0.7 already performs JIT provisioning for the standard external bearer-token path through build_external_identity(), gated by SSO_API_TOKEN_AUTH_ENABLED and the provider’s trusted_for_api_auth setting.
The remaining gap is the OAuth-enabled virtual-server MCP path in _try_oauth_access_token(). After successfully validating the token’s signature, issuer, expiry, and audience, that path still requires an existing EmailUser and returns 401 for a first-time headless user.
My proposed patch reuses the existing build_external_identity() implementation when the user is missing. It does not introduce a separate provisioning mechanism or provider-specific behaviour.
Provisioning would occur only when:
- SSO_API_TOKEN_AUTH_ENABLED=true
- The token has passed the virtual server’s issuer and audience validation
- The issuer maps to an enabled provider with trusted_for_api_auth=true
- The provider has auto_create_users=true
- The existing email-verification, trusted-domain, admin-approval, account-linking, role, and team rules pass
The patch also verifies that the normalised provisioned identity exactly matches the identity selected from the verified token. Existing users continue through the current fast path, disabled users remain rejected, and provisioning failures fail closed.
I have included unit tests covering successful first-use provisioning, the global and provider opt-ins, identity mismatch, and the existing denial path, plus a documentation update.
Since this issue is still marked triage, would the maintainers be open to a PR scoped to this remaining virtual-server OAuth gap?
PR #6402 for this issue is up to date with main again.
Merged current main (142effc). One conflict, one line in sso_service.py: main now stores the verification status from the new three-state claim, and the PR replaces that line with email_verified_at. I kept the PR's line, because main already returns before that point when the claim is explicitly false. The auth, SSO and transport unit tests and the detect-secrets hook pass locally.
Could a maintainer approve the workflow runs (they wait because the PR comes from a fork) and review the PR when there is time? Thanks.