Single Sign-On and identity management built for developers, organizations, and enterprises. Explore documentation →
Logo

Preventing Cross-Tenant Data Leaks with Strict Issuer and Audience Token Isolation

Defending multi-tenant B2B APIs against JWT replay, confused-deputy attacks, and broken object-level authorization using cryptographic claims and Postgres RLS.

PE
SSO.ID Platform Engineering
B2B & Enterprise Federation · 2026-11-06 · 9 min read
LinkedIn Share
Why This Matters Right Now

In a shared multi-tenant SaaS architecture, a single missing tenant check or overly broad JWT validation rule turns a legitimate customer token into a skeleton key across every other tenant's database rows. Cross-tenant confused-deputy leaks remain the most catastrophic failure mode in B2B cloud platforms—destroying customer trust and triggering mandatory breach disclosures.

Key Takeaways

  • Never trust client-supplied X-Tenant-Id or X-Organization-Id headers as authorization proof; derive tenant boundaries exclusively from cryptographically signed JWT claims.
  • Pin exact iss (Issuer), aud (Audience), and org_id claims on every microservice boundary so tokens minted for one application or tenant cannot replay against another.
  • Enforce database-level PostgreSQL Row-Level Security (RLS) bound to the verified JWT org_id claim so even a forgotten SQL WHERE clause cannot leak cross-tenant rows.
  • Isolate enterprise IdP connections with domain verification and assignToOrganizationOnly scoping to prevent federation cross-pollination.

How Cross-Tenant Confused-Deputy Attacks Happen in Practice

The classic multi-tenant confused-deputy vulnerability rarely looks like an exotic cryptographic break—it happens when an API validates that a JWT signature is authentic, extracts the user's sub claim, and then trusts an unverified URL path parameter or X-Tenant-Id header to fetch a record. If an attacker signs up for a free workspace (Organization A) on your platform, obtains a completely valid RS256 access token, and replays that token against GET /v1/orgs/org_b/invoices or manipulates a GraphQL object ID, a service that forgets to cross-check the token's org_id claim happily serves Organization B's confidential data.

A second subtle variant occurs across sibling applications sharing the same identity provider. When every service—say, a low-trust marketing portal and a high-trust billing API—validates signatures against the same JWKS keyset without enforcing strict aud (Audience) and iss (Issuer) constraints, an access token scoped for the marketing portal can be replayed directly against administrative billing endpoints. Even caching layers introduce cross-tenant leaks when Redis keys omit the verified org_id prefix.

  • Header spoofing: trusting mutable HTTP headers like X-Tenant-Id or subdomain strings without verifying them against signed JWT claims.
  • Audience confusion: accepting tokens issued for a different client or microservice because the API only checks signature validity and expiration.
  • Broken Object-Level Authorization (BOLA): querying records by primary key UUID alone without scoping every query to the token's verified org_id.
  • Cache key collisions: storing rendered dashboards, permissions, or export artifacts under userId or reportId without embedding org_id in the cache namespace.

Enforcing Strict Issuer, Audience, and Organization Claim Binding

Hard token isolation starts at the API gateway and repeats inside every backend service. Every incoming Bearer token must pass strict asymmetric verification (RS256 or ES256 against cached JWKS keys, explicitly disallowing none and symmetric HS256 algorithms), followed by exact-string validation of the expected iss (Issuer URL—including custom tenant domain alignment), the exact aud (Resource Server identifier for that specific API), and non-empty org_id (and ou_id where department isolation applies).

If a route URL includes an organization identifier (for example, /v1/organizations/:orgId/reports), the middleware must assert exact equality between req.params.orgId and the verified JWT payload's org_id claim, returning 403 Forbidden on any mismatch. Even better, omit redundant tenant headers entirely from your API contract—resolving tenant context exclusively from the signed Bearer JWT eliminates an entire class of spoofing bugs.

  • Pin an explicit allowlist of asymmetric algorithms (RS256, ES256) and reject tokens with mismatched kid or untrusted jku/x5u headers.
  • Bind every resource API to a unique aud URI (such as https://billing-api.cloudpulse.io) so tokens minted for one backend cannot replay against another.
  • Require immutable org_id and optional ou_id claims inside every B2B access token, failing closed whenever either expected claim is absent.
  • Enforce short access token lifetimes (5 to 15 minutes) with rotating refresh tokens so revoked tenant memberships expire rapidly across distributed nodes.
typescript
import { createRemoteJWKSet, jwtVerify } from "jose";
import type { Request, Response, NextFunction } from "express";

const EXPECTED_ISSUER = "https://login.cloudpulse.io";
const EXPECTED_AUDIENCE = "https://billing-api.cloudpulse.io";
const JWKS = createRemoteJWKSet(new URL(`${EXPECTED_ISSUER}/.well-known/jwks.json`));

export async function requireIsolatedTenantToken(req: Request, res: Response, next: NextFunction) {
  const authHeader = req.headers.authorization;
  if (!authHeader?.startsWith("Bearer ")) {
    return res.status(401).json({ error: "missing_bearer_token" });
  }

  try {
    const { payload } = await jwtVerify(authHeader.slice(7), JWKS, {
      issuer: EXPECTED_ISSUER,
      audience: EXPECTED_AUDIENCE,
      algorithms: ["RS256", "ES256"]
    });

    const orgId = typeof payload.org_id === "string" ? payload.org_id : null;
    const ouId = typeof payload.ou_id === "string" ? payload.ou_id : null;
    if (!orgId) {
      return res.status(403).json({ error: "missing_organization_context" });
    }

    // Reject confused-deputy route tampering if URL orgId != cryptographically signed org_id
    if (req.params.orgId && req.params.orgId !== orgId) {
      return res.status(403).json({ error: "cross_tenant_token_mismatch" });
    }

    req.authContext = { sub: String(payload.sub), orgId, ouId, roles: (payload.roles as string[]) ?? [] };
    return next();
  } catch {
    return res.status(401).json({ error: "invalid_or_expired_token" });
  }
}

Defense in Depth: Binding Verified JWT Claims to PostgreSQL Row-Level Security

Application-layer WHERE clauses are fragile because a single junior PR or raw reporting query that omits AND org_id = $1 exposes the entire table. Mature multi-tenant SaaS architectures push tenant isolation all the way into the database engine using PostgreSQL Row-Level Security (RLS) combined with transaction-local session variables.

At the start of every request transaction, your database pool wrapper runs SET LOCAL app.current_org_id = $1 using the verified org_id extracted from the JWT (never from raw HTTP headers). PostgreSQL's RLS policies then enforce org_id = current_setting('app.current_org_id', true)::uuid automatically on every SELECT, INSERT, UPDATE, and DELETE—guaranteeing that even a buggy ORM join or forgotten filter returns zero cross-tenant records. Crucially, use SET LOCAL inside an explicit transaction rather than session-scoped SET so pooled connections (PgBouncer) never leak tenant context onto the next request.

  • Enable both ENABLE ROW LEVEL SECURITY and FORCE ROW LEVEL SECURITY on every multi-tenant table and run application queries under a non-superuser database role.
  • Always use transaction-scoped SET LOCAL app.current_org_id so connection pools reset cleanly on commit or rollback.
  • Fail closed with NULLIF(current_setting('app.current_org_id', true), '')::uuid so queries executed without an explicit tenant transaction return zero rows rather than all rows.
  • Extend the same isolation pattern to object storage prefixes (s3://bucket/{org_id}/...), search indexes, and Redis cache keys.
sql
-- Enforce strict multi-tenant isolation inside PostgreSQL
ALTER TABLE invoices ENABLE ROW LEVEL SECURITY;
ALTER TABLE invoices FORCE ROW LEVEL SECURITY;

CREATE POLICY tenant_isolation_invoices ON invoices
  USING (
    org_id = NULLIF(current_setting('app.current_org_id', true), '')::uuid
    AND (
      ou_id IS NULL
      OR NULLIF(current_setting('app.current_ou_id', true), '') IS NULL
      OR ou_id = NULLIF(current_setting('app.current_ou_id', true), '')::uuid
    )
  )
  WITH CHECK (
    org_id = NULLIF(current_setting('app.current_org_id', true), '')::uuid
  );

-- Per-request transaction bound strictly to verified JWT claims
BEGIN;
  SELECT set_config('app.current_org_id', '6c4a8f12-9b30-4e11-8d2a-112233445566', true);
  SELECT set_config('app.current_ou_id',  '9d8e7f6a-5b4c-3d2e-1f0a-998877665544', true);
  SELECT id, total_cents, status FROM invoices WHERE status = 'open';
COMMIT;

Preventing Identity Provider Cross-Pollination Across Tenants

Token isolation can also be undermined upstream before a JWT is ever minted. Suppose Customer A configures a self-service SAML IdP and deliberately asserts an email address belonging to Customer B's CEO ([email protected]). If your identity broker fails to enforce verified domain boundaries per Organization or allows Customer A's SAML connection to authenticate into Customer B's workspace, the attacker receives a legitimately signed JWT for the victim's account.

Preventing federation cross-pollination requires three interlocking invariants at the identity plane: bind every enterprise SAML and OIDC connection strictly to its owning Organization (assignToOrganizationOnly) or Organization Unit (assignToOrganizationUnitOnly), verify DNS ownership of every email domain allowed to authenticate via that connection, and never allow an IdP attached to Organization A to assert users outside Organization A's verified domain list.

  • Enforce strict domain allowlists on every enterprise IdP connection so a customer's SAML or OIDC provider can only mint sessions for its verified corporate domains.
  • Isolate Organization connections via assignToOrganizationOnly so one tenant's IdP cannot be triggered from another tenant's authorize request.
  • Include automated cross-tenant negative security tests in CI that deliberately replay Org A tokens against Org B endpoints and assert 403 responses.
  • Stream token-mismatch and cross-tenant denial events to your SIEM as high-severity intrusion alerts.
Architecture Pattern

Resolve tenant context exclusively from the signed Bearer JWT token claims or verified custom tenant domain URL—never require or trust a mutable X-Tenant-Id request header. Pair strict iss/aud/org_id verification at the API edge with transaction-local PostgreSQL Row-Level Security so isolation holds across both compute and data tiers.

How SSO.ID Enforces Cryptographic Multi-Tenant Token Isolation

SSO.ID v2 embeds strict tenant and organization isolation directly into token issuance, resolution, and federation scoping—eliminating custom tenant headers and preventing cross-tenant IdP cross-pollination by design.

  • ✓Automatic tenant context resolution from cryptographically signed Bearer JWT claims or verified custom tenant domain URLs, requiring zero custom tenant HTTP headers.
  • ✓Per-Organization and per-Organization-Unit token overrides (overrideTokens) injecting immutable org_id, ou_id, and application-scoped aud and role claims into RS256/ES256 JWTs.
  • ✓Strict connection isolation flags (assignToOrganizationOnly and assignToOrganizationUnitOnly) keeping every customer IdP locked inside its contractual tenant boundary.
  • ✓Dedicated per-application JWKS endpoints (/.well-known/openid-configuration?appId={id}) and configurable short-lived Access Token TTLs with Refresh Token Rotation.

Frequently Asked Questions

Why is trusting an X-Tenant-Id HTTP header dangerous even when the user has a valid JWT?

An HTTP header is attacker-controlled input. If your JWT does not cryptographically bind the user's active org_id—or if your middleware fails to verify that the header matches the signed org_id claim—a user authenticated into Tenant A can swap the header to Tenant B and read unauthorized data.

Do we still need PostgreSQL Row-Level Security if our API middleware validates org_id on every request?

Yes. Middleware validates who the caller is, while RLS enforces tenant isolation at the storage engine boundary. If an engineer writes a new endpoint, background report, or GraphQL resolver and misses a single WHERE org_id filter, RLS prevents a cross-tenant data breach.

Should every B2B customer get a completely separate OIDC issuer URL?

Most multi-tenant SaaS platforms share one branded issuer (such as https://login.yourapp.com) and isolate B2B customers cryptographically via immutable org_id and ou_id claims plus strict aud values. Separate per-customer issuers are typically reserved for white-label OEMs running distinct custom domains.

Topics: #Token Isolation #Multi-Tenant Security #JWT Validation #Row-Level Security