Multi-Tenant Auth

Designing Multi-Tenant Authentication for B2B SaaS

How to model organizations, users, roles, and isolation when one user can belong to many tenants — and the architectural decisions that are painful to reverse later.

Emilian GheoneaJune 2, 20268 min read

Consumer apps have a simple identity model: one person, one account. B2B SaaS does not. A single user might belong to three different companies, hold a different role in each, and expect to switch between them without logging out. Getting this model right early matters, because the data shape you choose for tenancy is one of the hardest things to change once you have customers.

This article covers the core decisions: how to isolate tenant data, how to model the user-to-tenant relationship, and how to handle invitations, roles, and tenant switching.

What "multi-tenant" actually means

A tenant is a customer organization. Multi-tenancy means many tenants share the same application — and possibly the same database — while remaining logically isolated from one another. The defining requirement is simple to state and easy to get wrong: one tenant must never see another tenant's data.

Three isolation models

1. Separate database per tenant

Each tenant gets its own database. Strongest isolation, easiest compliance story, but operationally heavy — migrations, backups, and connection pooling multiply by the number of tenants. Usually reserved for enterprise deals with strict data-residency requirements.

2. Shared database, separate schema

One database, one schema per tenant. A middle ground, but most ORMs and migration tools aren't built to manage hundreds of schemas gracefully.

3. Shared database, shared schema (row-level)

Every table carries a tenant_id column, and every query filters on it. This is what the vast majority of SaaS products use. It scales well and keeps operations simple — but it puts the entire isolation guarantee on your query layer.

For the shared-schema model, defense in depth is essential:

  • Enforce tenant_id filtering in a single data-access layer, not scattered across the codebase.
  • Use database row-level security (RLS) as a backstop so a forgotten WHERE clause can't leak data.
  • Never accept tenant_id from the client as the source of truth — derive it from the authenticated session.

Postgres RLS makes the database itself refuse to return another tenant's rows, so a single missing WHERE tenant_id = … becomes a non-event rather than a breach:

ALTER TABLE documents ENABLE ROW LEVEL SECURITY;

CREATE POLICY tenant_isolation ON documents
  USING (tenant_id = current_setting('app.current_tenant')::uuid);

-- Your data layer sets the tenant once per transaction, from the session:
SET LOCAL app.current_tenant = '…tenant-uuid-from-session…';

Because the tenant is set from the authenticated session (never a request parameter), even an SQL-injection or a logic bug in one endpoint can't read across the boundary.

Modeling users and tenants

The mistake that's expensive to undo is binding a user identity to a single tenant — for example, putting tenant_id directly on the users table. The moment a customer wants to invite someone who already has an account elsewhere, that model breaks.

Model identity and membership as separate concepts:

users
  id, email (globally unique), password_hash, ...

organizations          (tenants)
  id, name, ...

memberships            (the join — one row per user-in-org)
  user_id, organization_id, role, status

A user exists once globally. A membership connects that user to an organization with a specific role. One user, many memberships, many tenants. This single decision unlocks invitations, tenant switching, and per-tenant roles cleanly.

Rendering diagram…

The join table is the entire trick: MEMBERSHIPS is a many-to-many bridge, so the same USERS row can appear in any number of organizations, each with its own role. Contrast that with putting organization_id on USERS — a one-to-many that silently forbids a person from ever belonging to two tenants.

Where tenant context lives

Once a user can belong to several tenants, every request needs to know which tenant it's acting in. Common approaches:

  • Subdomain — acme.yourapp.com maps to the Acme tenant. Clean URLs, good isolation, but more DNS and certificate plumbing.
  • Path prefix — /orgs/acme/.... Simple, no DNS work.
  • Active tenant in the session/token — the current tenant is stored in the session or encoded as a claim in the access token.

Whatever you choose, the active tenant must come from a trusted source. If you encode it in a JWT, the token is signed, so it can't be tampered with — but you still must verify on each request that the user actually has a membership in that tenant:

{
  "sub": "user_123",
  "org": "org_acme",
  "role": "admin",
  "iat": 1720000000,
  "exp": 1720000900
}

A signed org claim tells you which tenant the user selected; it does not by itself prove they're allowed there. Signature integrity and membership authorization are two separate checks — the token being untampered is necessary but not sufficient. (The broader mechanics of signing, alg pinning, and key rotation are in JWT Explained for Developers, and how these tokens should live in a session in Session Management Best Practices.)

Roles and authorization

Roles live on the membership, not the user — the same person can be an owner of one org and a viewer in another. Start with a small, well-defined set (owner, admin, member, viewer) and grow only when real requirements demand it. For more complex products, layer permission-based checks on top of roles so you can grant fine-grained capabilities without inventing a new role every time.

Authorization checks should always answer two questions together: Is this user a member of this tenant? and Does their role in this tenant permit this action?

Invitations

Invitations are the main way tenants grow, and they have sharp edges:

  • The invited email may or may not already have an account. Your flow must handle both — accept-and-sign-up versus accept-and-join.
  • Invitation tokens should be single-use, expiring, and scoped to a specific organization and role.
  • Verify that the email accepting the invite matches the invited email, or you create an account-takeover vector.
  • Make it possible to revoke a pending invite.

Tenant switching

Because a user can belong to many tenants, the UI needs a switcher, and the backend needs to rotate the active-tenant context safely. When a user switches:

  1. Confirm they hold a valid membership in the target tenant.
  2. Issue a new session or access token scoped to the new tenant.
  3. Invalidate any cached authorization decisions tied to the previous tenant.

Never let the active tenant be changed by simply editing a client-side value — it must be re-validated server-side every time.

The email uniqueness question

email globally unique on the users table looks obviously correct, and it is the right default — but it has consequences worth deciding deliberately rather than discovering.

The consequence is that an email address is a single identity across every tenant on your platform. If Dana signs up personally with [email protected], and later her employer invites [email protected] to their organization, she joins with the same account, the same password, and the same session. That is usually what everyone wants. It also means her employer's admin can see that this person existed on your platform before the invitation, and it means Dana's personal account and her work account are not separable. For most B2B products this is fine and even desirable. For products where tenants must not be able to infer anything about each other's members, it is a leak.

The alternative — email unique per tenant, so the same address can be two unrelated accounts — sounds like a small change and is not. It breaks password reset ("which account?"), it breaks magic links (the link has to encode a tenant), it makes SSO ambiguous, and it means a user with three memberships has three passwords. Almost everyone who builds this ends up regretting it.

The middle path that actually works: keep email globally unique, but make membership visibility the thing that is scoped. An admin can see that an invitation to an address was accepted; they cannot enumerate what other organizations that user belongs to. The user's profile is global; their presence in your tenant is all your tenant gets to know.

One related trap: case and normalization. [email protected] and [email protected] are the same mailbox in practice. Normalize to lowercase on write, store the normalized form in the unique index, and preserve the original only for display. Teams that skip this discover it when a user creates a duplicate account and then cannot reset the password on either. Whether to also strip Gmail-style dots and +tags is a judgment call — it prevents one person creating unlimited accounts, but it also merges addresses their owner considers distinct. Decide once, apply everywhere, and never change it retroactively.

Ownership, the last admin, and org deletion

Every multi-tenant product eventually hits the same three support tickets, and all three are data-model problems dressed as support problems.

The orphaned organization. The sole owner leaves the company, and their account is deactivated by their IdP. Nobody can add members, change billing, or delete the org. Prevent it structurally: refuse to remove or downgrade the last owner of an organization, and surface a warning when an org has exactly one. An org with a single owner is a latent support ticket.

The self-lockout. An admin edits their own membership and removes the permission that let them edit memberships. The check is simple — a user cannot reduce their own role — and it is skipped in roughly every first implementation.

Deletion semantics. When an organization is deleted, what happens to a user whose only membership was in that org? They now have an account attached to nothing. If you hard-delete the user, you have destroyed an identity that might be re-invited tomorrow. If you leave them, you have accounts that can log in and see an empty state. The workable answer is soft-deletion with a retention window on the organization, users left intact, and a first-run experience that handles "you belong to no organizations" as a real state with a create-or-join prompt rather than an error page.

SSO and enterprise identity

Larger customers will eventually ask for SAML or OIDC single sign-on, often with their own identity provider and just-in-time user provisioning. Design for this even before you build it: keep identity (the user) separate from authentication method (password, OAuth, SSO), so adding enterprise SSO later is a new login path — not a rewrite of your user model.

A summary of the decisions that are hard to reverse

  • Global user identity, separate membership records. Don't tie a user to one tenant.
  • A single, enforced data-access layer for tenant_id filtering, with RLS as a backstop.
  • Roles on memberships, not users.
  • Active tenant derived from a trusted, signed source and re-validated per request.
  • Identity decoupled from authentication method so SSO is additive.

Multi-tenant auth is mostly modeling, not cryptography. Spend the time on the data model up front — it's the part you'll regret rushing.

EmbedAuth's own dashboard is built in this shape: each account is an organization, team members hold per-organization roles, and invitations handle both the accept-and-join and the accept-and-sign-up branches. For your application's end users, EmbedAuth supplies the identity — one app per tenant, a verified token per user — and leaves roles to you. If enterprise SSO is on your roadmap, the identity-vs-method separation above is exactly what makes SAML and OIDC additive rather than a rewrite.

Written by

Emilian Gheonea

Senior Blockchain & Full-Stack Software Engineer. I build EmbedAuth — an embeddable authentication platform for SaaS — and write about the auth problems most teams hit too late.