Cross-Domain OIDC Sign-On and Delegated Tool Authorization
Medium · System Design · Backend Engineer · Onsite
Prompt
An enterprise software vendor operates acmecloud.com and recently purchased novadesk.io. Customers and employees who authenticate on one web property should transition to the other without typing their password or second factor again as long as their central identity session remains valid.
Because acmecloud.com and novadesk.io live under separate registrable domain names, browser cookie isolation prevents them from sharing a parent-domain cookie, and modern browser privacy defenses block or partition cookies inside cross-site iframes. Each application can issue top-level HTTP redirects to a shared Identity Provider (IdP) and process server-side login callbacks.
For example, when Maya signs into https://acmecloud.com/projects and clicks over to https://novadesk.io/inbox ten minutes later, she enters novadesk.io with zero extra credential prompts, and can then either open an approved external analytics web app or trigger a backend call from novadesk.io to an external ticketing REST API.
Design goals & constraints:
- Cross-domain login choreography: Walk through Maya's initial login on acmecloud.com and subsequent silent sign-on to novadesk.io using OpenID Connect (OIDC)—covering redirect parameters, CSRF/replay/code-theft defenses, token verification, independent per-site sessions, expired central sessions, and step-up authentication when sensitive routes demand stronger assurance (such as recent MFA).
- Multi-domain & third-party expansion: Generalize the design to many company domains and approved external tools, isolating client credentials, callback allowlists, and session boundaries per relying party.
- UI federation vs API delegation: Clearly separate signing a user into an external tool's web interface from granting backend API access—never treating an OIDC ID token as an all-purpose API bearer credential.
- Governance, account linking & logout: Enforce user/group tool entitlements, protect stored OAuth credentials, safely migrate and link pre-acquisition accounts across domains, and define what happens during single-site logout, central logout, and administrative revocation.
Scope & Expectations
- Trace the end-to-end OIDC Authorization Code + PKCE redirect sequence across
acmecloud.com,novadesk.io, and the shared IdP, detailing cookie attributes and server-side token validation checks. - Specify per-application client isolation, local session management, expired IdP session handling, and step-up authentication enforcement.
- Contrast federated sign-in to third-party web tools (OIDC/SAML + SCIM) with delegated API authorization (OAuth Token Exchange and KMS-encrypted SaaS refresh tokens) gated by entitlement rules.
- Address safe account linking for overlapping pre-acquisition users and contrast single-site logout against back-channel global logout and emergency credential revocation.
Step-by-step walkthrough
Clarify requirements and core concepts
After the company behind
acmecloud.comacquiresnovadesk.io, customers expect Single Sign-On (SSO)—authenticating once and navigating across both web apps without re-entering credentials. Becauseacmecloud.comandnovadesk.iosit on separate registrable domains (distinct base domains registered independently in the public suffix list), browsers isolate their cookie jars completely:acmecloud.comcannot set or read cookies belonging tonovadesk.io.To connect separate domains without cross-domain cookies, every app delegates login to one shared Identity Provider (IdP) hosted on its own canonical hostname,
auth.acmegroup.id. Each web property trusting the IdP for sign-in acts as a Relying Party (RP). Keep two responsibilities strictly distinct throughout the architecture: - Authentication establishes who the person is (for instance, Maya authenticated via password + passkey 2 minutes ago). - Authorization governs which operations an app or user may perform (for instance,novadesk.io's backend may read Maya's tickets in an external ticketing API, but cannot delete them).Functional requirements
- Authenticating on
acmecloud.comlets Maya opennovadesk.io(and future company domains) without a second credential prompt while her central IdP session stays active. - Every application manages its own isolated local session cookie and application profile store.
- Sensitive routes (such as billing or payout edits on
/billing) can trigger step-up authentication—requiring fresh Multi-Factor Authentication (MFA) completed within a short window (such as 15 minutes). - Entitled users can launch approved external web tools via their company identity (federated sign-in), and company backends can invoke external tool APIs on a user's behalf (delegated API authorization).
- Administrators manage user/group tool entitlements centrally and can revoke access on demand.
- Support both single-site logout and ecosystem-wide logout.
Non-functional requirements
- Security: Individual product sites never touch user passwords. Every flow relies on OpenID Connect (OIDC) (an identity protocol layered onto OAuth 2.0 to prove who logged in) and OAuth 2.0 (an authorization framework issuing scoped API tokens).
- Browser compatibility: Must operate cleanly when browsers block or partition third-party cookies (cookies whose domain differs from the top-level site in the URL bar).
- Availability: Target
99.99%availability on the IdP since brand-new logins depend on it, while already-established local sessions onacmecloud.comandnovadesk.ioremain unaffected during transient IdP downtime. - Latency: Cross-domain silent SSO adds at most
200–300 msof redirect time when establishing a site's local session, and0 mson subsequent page loads. - Auditability: Persist an append-only security log covering logins, account links, OAuth grants, and revocations.
Assumptions from clarifying questions
- Account migration and linking: Legacy
novadesk.ioaccounts migrate lazily into the central IdP upon login. Pre-existing accounts onacmecloud.comandnovadesk.iosharing an email string are never merged automatically; linking requires proving control over both accounts. - Third-party tool capabilities: External integrations span three categories: web UIs supporting OIDC or SAML federation, commercial SaaS APIs running their own OAuth servers, and partner APIs trusting tokens signed by our IdP.
- Logout behavior: Clicking "Sign out" clears the active site's cookie and, by default, terminates the central IdP session and dispatches server-to-server logout webhooks to sibling apps.
- Authenticating on
Back-of-the-envelope capacity estimates
Assume
acmecloud.comholds22Mexisting account rows andnovadesk.ioholds10M(32Mtotal rows with ~2Moverlapping individuals, or~30Munique people). Assume5Mdaily active users (DAU) visit an average of2company domains per day and create1.5local sessions per domain per day, while1Mactive users invoke third-party tool APIs.1. Browser authorization redirects (GET /oauth2/authorize) 5M DAU * 2 sites/day * 1.5 sessions/site = 15M requests/day Average: 15,000,000 / 86,400 s = ~175 req/s Peak (5x diurnal spike): = ~900 req/s (provision for 2,000 req/s) 2. Primary credential checks (password / passkey / MFA) Only needed when the IdP session is missing or expired (~1M logins/day) Average: ~12/s | Peak: ~100/s Password hashing (Argon2id tuned to ~50 ms CPU and 64 MB RAM per hash): CPU at peak: 100/s * 0.05 s = ~5 CPU cores Concurrent RAM: ~5 hashes * 64 MB = ~320 MB (guarded by a semaphore) 3. Token minting and refresh (POST /oauth2/token) Authorization-code exchanges: = ~900 req/s at peak Tool API token exchanges / lazy refreshes (only when a user actively calls a tool): 1M users * ~10 active 10-min windows/day = 10M/day -> ~115/s avg, ~600/s peak Total cryptographic token signatures: = ~1,500-2,000 JWTs/s at peak ECDSA P-256 signing takes < 0.1 ms CPU = < 1 CPU core across the fleet 4. State and storage footprint Active IdP sessions: 5M * ~1 KB = ~5 GB (fits easily in replicated Redis) Site local sessions: 5M * ~0.5 KB/site = ~2.5 GB per site Encrypted token vault: 1M users * 3 tools * ~2 KB = ~6 GB Security audit log: 15M events/day * 1 KB = ~15 GB/day (~5.5 TB/year)What these numbers tell us:
- Throughput is modest. Even
2,000 req/sis comfortably served by a small multi-region fleet of stateless IdP servers and a5 GBreplicated session store. The real challenge is protocol correctness and security isolation, not raw QPS. - Password hashing is CPU- and memory-heavy, and SSO makes it rare. Over
90%of/authorizehits reuse an active IdP session cookie and need only one Redis lookup and one fast signature. - Lazy on-demand token refresh beats background polling. Refreshing third-party API tokens only when an API request actually arrives avoids wasting millions of idle refreshes and avoids hitting SaaS rate limits.
- Throughput is modest. Even
API and protocol endpoints
Every site must redirect to the IdP under one canonical hostname (
https://auth.acmegroup.id). Ifacmecloud.comusedlogin.acmecloud.comandnovadesk.iousedlogin.novadesk.ioas branded aliases, the browser would store the IdP cookie underlogin.acmecloud.comand never send it tologin.novadesk.io, breaking SSO completely.The IdP exposes standard OIDC endpoints, including a JSON Web Key Set (JWKS) endpoint—a public JSON document listing the IdP's public cryptographic keys, each tagged with a key ID (
kid), so sites and APIs can verify token signatures locally without calling the IdP on every request.Identity Provider (https://auth.acmegroup.id) GET /.well-known/openid-configuration Discovery metadata (issuer, URLs, algorithms) GET /oauth2/jwks Public signing keys indexed by key ID (kid) GET /oauth2/authorize Browser redirect entry point ?response_type=code &client_id=nova-web &redirect_uri=https://novadesk.io/auth/callback &scope=openid profile email &state=<random_csrf_token> &nonce=<random_id_token_binder> &code_challenge=<BASE64URL(SHA256(code_verifier))>&code_challenge_method=S256 [&prompt=none|login] [&max_age=900] [&acr_values=urn:acme:acr:mfa] -> 303 https://novadesk.io/auth/callback?code=<one_time_code>&state=...&iss=https://auth.acmegroup.id POST /oauth2/token Server-to-server token exchange (private_key_jwt auth) grant_type=authorization_code | refresh_token | urn:ietf:params:oauth:grant-type:token-exchange POST /oauth2/revoke Revoke refresh or access tokens (RFC 7009) POST /oauth2/introspect Check live token validity for high-risk APIs (RFC 7662) GET /oauth2/logout RP-initiated global logoutEach site acts as a confidential client (a server-side application capable of keeping cryptographic keys secret, so raw tokens never touch browser JavaScript):
Each Relying Party Site (acmecloud.com, novadesk.io, ...) GET /auth/login?return_to=/inbox Creates login transaction, 302 to IdP /authorize GET /auth/callback?code=...&state=... Redeems code server-to-server, sets local cookie POST /auth/logout Clears local session, redirects to IdP /logout POST /auth/backchannel-logout Server-to-server webhook receiving IdP logout_tokenAn internal Tool Access Service centralizes third-party tool permissions and credentials:
Tool Access Service (internal) GET /tools List tools the signed-in user is entitled to use GET /tools/{tool_id}/launch 302 into a federated third-party web UI POST /tools/{tool_id}/connect Start user OAuth consent flow for an external SaaS API GET /tools/{tool_id}/oauth/callback Validate consent callback and store encrypted grant POST /tools/{tool_id}/calls Check entitlement, attach scoped API token, proxy call DELETE /tools/{tool_id}/connection Revoke and delete stored SaaS OAuth tokens PUT /admin/entitlements/{tool_id} Assign or revoke group/user tool permissionsData model and session boundaries
Central Identity Provider (IdP) users user_id (immutable opaque UUID), status, primary_email, email_verified_at identities PRIMARY KEY (issuer, subject) -> user_id e.g. ("https://auth.acmegroup.id", "u_9aF2"), ("legacy-nova", "88123") credentials user_id, cred_type (password_hash | passkey_pub | totp_seed), material link_events event_id, user_id, linked_identity, proof_method, actor, created_at clients client_id, client_type (first_party | federated_tool), redirect_uris (exact match list), backchannel_logout_uri, public_jwks, allowed_scopes, subject_type (public | pairwise) idp_sessions sid, user_id, auth_time, acr (assurance level), amr (methods), expires_at session_clients PRIMARY KEY (sid, client_id) -> issued_at (tracks which RPs joined sid) auth_codes code_sha256, client_id, redirect_uri, user_id, sid, nonce, code_challenge, scopes, expires_at (TTL 60s), used_at refresh_tokens token_sha256, family_id, client_id, user_id, sid, scopes, aud, revoked_at Each Site (acmecloud.com, novadesk.io — isolated per-site stores) login_tx tx_id -> state, nonce, code_verifier, return_to, expires_at (TTL 10m) sessions session_id (256-bit random) -> local_user_id, iss, sid, acr, auth_time, exp local_accounts local_user_id, UNIQUE (iss, sub), site_profile_data Tool Access Service tools tool_id, mode (federation | idp_api | external_oauth), auth_metadata, allowed_scopes entitlements tool_id, principal (group_id or user_id), allowed_scopes, expires_at vault_grants PRIMARY KEY (user_id, tool_id) -> ciphertext_refresh_token, wrapped_dek, scopes, statusFour rules make this schema safe:
- Key users by
(issuer, subject), never by email. Email addresses can change, be unverified, or be reassigned when an employee leaves. Theidentitiestable maps multiple login origins cleanly onto oneuser_id. - Hash one-time codes and refresh tokens before storing them. Storing
SHA-256(token)means a read-only database leak or backup exposure cannot be replayed to hijack sessions. - Bind site sessions to the IdP
sid. Recording(sid, client_id)insession_clientsand storingsidinside each site'ssessionstable lets global logout target the exact browser session without logging the user out of their phone at the same time. - Enforce strict per-site session isolation.
acmecloud.comandnovadesk.ionever read each other's databases or cookies.
- Key users by
High-level system architecture
+----------------------------------------------------------+ | Central Identity Provider (https://auth.acmegroup.id) | | /authorize | /token | /jwks | /logout | | Users & Identities | Redis IdP Sessions | KMS Keys | +----^-----------------------^--------------------+--------+ Browser | 1. Code exchange | 2. Token exchange | 3. Back-channel (top-level HTTP | (server-to-server) | (RFC 8693) | logout + SCIM GET redirects) | | v | | +----+----------+ +--------+---------+ +---------------+ | +----->| acmecloud.com | | Tool Access |-->| Entitlement | | | Backend (RP) |-->| Service | | Service | | | client:acme | | - Policy check | | (Groups/RBAC) | | +---------------+ | - KMS Vault | +---------------+ | +---------------+ | - API Proxy | +---------------->| novadesk.io |-->+--------+---------+ | Backend (RP) | | Audience-scoped, short-lived access token | client:nova | v +---------------+ +------------------+ +-----------------------+ | External SaaS | | Partner Tool API | | API (own OAuth) | | (trusts our IdP JWKS) | +------------------+ +-----------------------+ +----------------------------------------------------------+ | Federated Third-Party Tool Web UI (OIDC / SAML RP) | | Signs users in via auth.acmegroup.id; synced via SCIM | +----------------------------------------------------------+How the architecture divides responsibilities:
- Browsers carry only short-lived redirects and opaque first-party cookies. Passwords and MFA codes are entered exclusively on
auth.acmegroup.id. Tokens are redeemed and stored strictly server-to-server. - Every site and federated tool is an isolated OIDC client with its own
client_id, asymmetric key pair, exact allowlisted callback URLs, and independent local session store. - The Tool Access Service is the sole custodian of third-party API credentials. Individual web backends (
acmecloud.com,novadesk.io) ask it to execute or authorize tool calls rather than storing third-party refresh tokens across dozens of databases.
- Browsers carry only short-lived redirects and opaque first-party cookies. Passwords and MFA codes are entered exclusively on
Deep dive 1: Cross-domain login flow (acmecloud.com then novadesk.io)
Here is the exact redirect choreography when Maya signs in on
acmecloud.comand later opensnovadesk.io:Browser acmecloud.com novadesk.io auth.acmegroup.id |-- 1. GET /projects -------->| | | |<-- 302 /authorize + tx -----| | | |-- 2. GET /authorize ------- | ------------------------- | ---------------------->| (No IdP cookie) |<-- Login page ------------- | ------------------------- | -----------------------| |-- 3. POST password + MFA -- | ------------------------- | ---------------------->| Sets IdP cookie (sid) |<-- 303 acmecloud.com/auth/callback?code=C1&state=S1 --- | -----------------------| |-- 4. GET /auth/callback --->| | | | |-- 5. POST /token (C1 + code_verifier) ------------>| | |<-- ID token (aud=acme-web, sub=u_1, sid=sid_A) ----| |<-- Set acme_session + 302 /projects | | | | | |-- 6. Later: GET novadesk.io/inbox --------------------->| (No novadesk cookie) | |<-- 302 /authorize + nova_tx cookie ---------------------| | |-- 7. GET /authorize + IdP cookie (sid_A sent!) -------- | ---------------------->| Valid sid_A! |<-- 303 novadesk.io/auth/callback?code=C2&state=S2 (0 prompts!) ------------------| |-- 8. GET /auth/callback ------------------------------->| | | |-- 9. POST /token (C2)->| | |<-- ID token (aud=nova)-| |<-- Set nova_session + 302 /inbox -----------------------| |Step-by-step security invariants during first sign-in on
acmecloud.com:- Transaction binding before redirect:
acmecloud.comgenerates three random secrets:state(blocks Cross-Site Request Forgery, CSRF, where an attacker tricks Maya's browser into completing a login into the attacker's account),nonce(binds the resulting ID token to this exact login attempt to prevent token replay), and a PKCE (Proof Key for Code Exchange)code_verifier(a random secret whoseSHA-256hash,code_challenge, is sent now and verified during code redemption so an intercepted code is useless alone).acmecloud.comstores these undertx_id, sets cookie__Host-acme_tx=<tx_id>; Secure; HttpOnly; SameSite=Lax; Path=/; Max-Age=600, and redirects to/oauth2/authorize. - Strict
redirect_uricheck at the IdP: Before rendering anything, the IdP verifiesclient_id=acme-weband checks byte-for-byte equality ofredirect_uriagainstacme-web's allowlist. If mismatched, the IdP renders an error page directly and never redirects—redirecting to an untrusted URL leaks codes or error metadata. - Authentication and IdP cookie creation: Because Maya has no IdP cookie yet, she enters her credentials + MFA on
auth.acmegroup.id. The IdP creates sessionsid_A, sets__Host-idp_session=<opaque>; Secure; HttpOnly; SameSite=Lax; Path=/onauth.acmegroup.id, stores single-usecode=C1(60-second TTL), and returns303 See Othertohttps://acmecloud.com/auth/callback?code=C1&state=S1&iss=https://auth.acmegroup.id. - Callback verification and server-to-server redemption: Because the redirect is a top-level
GETnavigation, the browser attaches__Host-acme_tx.acmecloud.comloads and deletestx_id(one-time use), verifiesstateandiss, and callsPOST /oauth2/tokenauthenticated withprivate_key_jwt(signing a short-lived client assertion withacmecloud.com's private key so no shared secret travels over the wire). The IdP checksSHA256(code_verifier) == code_challenge, marksC1used, and returns an ID token—a signed JSON Web Token (JWT) describing the authentication event. - ID token validation and local session creation:
acmecloud.comverifies the JWT signature against the cached JWKS key matchingkid, enforces an allowlisted signing algorithm (nevernone), checksiss, checksaud == "acme-web", checksexp/iatwithin 60 seconds of clock skew, and verifiesnonce. It then issues a brand-new random__Host-acme_sessioncookie (never reusing any pre-login cookie, which prevents session fixation) and redirects to a validated relative path/projects(preventing open-redirect attacks).
Why
novadesk.iosigns in silently—even with third-party cookies blocked: When Maya visitsnovadesk.io/inbox,novadesk.iohas no cookie and redirects the top-level browser tab tohttps://auth.acmegroup.id/oauth2/authorize. Becauseauth.acmegroup.idis now the address in the browser's top-level URL bar,__Host-idp_sessionis a first-party cookie, so every browser sends it regardless of third-party cookie blocking. Note two subtle cookie choices: - We useSameSite=Lax(notSameSite=Strict) andresponse_mode=query(notform_post) becauseSameSite=Laxcookies are sent on cross-site top-levelGETredirects, whereasStrictwould withhold__Host-acme_txon the return hop from the IdP andform_postwould turn the callback into a cross-sitePOSTthat dropsLaxcookies. - The__Host-cookie prefix forcesSecure,Path=/, and noDomainattribute, preventing sibling subdomains from planting or overwriting session cookies.Expired IdP sessions and step-up assurance: - If
sid_Ahas expired when Maya visitsnovadesk.io, step 7 naturally shows the IdP login screen. If a public homepage wants to check whether Maya is signed in without forcing a login screen, it can do at most one top-level redirect per browser session withprompt=none(receivingerror=login_requiredif signed out and caching "anonymous" locally so visitors are not bounced repeatedly). - Ifnovadesk.io/billingrequires MFA within 15 minutes,novadesk.ioredirects withacr_values=urn:acme:acr:mfa&max_age=900. The IdP prompts only for the missing second factor and updatessid_A.novadesk.iomust still verifyacrandauth_timeinside the returned ID token, becauseacr_valuesin OIDC is a requested preference, not a guarantee unless verified by the relying party.- Transaction binding before redirect:
Deep dive 2: Multi-site scaling and third-party tool access
Scaling from two sites to twenty follows strict per-client isolation: every web app, mobile app, and tool gets its own
client_id, asymmetric credentials, exact callback URIs (never wildcards—one open redirect on a wildcarded domain lets attackers steal authorization codes), and independent session TTLs. Single-page apps talk to a lightweight Backend-for-Frontend (BFF) server on their own domain so tokens stay out of browserlocalStorage(where any Cross-Site Scripting bug could steal them). External tools can also be configured with pairwisesubidentifiers—cryptographically salted per-client user IDs so two outside vendors cannot collude to correlate user activity by ID.For third-party tools, separate signing a user into a tool's UI from calling a tool's API:
Path A: Federated Sign-In (User -> Tool's Web UI) Browser -> Tool UI -> 302 auth.acmegroup.id -> Policy hook checks Entitlement Service -> Issues ID token (aud = tool_client_id) or SAML assertion -> Tool creates its own session Path B: Delegated API Access (User -> novadesk.io -> Tool Access Service -> Tool's API) novadesk.io -> Tool Access Service (checks Entitlement Service + active user consent) -> Variant 1 (Tool API trusts our IdP): OAuth Token Exchange (RFC 8693) mints 5-min JWT with typ="at+jwt", aud="https://api.tool.example", scope="tickets:read" -> Variant 2 (SaaS tool with own OAuth): Decrypts refresh token from KMS Vault, lazily refreshes if expired, attaches SaaS access token -> Calls Tool APIWhy an ID token must NEVER be used as an API credential: An ID token is like a stamped entry stub proving Maya entered
acmecloud.com(aud: "acme-web"). It carries no API permission scopes (readvsdelete) and is not addressed to any API. If an API accepted ID tokens as bearer credentials, any website or vendor where Maya signed in could replay her ID token to impersonate her against that API. APIs must require access tokens explicitly addressed to that API's resource URI (aud) with narrowscopeclaims.How each integration mode works:
- Federated sign-in (OIDC or SAML): Some enterprise tools only speak SAML (Security Assertion Markup Language), an older XML-based SSO standard; our IdP supports both OIDC and SAML clients. Before issuing an assertion, the IdP queries the Entitlement Service (
allowed(user_id, tool_id)). Account creation and removal are automated via SCIM (System for Cross-domain Identity Management), a standard REST protocol that pushes user provisioning and instant deactivation to SaaS tools when group memberships change. - Partner APIs that trust our IdP:
novadesk.iocalls the Tool Access Service, which performs OAuth 2.0 Token Exchange (RFC 8693) at our IdP to trade the caller's token for a5–10 minuteJWT access token (typ: at+jwt, RFC 9068) bound toresource=https://api.tool.exampleand intersected with the user's entitled scopes. - External SaaS APIs with their own OAuth servers (e.g., Slack, GitHub, Jira): The user clicks "Connect Tool", starting an OAuth authorization-code + PKCE flow against the tool's OAuth server, bound via
stateto the user's authenticated session (preventing an attacker from linking the attacker's SaaS account to the victim's profile). The returned refresh token is stored in the Token Vault using envelope encryption: each row is encrypted with a unique Data Encryption Key (DEK), and that DEK is encrypted by a hardware Key Management Service (KMS). Short-lived access tokens are cached in memory and refreshed lazily on demand. - Organization-wide service accounts (
client_credentials): When a tool only supports one company-wide API key, the Tool Access Service must check the calling user's entitlement and object-level permissions before every outgoing request. Skipping that check creates a confused deputy vulnerability, where an underprivileged user tricks our privileged backend into reading or modifying another user's records.
Every tool request evaluates one policy rule (cached for at most 60 seconds):
allow(user, tool, requested_scopes) = user.status == ACTIVE at IdP AND non-expired entitlement exists for user (or user's group) on tool AND requested_scopes is a subset of entitlement.allowed_scopes AND (tool requires user consent => active vault_grant or consent covers requested_scopes)- Federated sign-in (OIDC or SAML): Some enterprise tools only speak SAML (Security Assertion Markup Language), an older XML-based SSO standard; our IdP supports both OIDC and SAML clients. Before issuing an assertion, the IdP queries the Entitlement Service (
Deep dive 3: Safe account linking, logout, and revocation
Lazy migration and safe account linking for
novadesk.io: Forcing10Macquirednovadesk.iousers to reset passwords on day one causes massive drop-off. Instead, use lazy migration: when an unmigratednovadesk.iouser signs in atauth.acmegroup.id, the IdP verifies their password againstnovadesk.io's legacy store once, creates a centraluser_idmapped to("legacy-nova", old_id), and stores a fresh Argon2id hash centrally.What if
maya@gmail.comalready exists on bothacmecloud.comandnovadesk.io? Never auto-merge accounts based on matching email: - One site may never have verified email ownership. - Employers and email providers recycle addresses when people leave. - An attacker who knowsmaya@company.comusesacmecloud.comcould pre-registermaya@company.comonnovadesk.iobefore the acquisition, waiting for an auto-merge to grant full access to Maya'sacmecloud.comaccount (a pre-account takeover attack).Safe linking rule—proof of control of both accounts in one session: 1. Maya signs in to account A with a fresh authentication (
max_age <= 300s). 2. Inside an "Attach existingnovadesk.ioaccount" flow, the IdP requires Maya to authenticate to account B using B's own credentials and MFA. 3. Maya confirms the merge preview; the IdP attaches B's(issuer, subject)row inidentitiesto A'suser_id, writes an immutablelink_eventsaudit entry, and emails security notifications to both addresses. Until linked, the two accounts remain completely separate principals.Logout and revocation across independent session layers:
State Layer How It Ends What Remains Active Unless Handled acmecloud.comlocal sessionDelete server session row + clear __Host-acme_sessionIdP session, novadesk.iosession, API tokens, tool sessionsCentral IdP session ( sid)GET /oauth2/logoutwithid_token_hintAlready-established novadesk.iolocal sessionsSibling site sessions ( novadesk.io)Back-channel logout ( POST /auth/backchannel-logout)Sites temporarily unreachable (bounded by retry + TTL) JWT access tokens Natural expiry ( 5–10 minexp) or/oauth2/introspectValid until expat stateless APIsIdP refresh tokens Revoked immediately by sidoruser_idNothing once revoked Vaulted third-party grants DELETE /tools/{id}/connection+ RFC 7009 call to toolIntentionally survive normal browser logout for background jobs Third-party tool web sessions Tool's own logout or SCIM account deactivation Tool's local browser cookie until its own TTL expires Why OIDC Back-Channel Logout beats Front-Channel Logout: Front-channel logout embeds hidden
<iframe>tags pointing to each site's logout URL, relying on the browser sending third-party cookies inside those iframes—which modern Safari, Firefox, and Chrome third-party cookie restrictions break. Instead, in Back-Channel Logout, the IdP looks up everyclient_idrecorded insession_clientsforsidand sends a server-to-serverPOSTcarrying a signedlogout_tokenJWT (typ: logout+jwt, containingiss,aud,iat,jti,sid, thebackchannel-logouteventsclaim, and explicitly nononceclaim so it can never be replayed as an ID token). Each site validates the JWT, deletes local sessions matchingsid, and returns200 OK(with exponential-backoff retries on network failure).Note the local-only logout trap: if
acmecloud.comonly clears__Host-acme_sessionand leaves the IdP session alive, clicking "Sign in" (or hitting a protected route) bounces throughauth.acmegroup.idand silently logs Maya right back in—broken UX on a shared computer! Make global IdP logout the default, and provide an emergency admin kill-switch (for compromised accounts or departing employees) that disables the user, purges allidp_sessionsandrefresh_tokens, fires back-channel logouts, revokes vaulted SaaS grants, and sends SCIM deactivation calls to every federated tool.Scaling, failure handling, and trade-off summary
Scaling and operational resilience
- Multi-region stateless IdP: Run stateless IdP servers across at least two regions behind geo-steered load balancers, backed by active-active replicated Redis for
idp_sessionsandauth_codes(codes require read-after-write consistency or encrypted self-contained payloads + a replicated single-usejtiset so a code issued in Region A can be redeemed milliseconds later in Region B). - Local cryptographic signing and key rotation: Calling a remote KMS over the network
2,000times/second adds tail latency and risks KMS throttling. Instead, unwrap the active signing key into IdP memory at startup, rotate keys regularly, publish the upcoming public key in/oauth2/jwksbefore signing with it, and keep retired public keys in JWKS until every token signed with them expires. - Graceful behavior during an IdP outage: Because
acmecloud.comandnovadesk.iovalidate the ID token once at login and rely on their own local session stores afterward, an IdP outage never breaks already-signed-in users; only brand-new logins, step-up prompts, and expired token refreshes fail fast with a clear status message. - Stolen code or refresh token defense: If an authorization code is presented a second time, reject it and immediately revoke all tokens issued on its first redemption. For refresh tokens, use refresh token rotation: every refresh issues a new token under the same
family_idand invalidates the old one; if an already-rotated token is ever presented again, revoke the entirefamily_id. - Multi-issuer mix-up defense: Include and verify the
issquery parameter on/auth/callback(RFC 9207) so responses from external OAuth servers can never be confused with our central IdP.
Summary of key trade-offs
- Top-level OIDC redirects vs hidden-iframe silent checks: Full-page redirects treat the IdP cookie as first-party so SSO survives third-party cookie blocking, trading a
~200 msinitial redirect bounce for universal browser reliability. - Independent local site sessions vs per-request central IdP checks: Local sessions give sub-millisecond checks and survive IdP outages, trading instant session termination for asynchronous back-channel logout propagation.
- Single shared IdP domain vs per-brand vanity login domains: One domain (
auth.acmegroup.id) shares the IdP cookie effortlessly across brands, trading URL vanity branding for seamless cross-domain SSO. - Short-lived stateless JWT access tokens vs opaque tokens with introspection:
5–10 minuteJWTs let APIs verify requests locally at zero IdP cost, trading instant mid-TTL revocation (reserved via/introspectfor high-risk endpoints) for low latency and high availability. - Centralized Token Vault vs per-site OAuth storage: Routing external API tokens through one KMS-backed Tool Access Service adds one internal hop on tool API calls, in exchange for a narrow blast radius, unified entitlement checks, and one-click revocation.
- Multi-region stateless IdP: Run stateless IdP servers across at least two regions behind geo-steered load balancers, backed by active-active replicated Redis for
Intuition & how it works
Think of acmecloud.com and novadesk.io as two office buildings on different streets owned by the same parent company, and the central Identity Provider (IdP) (auth.acmegroup.id) as a central security badge desk down the block. Neither building accepts the other building's local visitor sticker, and neither building ever asks to see your passport (your password). Instead, the first time you arrive at acmecloud.com, the guard directs you to the central badge desk, where you verify your passport once, keep a master check-in slip on file at the desk, and walk back to acmecloud.com with a sealed, 60-second voucher addressed only to acmecloud.com. acmecloud.com verifies that voucher directly with the badge desk and issues its own acmecloud.com visitor pass. Ten minutes later, when you walk over to novadesk.io, its guard also sends you to the central badge desk—which immediately recognizes your active check-in slip, skips the passport check, and hands you a fresh voucher addressed to novadesk.io.
Why do simpler approaches fail? Browser security enforces the registrable-domain boundary (isolating cookies by base domain such as acmecloud.com vs novadesk.io), so the two sites literally cannot read or write each other's cookies. Passing session tokens in URL query links exposes live credentials in browser history, proxy logs, and HTTP Referer headers, while checking login status inside hidden cross-site <iframe> elements fails in modern browsers that block or partition third-party cookies (cookies belonging to a domain different from the top-level URL bar). Finally, forwarding a sign-in receipt (ID token) directly to third-party APIs lets any site where a user signed in impersonate that user everywhere.
Here is a concrete 5-event trace showing how OpenID Connect (OIDC) (an identity layer built on OAuth 2.0) solves both cross-domain sign-in and tool access:
1. Visit acmecloud.com: Maya opens https://acmecloud.com/projects with no cookie; acmecloud.com saves a one-time login transaction (state, nonce, and a PKCE secret verifier) and redirects her browser tab to https://auth.acmegroup.id/oauth2/authorize.
2. Authenticate once at the IdP: Maya enters her password and Multi-Factor Authentication (MFA) code on auth.acmegroup.id, which sets first-party cookie sid=S1 on auth.acmegroup.id and redirects back to acmecloud.com/auth/callback?code=C1.
3. Create acmecloud.com local session: acmecloud.com's server trades C1 server-to-server at POST /oauth2/token for a signed ID token (aud="acme-web", sub="u_42"), verifies its signature, and sets acmecloud.com's own session cookie.
4. Silent SSO to novadesk.io: Maya clicks over to https://novadesk.io/inbox; novadesk.io redirects her top-level tab to auth.acmegroup.id, where the browser automatically sends sid=S1 as a first-party cookie, so the IdP skips the password prompt and immediately redirects back with code=C2 for novadesk.io to start its own independent session.
5. Call a third-party tool API: When Maya triggers an external ticket lookup from novadesk.io, novadesk.io never forwards her ID token; instead, an internal Tool Access Service checks her group entitlement (assigned permission) and uses a short-lived, narrowly scoped access token (aud="https://api.tickets.example", scope="tickets:read") retrieved via OAuth token exchange or from an encrypted Token Vault.
Key trade-offs
- Top-level browser redirects vs hidden-iframe silent checks. Full-page redirects navigate the top-level browser tab to
auth.acmegroup.id, making the IdP cookie a first-party cookie that survives strict third-party cookie blocking. The trade-off is a brief~200 msredirect hop when starting a new site session, whereas hidden iframes avoid the visual hop but silently fail in Safari, Firefox, and privacy-hardened browsers. - Independent local site sessions vs per-request IdP validation. Validating the ID token once at login and issuing a local site cookie keeps page loads fast and lets
acmecloud.comandnovadesk.iostay up even during an IdP outage. The trade-off is that global logout is asynchronous—propagated via back-channel logout (server-to-server webhook notifications from the IdP to each site) rather than instantaneous. - Confidential server-side client (Backend-for-Frontend) vs storing tokens in browser JavaScript. Redeeming codes on the backend and giving the browser only an
HttpOnlysession cookie protects access and refresh tokens from Cross-Site Scripting (XSS) theft, at the cost of running a lightweight server layer per web app. - One canonical IdP hostname vs per-brand vanity login domains. Hosting the IdP on a single domain (
auth.acmegroup.id) lets all sites share one IdP session cookie. Giving each brand its own login hostname (login.acmecloud.com,login.novadesk.io) looks custom in the URL bar but splits cookies into separate browser jars and breaks cross-domain SSO. - Short-lived stateless JWT access tokens vs opaque tokens with introspection. A JSON Web Token (JWT) (a cryptographically signed JSON payload) with a
5–10 minutelifetime can be verified locally by APIs using cached public keys (JWKS), avoiding per-request IdP calls at the cost of up to5–10 minutesof revocation delay. Token introspection (calling the IdP on each API request to check live status) revokes access instantly at the cost of extra latency and IdP load; reserve it for high-risk endpoints. - OAuth Token Exchange at our IdP vs vaulting external SaaS refresh tokens. When a partner API trusts our IdP, OAuth Token Exchange (RFC 8693) mints audience-restricted tokens centrally with zero long-lived secrets to store. Most commercial SaaS APIs only trust their own OAuth servers, requiring us to store their refresh tokens under envelope encryption (encrypting each token with a data key wrapped by a hardware Key Management Service, KMS) and revoke them per vendor.
- Lazy credential migration + proof-of-control linking vs forced resets or email auto-merge. Verifying legacy
novadesk.iopasswords on first login avoids disruptive mass password resets, and requiring sign-in to both accounts before linking adds one step for dual-account users in exchange for blocking account-takeover attacks.
Common mistakes
- Trying to share cookies across
acmecloud.comandnovadesk.ioor passing session IDs in URLs. Browsers reject cross-domain cookies, and session tokens in URLs leak via server logs, browser history, copy-pasted links, andRefererheaders. - Returning tokens directly to the browser URL fragment (the legacy OAuth implicit flow) instead of using the Authorization Code flow with PKCE (Proof Key for Code Exchange, which binds the one-time code to a secret generated by the client) and server-side redemption.
- Omitting
stateornoncechecks, or breaking transaction cookies with mismatchedSameSitesettings. Skippingstateenables login CSRF; skippingnonceenables ID-token replay; pairing aSameSite=Laxtransaction cookie withresponse_mode=form_postdrops the cookie on the cross-sitePOSTcallback. - Accepting an ID token without checking
aud(audience), or sending an ID token as an API bearer token. Failing to verifyaudlets a token minted for one client sign into another, and using ID tokens for API calls violates audience and scope isolation. - Allowing wildcard
redirect_uripatterns (such ashttps://*.acmecloud.com/*), which lets a single open redirect or compromised subdomain steal authorization codes. - Auto-merging
acmecloud.comandnovadesk.ioaccounts solely because they share an email address, enabling pre-account takeover when one side's email is unverified or pre-registered by an attacker. - Clearing only the local site cookie on logout while leaving the IdP session active, causing the user to be silently signed right back in on their next click.
- Relying on hidden-iframe front-channel logout, which silently fails to clear sibling site cookies when third-party cookies are blocked.
- Using a single organization-wide API service token for a third-party tool without checking per-user permissions first, creating a confused deputy bug where any signed-in user can read or mutate another user's records through the backend.
Follow-up questions
- Suppose a user already owns unlinked accounts under the same email address on both domains—how do you link them without risking account takeover? Treat the two accounts as completely independent principals until the human proves control over both inside one authenticated session. Concretely, after authenticating freshly (
max_age <= 5 minutes) into account A, the user opens an explicit "Attach existingnovadesk.ioaccount" workflow and must sign into account B using B's own password and MFA factor; only upon confirmation does the IdP attach both(issuer, subject)entries to a singleuser_id, write an append-onlylink_eventsaudit record, and send security notifications to both email addresses. A shared email string may trigger a UI banner offering to link, yet must never auto-merge accounts, because unverified, recycled, or attacker-planted email addresses would let an impersonator hijack the victim's account. - Why do legacy iframe-based SSO patterns break under modern browser cookie partitioning, and how does your design stay functional? Modern browsers partition or block cookies inside cross-origin
<iframe>tags becauseauth.acmegroup.idinside an iframe onnovadesk.iois a third-party context—breaking both silentprompt=noneiframe token renewal and front-channel iframe logout. Our architecture performs all sign-in transitions via top-level browserGETredirects to a single canonical IdP hostname (auth.acmegroup.id), where__Host-idp_session(SameSite=Lax) is sent as an unblocked first-party cookie. Token refresh runs server-to-server behind a Backend-for-Frontend (HttpOnlycookie), ecosystem logout propagates server-to-server via OIDC Back-Channel Logout webhooks, anonymous landing pages perform at most one top-levelprompt=nonecheck per session, and bounce-tracking storage purges after prolonged inactivity simply fall back cleanly to a fresh login prompt. - If a user clicks logout on just a single application domain, which credentials, tokens, and sessions remain live across the ecosystem? Clearing only
acmecloud.com's local session cookie leaves active: the central IdP sessionsid(which would silently sign the user right back intoacmecloud.comon the next protected click), independent local sessions onnovadesk.ioand other first-party sites, previously minted JWT access tokens until their5–10 minuteexpdeadline, IdP refresh tokens held by sibling apps, KMS-encrypted SaaS OAuth grants inside the Token Vault, standalone browser sessions inside federated third-party web tools, and sessions on separate devices. Triggering RP-initiated IdP logout killssid, revokes associated IdP refresh tokens, and pushes back-channel logout webhooks to sibling company sites, while short-lived JWTs expire within minutes and vaulted background OAuth grants persist unless explicitly disconnected. Emergency account compromise or offboarding invokes the admin kill-switch to disable the user, purge all sessions and vault grants, enforce/introspecton sensitive endpoints, and push SCIM deactivation to federated SaaS tools.
Follow-up questions
- Suppose a user already owns unlinked accounts under the same email address on both domains—how do you link them without risking account takeover?
- Why do legacy iframe-based SSO patterns break under modern browser cookie partitioning, and how does your design stay functional?
- If a user clicks logout on just a single application domain, which credentials, tokens, and sessions remain live across the ecosystem?
Similar questions
- Multi-Tenant Time-Series Metrics Platform
- Real-Time Messaging and Critical Alert Platform
- Cross-Domain OIDC Single Sign-On and Third-Party API Delegation
- Three-Part Behavioral Screen: AI Workflows, Peer Leadership, and Cross-Team Delivery
- Securing an MCP Server with Auth0 RS256 Tokens
- Configurable Token-Bucket API Rate Limiter and Code Review
More Okta interview questions
- Three-Part Behavioral Screen: AI Workflows, Peer Leadership, and Cross-Team Delivery Medium
- Configurable Token-Bucket API Rate Limiter and Code Review Medium
- Fixing a Blocking Express Login Endpoint Safely Medium Pro
- Securing an MCP Server with Auth0 RS256 Tokens Medium Pro
- Order-Preserving Array Deduplication Medium Pro
- Real-Time Messaging and Critical Alert Platform Medium Pro
- Cross-Domain OIDC Single Sign-On and Third-Party API Delegation Medium Pro
- Multi-Tenant Time-Series Metrics Platform Medium Pro
- Refactor Session Deduplication for Time and Memory Medium Pro
- Filter Valid IPv4 Addresses Medium Pro