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

  1. Clarify requirements and core concepts

    After the company behind acmecloud.com acquires novadesk.io, customers expect Single Sign-On (SSO)—authenticating once and navigating across both web apps without re-entering credentials. Because acmecloud.com and novadesk.io sit on separate registrable domains (distinct base domains registered independently in the public suffix list), browsers isolate their cookie jars completely: acmecloud.com cannot set or read cookies belonging to novadesk.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.com lets Maya open novadesk.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 on acmecloud.com and novadesk.io remain unaffected during transient IdP downtime.
    • Latency: Cross-domain silent SSO adds at most 200–300 ms of redirect time when establishing a site's local session, and 0 ms on 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.io accounts migrate lazily into the central IdP upon login. Pre-existing accounts on acmecloud.com and novadesk.io sharing 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.
  2. Back-of-the-envelope capacity estimates

    Assume acmecloud.com holds 22M existing account rows and novadesk.io holds 10M (32M total rows with ~2M overlapping individuals, or ~30M unique people). Assume 5M daily active users (DAU) visit an average of 2 company domains per day and create 1.5 local sessions per domain per day, while 1M active 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/s is comfortably served by a small multi-region fleet of stateless IdP servers and a 5 GB replicated 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 /authorize hits 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.
  3. API and protocol endpoints

    Every site must redirect to the IdP under one canonical hostname (https://auth.acmegroup.id). If acmecloud.com used login.acmecloud.com and novadesk.io used login.novadesk.io as branded aliases, the browser would store the IdP cookie under login.acmecloud.com and never send it to login.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 logout
    

    Each 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_token
    

    An 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 permissions
    
  4. Data 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, status
    

    Four rules make this schema safe:

    1. Key users by (issuer, subject), never by email. Email addresses can change, be unverified, or be reassigned when an employee leaves. The identities table maps multiple login origins cleanly onto one user_id.
    2. 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.
    3. Bind site sessions to the IdP sid. Recording (sid, client_id) in session_clients and storing sid inside each site's sessions table lets global logout target the exact browser session without logging the user out of their phone at the same time.
    4. Enforce strict per-site session isolation. acmecloud.com and novadesk.io never read each other's databases or cookies.
  5. 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.
  6. Deep dive 1: Cross-domain login flow (acmecloud.com then novadesk.io)

    Here is the exact redirect choreography when Maya signs in on acmecloud.com and later opens novadesk.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:

    1. Transaction binding before redirect: acmecloud.com generates 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 whose SHA-256 hash, code_challenge, is sent now and verified during code redemption so an intercepted code is useless alone). acmecloud.com stores these under tx_id, sets cookie __Host-acme_tx=<tx_id>; Secure; HttpOnly; SameSite=Lax; Path=/; Max-Age=600, and redirects to /oauth2/authorize.
    2. Strict redirect_uri check at the IdP: Before rendering anything, the IdP verifies client_id=acme-web and checks byte-for-byte equality of redirect_uri against acme-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.
    3. Authentication and IdP cookie creation: Because Maya has no IdP cookie yet, she enters her credentials + MFA on auth.acmegroup.id. The IdP creates session sid_A, sets __Host-idp_session=<opaque>; Secure; HttpOnly; SameSite=Lax; Path=/ on auth.acmegroup.id, stores single-use code=C1 (60-second TTL), and returns 303 See Other to https://acmecloud.com/auth/callback?code=C1&state=S1&iss=https://auth.acmegroup.id.
    4. Callback verification and server-to-server redemption: Because the redirect is a top-level GET navigation, the browser attaches __Host-acme_tx. acmecloud.com loads and deletes tx_id (one-time use), verifies state and iss, and calls POST /oauth2/token authenticated with private_key_jwt (signing a short-lived client assertion with acmecloud.com's private key so no shared secret travels over the wire). The IdP checks SHA256(code_verifier) == code_challenge, marks C1 used, and returns an ID token—a signed JSON Web Token (JWT) describing the authentication event.
    5. ID token validation and local session creation: acmecloud.com verifies the JWT signature against the cached JWKS key matching kid, enforces an allowlisted signing algorithm (never none), checks iss, checks aud == "acme-web", checks exp/iat within 60 seconds of clock skew, and verifies nonce. It then issues a brand-new random __Host-acme_session cookie (never reusing any pre-login cookie, which prevents session fixation) and redirects to a validated relative path /projects (preventing open-redirect attacks).

    Why novadesk.io signs in silently—even with third-party cookies blocked: When Maya visits novadesk.io/inbox, novadesk.io has no cookie and redirects the top-level browser tab to https://auth.acmegroup.id/oauth2/authorize. Because auth.acmegroup.id is now the address in the browser's top-level URL bar, __Host-idp_session is a first-party cookie, so every browser sends it regardless of third-party cookie blocking. Note two subtle cookie choices: - We use SameSite=Lax (not SameSite=Strict) and response_mode=query (not form_post) because SameSite=Lax cookies are sent on cross-site top-level GET redirects, whereas Strict would withhold __Host-acme_tx on the return hop from the IdP and form_post would turn the callback into a cross-site POST that drops Lax cookies. - The __Host- cookie prefix forces Secure, Path=/, and no Domain attribute, preventing sibling subdomains from planting or overwriting session cookies.

    Expired IdP sessions and step-up assurance: - If sid_A has expired when Maya visits novadesk.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 with prompt=none (receiving error=login_required if signed out and caching "anonymous" locally so visitors are not bounced repeatedly). - If novadesk.io/billing requires MFA within 15 minutes, novadesk.io redirects with acr_values=urn:acme:acr:mfa&max_age=900. The IdP prompts only for the missing second factor and updates sid_A. novadesk.io must still verify acr and auth_time inside the returned ID token, because acr_values in OIDC is a requested preference, not a guarantee unless verified by the relying party.

  7. 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 browser localStorage (where any Cross-Site Scripting bug could steal them). External tools can also be configured with pairwise sub identifiers—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 API
    

    Why 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 (read vs delete) 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 narrow scope claims.

    How each integration mode works:

    1. 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.
    2. Partner APIs that trust our IdP: novadesk.io calls the Tool Access Service, which performs OAuth 2.0 Token Exchange (RFC 8693) at our IdP to trade the caller's token for a 5–10 minute JWT access token (typ: at+jwt, RFC 9068) bound to resource=https://api.tool.example and intersected with the user's entitled scopes.
    3. 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 state to 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.
    4. 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)
    
  8. Deep dive 3: Safe account linking, logout, and revocation

    Lazy migration and safe account linking for novadesk.io: Forcing 10M acquired novadesk.io users to reset passwords on day one causes massive drop-off. Instead, use lazy migration: when an unmigrated novadesk.io user signs in at auth.acmegroup.id, the IdP verifies their password against novadesk.io's legacy store once, creates a central user_id mapped to ("legacy-nova", old_id), and stores a fresh Argon2id hash centrally.

    What if maya@gmail.com already exists on both acmecloud.com and novadesk.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 knows maya@company.com uses acmecloud.com could pre-register maya@company.com on novadesk.io before the acquisition, waiting for an auto-merge to grant full access to Maya's acmecloud.com account (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 existing novadesk.io account" 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 in identities to A's user_id, writes an immutable link_events audit 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.com local session Delete server session row + clear __Host-acme_session IdP session, novadesk.io session, API tokens, tool sessions
    Central IdP session (sid) GET /oauth2/logout with id_token_hint Already-established novadesk.io local sessions
    Sibling 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 min exp) or /oauth2/introspect Valid until exp at stateless APIs
    IdP refresh tokens Revoked immediately by sid or user_id Nothing once revoked
    Vaulted third-party grants DELETE /tools/{id}/connection + RFC 7009 call to tool Intentionally 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 every client_id recorded in session_clients for sid and sends a server-to-server POST carrying a signed logout_token JWT (typ: logout+jwt, containing iss, aud, iat, jti, sid, the backchannel-logout events claim, and explicitly no nonce claim so it can never be replayed as an ID token). Each site validates the JWT, deletes local sessions matching sid, and returns 200 OK (with exponential-backoff retries on network failure).

    Note the local-only logout trap: if acmecloud.com only clears __Host-acme_session and leaves the IdP session alive, clicking "Sign in" (or hitting a protected route) bounces through auth.acmegroup.id and 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 all idp_sessions and refresh_tokens, fires back-channel logouts, revokes vaulted SaaS grants, and sends SCIM deactivation calls to every federated tool.

  9. 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_sessions and auth_codes (codes require read-after-write consistency or encrypted self-contained payloads + a replicated single-use jti set 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,000 times/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/jwks before 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.com and novadesk.io validate 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_id and invalidates the old one; if an already-rotated token is ever presented again, revoke the entire family_id.
    • Multi-issuer mix-up defense: Include and verify the iss query 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 ms initial 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 minute JWTs let APIs verify requests locally at zero IdP cost, trading instant mid-TTL revocation (reserved via /introspect for 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.

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 ms redirect 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.com and novadesk.io stay 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 HttpOnly session 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 minute lifetime can be verified locally by APIs using cached public keys (JWKS), avoiding per-request IdP calls at the cost of up to 5–10 minutes of 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.io passwords 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.com and novadesk.io or passing session IDs in URLs. Browsers reject cross-domain cookies, and session tokens in URLs leak via server logs, browser history, copy-pasted links, and Referer headers.
  • 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 state or nonce checks, or breaking transaction cookies with mismatched SameSite settings. Skipping state enables login CSRF; skipping nonce enables ID-token replay; pairing a SameSite=Lax transaction cookie with response_mode=form_post drops the cookie on the cross-site POST callback.
  • Accepting an ID token without checking aud (audience), or sending an ID token as an API bearer token. Failing to verify aud lets a token minted for one client sign into another, and using ID tokens for API calls violates audience and scope isolation.
  • Allowing wildcard redirect_uri patterns (such as https://*.acmecloud.com/*), which lets a single open redirect or compromised subdomain steal authorization codes.
  • Auto-merging acmecloud.com and novadesk.io accounts 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 existing novadesk.io account" 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 single user_id, write an append-only link_events audit 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 because auth.acmegroup.id inside an iframe on novadesk.io is a third-party context—breaking both silent prompt=none iframe token renewal and front-channel iframe logout. Our architecture performs all sign-in transitions via top-level browser GET redirects 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 (HttpOnly cookie), ecosystem logout propagates server-to-server via OIDC Back-Channel Logout webhooks, anonymous landing pages perform at most one top-level prompt=none check 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 session sid (which would silently sign the user right back into acmecloud.com on the next protected click), independent local sessions on novadesk.io and other first-party sites, previously minted JWT access tokens until their 5–10 minute exp deadline, 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 kills sid, 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 /introspect on sensitive endpoints, and push SCIM deactivation to federated SaaS tools.

Follow-up questions

Similar questions

More Okta interview questions

All 11 Okta questions →