Tenant Membership and the Sign-In Tenant Claim
Derived page. The behaviour described here is specified by the
tenant-directorycapability underopenspec/specs/. That specification is the source; this page explains and illustrates it. Where the two disagree, the specification is right and this page is a bug.
Stratara.Identity.EntityFrameworkCore owns the identity-directory plane: which tenants a user
belongs to, and which tenant-scoped roles the user holds in each. Stratara.Identity.AspNetCore
bridges that plane into the sign-in path, emitting the stratara:tenant_id claim that the
session-context middleware already reads — no middleware change, no new session shape.
The user↔tenant relationship is many-to-many, with roles scoped per membership. A single-tenant application is simply the degenerate case of one membership per user.
The two role levels
A TenantMembership(UserId, TenantId, Roles, Status) carries role names that apply only inside
its TenantId. Global platform roles — platform-administrator, developer — stay in ASP.NET
Identity's role store. The two levels are independent, and authorization components consult both.
MembershipStatus.Active grants access; MembershipStatus.Pending models an invitation that has
been issued but not accepted — the row exists so it can be listed and accepted transactionally,
but it confers no access anywhere in the stack.
// Alice administers Acme and merely reads at Globex — two memberships, two role sets.
await memberships.SetMembershipAsync(new TenantMembership(alice, acme, ["TenantAdmin"]));
await memberships.SetMembershipAsync(new TenantMembership(alice, globex, ["Viewer"]));
await memberships.SetMembershipAsync(new TenantMembership(bob, acme, [], MembershipStatus.Pending));
Hosting the directory tables
The tables (tenant_membership, active_tenant) live in a DbContext you own. Fold them into an
existing context — typically your ASP.NET Identity context, so everything shares one migration
lineage — by calling ApplyIdentityDirectoryModel() in OnModelCreating. Or derive a standalone
context from IdentityDirectoryDbContext<TContext>, which applies the model for you:
public sealed class DirectoryDbContext(DbContextOptions<DirectoryDbContext> options)
: IdentityDirectoryDbContext<DirectoryDbContext>(options);
builder.Services.AddTenantMembershipStore<DirectoryDbContext>(); // ITenantMembershipStore, scoped
Several hosts sharing one identity? Hosting the tables in your own context gives each host a migration lineage of its own, and two lineages cannot share tables. Use the shared identity store instead: it holds the accounts and the directory and ships their migrations.
One context for the request, or one per operation
That registration — and its siblings AddApiKeyStore<TContext>() and AddSettingStore<TContext>() —
gives every directory store in a request the same context instance. Two things follow, and both
are easier to meet head-on than to meet as a bug:
- A database context serves one operation at a time. Directory work issued concurrently inside one request — two role checks started together, a lookup racing a page load — fails on whichever arrives second, and it fails at the call site that lost the race rather than the one that introduced the concurrency.
- The stores commit their own writes. On a shared context, that commit also commits whatever you have left unsaved on it.
If either matters to you, register the stores against a context factory instead:
// configure the factory with the same provider options as your AddDbContext call
builder.Services.AddDbContextFactory<DirectoryDbContext>(options => { /* … */ });
builder.Services
.AddTenantMembershipStoreFromContextFactory<DirectoryDbContext>()
.AddApiKeyStoreFromContextFactory<DirectoryDbContext>()
.AddSettingStoreFromContextFactory<DirectoryDbContext>();
Each operation then takes a fresh context and disposes it, so operations do not contend and a store's commit reaches only its own rows. In exchange, a store write no longer takes part in a transaction you opened on your own scoped context — that is the whole of the trade, and it is why the shared registration remains the default rather than being quietly replaced.
Keep the factory's options aligned with your scoped registration: interceptors, query filters and conventions are configured per registration, not per context type. Calling both registrations for the same store leaves whichever ran first in place; they do not compose.
Working with the store
ITenantMembershipStore is deliberately relational-shaped — sign-in needs read-your-write
consistency. Both directions are first-class: GetMembershipsAsync answers "which tenants may this
user access", GetMembersAsync answers "who belongs to this tenant". SetMembershipAsync upserts
on (UserId, TenantId), replacing the role set and status.
var mine = await memberships.GetMembershipsAsync(alice); // forward lookup, any status
var staff = await memberships.GetMembersAsync(acme); // reverse lookup
var one = await memberships.GetMembershipAsync(alice, acme); // null when not a member
await memberships.SetActiveTenantAsync(alice, globex); // tenant switch
var active = await memberships.GetActiveTenantAsync(alice); // null when never selected
await memberships.RemoveMembershipAsync(alice, globex); // revoke one tenant's access
await memberships.RemoveAllMembershipsAsync(alice); // user-erasure sweep (GDPR Art. 17)
await memberships.RemoveAllMembersAsync(globex); // tenant-teardown sweep
SetActiveTenantAsync is membership-guarded: selecting a tenant the user holds no Active
membership in throws InvalidOperationException rather than persisting an unusable selection.
Changing single roles
To give or take one role, do not read the membership and write it back: two such changes that
overlap read the same role set, and the later write silently undoes the earlier one.
AddRolesAsync and RemoveRolesAsync change only the roles they name, leave the other roles and the
status as they are, and return the membership as it stands afterwards — null when the user has no
membership in the tenant, because neither creates one.
await memberships.AddRolesAsync(alice, acme, ["Billing"]); // alice keeps TenantAdmin
await memberships.RemoveRolesAsync(alice, acme, ["Billing"]); // Billing goes, TenantAdmin stays
On the framework's stores two role changes to the same membership that overlap both take effect,
whichever finishes first — also when two hosts sharing one identity store make them. A store that
keeps losing to concurrent writers fails with InvalidOperationException rather than drop the change.
Neither operation changes the database schema, so a context that hosts the directory tables needs no
migration for them.
SetMembershipAsync stays a whole replace: a whole write and a role change that run at the same time
do not protect each other. A membership store you implemented yourself gets both operations without a
code change, as a read followed by a whole write, and with that no protection against a concurrent
writer — override them where that matters, and forward them from a decorator to the store it wraps,
or the decorator quietly falls back to that unprotected form. TenantMembership.WithRolesAdded and WithRolesRemoved
compute the changed role set for such an override.
Ending a membership without forgetting it
A membership has three states. Active confers its roles. Pending is an invitation not yet
accepted. Former is a member who has left: the row stays, so the tenant still knows the person
belonged to it, and it confers nothing — no role, no permission, no cross-tenant access, never the
tenant at sign-in, never a selection. Writing a status other than Active over a selected
membership clears the selection, exactly as removing it does.
// alice leaves acme: she keeps her history there, and loses every right in it
await memberships.SetMembershipAsync(new TenantMembership(alice, acme, [], MembershipStatus.Former));
GetMembersAsync and GetMembershipsAsync return every status, so a member list filters for the
ones it means. A former membership is kept until the user's or the tenant's erasure removes it with
every other membership. The person's name belongs to their own data, not to the tenant: after the
person's erasure the tenant still sees a former member, without a name.
If your membership changes are event-sourced, keep emitting your events and update the store from a
projection or saga instead of calling SetMembershipAsync inline.
The sign-in tenant claim
All three bridge modes resolve the same way — persisted active-tenant selection → the user's only active membership, where they have exactly one → no claim at all. They differ in when the lookup runs, and in whether the claim is checked afterwards:
| Mode | Behavior |
|---|---|
AddMembershipTenantClaim<TUser>() — decorates IUserClaimsPrincipalFactory<TUser> |
Stamps the claim at issuance, into cookies and Identity bearer tokens alike. No per-request lookup; a tenant switch — and an ended membership — reaches a signed-in user on the next sign-in refresh. |
AddMembershipTenantClaimsTransformation() — registers an IClaimsTransformation |
Resolves live on every request, so a tenant switch applies immediately without re-issuing the sign-in. Costs one store lookup per request — cache behind the store when it gets hot. |
AddCheckedMembershipTenantClaim<TUser>() — the factory decorator, a checking IClaimsTransformation and a cookie-refresh hook |
Stamps the claim at issuance and keeps it across a cookie refresh; on every request it checks that the membership in the carried tenant is still Active and drops the claim where it is not. The tenant changes only when the host re-issues the sign-in. One store lookup per request. |
One selection per account. active_tenant holds one row per user, across everything that shares
the identity store. With live resolution, a user who switches tenant in one application moves every
open session they have — in every application on the same store. Where several applications share
one identity store, use AddCheckedMembershipTenantClaim<TUser>(). To switch a user there, select
the tenant and re-issue the sign-in:
await memberships.SetActiveTenantAsync(userId, globex); // refuses a tenant without an active membership
await signInManager.RefreshSignInAsync(user); // the re-issued principal carries globex
A re-issue for any other reason resolves from the selection as well, so in this mode a re-issue is
the switch. A person removed from the tenant — Former, Pending or deleted — loses the claim on
their next request, without waiting for a refresh, and is not moved to another of their tenants: the
request resolves to the reserved default tenant like any request without a claim, and every role-
or permission-guarded request is refused. The cookie refresh is what keeps the tenant; a
bearer-token refresh re-creates the principal through the claims factory, which resolves from the
selection. Only principals ASP.NET Identity issued are checked: an API key, or a token your application
mints, keeps the tenant it carries. That applies to a key that authenticates at all: a personal access
token whose user's membership in the key's tenant is not active fails validation and yields no principal,
so a removed person's token gets a 401 rather than a request in the default tenant (see
API Keys and Personal Access Tokens). The checked mode cannot be combined with live resolution — registering
both throws — and a host that registers a claims transformation of its own beside it is refused at start,
because ASP.NET Core runs only one and the check would stop silently.
builder.Services
.AddTenantMembershipStore<DirectoryDbContext>()
.AddMembershipTenantClaim<ApplicationUser>(); // after your identity + store registration
Stamping and live resolution compose: a principal that already carries stratara:tenant_id — stamped at issuance, by an
earlier transformation run, or by your own machine-JWT minting — passes through untouched.
The framework will not choose a tenant for a user
A user with several active memberships and no valid selection gets no claim. Not the first by some order, not the oldest, not a guess. If you expected a sensible default, this is the paragraph that says there isn't one.
The reason is asymmetry in how the two failures behave. A missing claim fails closed and visibly: the request is refused and somebody notices. A wrong claim fails invisibly — the work lands in the wrong tenant, it succeeds, and nothing reports it. There is no basis in the directory for picking between a user's tenants, so the framework does not pretend there is one.
What this means for your host: a user who belongs to several tenants must choose before they can
act. Call SetActiveTenantAsync once they have, and the selection persists.
await memberships.SetActiveTenantAsync(alice, acme); // now she has a claim
Until then their requests carry no tenant, so any route that needs one will refuse them. Give them a route that does not — a tenant picker — or they have nowhere to go.
Telling the two no-claim cases apart
"No claim" covers two situations that call for opposite responses, and they look identical from the
principal. GetMembershipsAsync distinguishes them, and the count is the whole distinction:
var active = (await memberships.GetMembershipsAsync(alice))
.Where(m => m.Status == MembershipStatus.Active)
.ToList();
var next = active.Count switch
{
0 => "no access at all — a dead end, say so",
1 => "unreachable: one active membership always resolves",
_ => "several tenants, none chosen — prompt for one",
};
Showing a multi-tenant user "you have no access" is the mistake this section exists to prevent. They have plenty; they have not said which.
Why fail-closed resolution matters
A user with no active membership gets no claim — not a default tenant, not an empty Guid. That keeps every downstream consumer on its fail-closed path instead of silently resolving to somebody else's data. The same rule holds for hosts whose Identity keys are not Guid-parseable: no claim is stamped, no exception is thrown, so verify your key shape before adopting the bridge.
Membership-backed authorization
MembershipAuthorizationProvider is the framework's first shipped IAuthorizationProvider: a
[RequireRole] check passes when the session's actor holds that role as a membership role in
the session's data-owner tenant. The <TUser> variant additionally falls back to global ASP.NET
Identity roles on a membership miss — so tenant-scoped checks cost no Identity round trip.
// Membership roles only — the provider behind the authorizing mediator:
builder.Services.AddAuthorizingMediator<MembershipAuthorizationProvider>();
// Or membership roles ∪ global Identity roles, for components that resolve
// IAuthorizationProvider directly (the authorizing outbox dispatcher):
builder.Services.AddMembershipAuthorization<ApplicationUser>();
For strict tenant isolation, back the deny-all default with stored facts. A cross-tenant operation then passes when the actor has an active membership in the data-owner tenant or holds a configured platform role — the operator-impersonation path:
builder.Services
.AddStrataraTenantIsolation(o => o.Mode = TenantIsolationMode.Strict)
.AddMembershipCrossTenantAuthorizer(o => o.CrossTenantRoles.Add("PlatformAdmin"));
Every one of these is fail-closed: no ambient session, no membership, a Pending membership, or an
unknown role all evaluate to false.
Erasing a subject
Removing memberships is one plane of an erasure, not the whole of it. ISubjectEraser composes the
four sweeps the framework owns and runs them in an order that leaves nothing unreachable before it
has been removed:
services.AddStrataraErasure(); // the four stores it sweeps are registered separately
var report = await eraser.EraseUserAsync(alice);
// report.Planes: ApiKeys -> Settings -> KeyMaterial -> Memberships
Why that order. API keys go first, so nothing can act on the subject's behalf while the erasure runs. Key material comes after the settings, because shredding it makes them unreadable. Sweep it first and a later failure leaves rows nobody can identify. Memberships go last, because they are what tells the eraser which tenants the subject has settings and keys in. An erasure run again after a failure therefore still finds them.
Which keys it shreds. A key is named by its sensitivity level, its tenant and its user together, and the level decides whose erasure a value dies with. Every level is the tenant's. A tenant's erasure therefore shreds every key naming the tenant, alone or together with each of its members, at the user, tenant and confidential levels alike. That includes the key a user-level value is encrypted under when it is written with no user, which is the case for an event appended from an ordinary request. Only the user level is the user's. A user's erasure shreds the user-level keys naming the user, alone or together with each tenant it belongs to. A tenant-level or confidential value written for that user stays readable until its tenant is erased. Both erasures also ask the key store for every key naming the subject, which reaches a key shared with someone who is no longer in the directory.
A person's own data. Data recorded for an owner that names a user alone (EventSubject.ForUser,
see encryption setup) is keyed to that user
and no tenant of theirs. The user's erasure always shreds it — the directory names that key itself,
so it does not depend on the key store being able to list — and no tenant's erasure reaches it.
An erased subject is given no new key. Before it sweeps any plane, the erasure marks the
subject erased in the key store (IKeyStore.MarkSubjectErasedAsync). From then on the store refuses
every key the erasure covers, whether or not it ever existed, with a KeyScopeErasedException that
names the scope. A job, a request in flight or another process that encrypts for the subject after
the erasure therefore fails instead of writing data under a fresh key that nothing would shred. An
encryption that races the erasure and wins creates its key before the mark, and the listing shreds
it with the rest. Map the exception to whatever your API answers for data that is gone. The mark is
permanent: an erased subject's id cannot be used for encrypted data again.
If a plane fails, the erasure stops there and raises ErasureIncompleteException, naming the
plane and listing what was already swept. It does not continue, precisely so that a failed settings
sweep never leads to the key being shredded anyway. Run the erasure again once the cause is fixed.
Every sweep is safe to repeat, and the planes already swept simply find nothing left.
What it does not cover, and this matters as much as what it does:
- Read models your own projections built. The framework does not know they exist. They are yours to sweep.
- Event-stream data not protected by a scoped key. Removing a key shreds what that key encrypted; anything written in the clear is still there.
- The command audit log and the outbox. Both carry a session context naming the subject, and both are deliberately left alone — the audit log is the evidence that the erasure happened, and whether to retain it is a decision only you can take for your jurisdiction.
- System-wide
Confidentialkey material. A confidential value written with an empty tenant uses one key for everybody, and no erasure shreds it. Written for a tenant, it is shredded with the tenant. - Keys a custom key store cannot list. The framework's key stores list every key they hold. A key
store of your own that does not implement
IKeyStore.ListScopesAsyncleaves an erasure with the keys the directory names: a key shared with a former member, or with an operator acting in the tenant from outside it, is then not found. - Keys a custom key store cannot refuse. A key store of your own that does not implement
IKeyStore.MarkSubjectErasedAsyncstill has its keys shredded, but gives the subject a new key when something encrypts for it afterwards. The erasure logs a warning when that happens. - Snapshots written before 4.4.0, on a user's erasure. They record no user and stay under their tenant alone. The 4.4.0 changelog gives the statement that removes them on upgrading.
Tenants themselves are event-sourced
The tenant a membership points at is not a row somebody inserts. Stratara.Domain ships the Tenant
aggregate (Stratara.Domain.Multitenancy), and its whole lifecycle is recorded as events, each a
distinct fact in the tenant's stream:
| Lifecycle step | Event |
|---|---|
| Created | TenantCreated |
| Renamed | TenantRenamed |
| Activated | TenantActivated |
| Deactivated | TenantDeactivated |
| Assigned to a customer | TenantAssignedToCustomer |
| Default locale changed | TenantDefaultLocaleChanged |
| Deleted | TenantDeleted |
Stratara.Projections ships the read model: TenantProjection keeps a TenantView per tenant up to
date from those events, and ITenantRepository reads it. It also handles CustomerTenantsDeleted,
which removes every tenant of a customer from the read model in one go. That event goes on your own
customer aggregate's stream, and the aggregate needs no Apply for it: a rebuild skips an event the
aggregate has no Apply for without reading it. A host that never registers the type logs a warning
at the first skip; AddTrustedType<CustomerTenantsDeleted>() there acknowledges it. The
snapshot guide has the details.
Your own projections that remove a deleted tenant's rows can declare IForgetsDeletedTenants, so a
fact of the tenant that arrives after its deletion is passed over instead of failing them or adding a
row nothing removes — see
Write a Projection.
Register the aggregate and the projection like your own:
builder.Services
.AddAggregatesFromAssemblyContaining<Tenant>()
.AddProjectionsFromAssemblyContaining<IStrataraProjectionsMarker>();
A new tenant belongs to itself. TenantCreated declares the tenant it creates as the event's
owning tenant. A platform operator whose session belongs to a different tenant can create a tenant,
and the recorded owner is still the new tenant, not the operator's.
The read model is forgiving about delivery, because delivery is at least once:
- A lifecycle event for a tenant the read model does not hold, such as a rename that arrives before the creation was applied, is ignored rather than failing the bundle.
- A
TenantCreateddelivered twice writes nothing the second time. - A deletion that finds its row already removed by another writer absorbs the concurrency failure rather than failing the bundle.
See also
- The runnable
Stratara.Sample.IdentityDirectorysample wires membership, permissions, and scoped settings end to end against SQLite;Stratara.Sample.Identitycovers the sign-in side. - Permission-Based Authorization — the fine-grained layer these membership roles grant through.
- Authorization Decorators — the
[RequireRole]/permission enforcement that membership roles feed. - Enforce Tenant Isolation — the tenant guard the
stratara:tenant_idclaim resolves for.