Skip to content

Multi-Tenancy ​

GrydAuth provides comprehensive multi-tenancy support for SaaS applications, including tenant isolation, federation, and cross-tenant access patterns.

Multi-Tenancy Model ​

All tenants share one database; every tenant-owned row carries its TenantId, and the framework filters reads and guards writes by it. There is no database-per-tenant or schema-per-tenant mode (ADR 0011, D24): if one is ever needed, it comes back with its own design and ADR.

Quick Setup ​

1. Enable Multi-Tenancy ​

Multi-tenancy is always on and the tenant of a request is always the session's tenant_id claim (ADR 0011, D16 and D18): there is nothing to enable and no source to choose. The MultiTenancy section at the root of appsettings.json (a Core feature, not GrydAuth-specific) holds only product semantics:

json
{
  "MultiTenancy": {
    "OptionalTenantVisibilityMode": "CurrentTenantOrGlobal",
    "MaxGroupScopeTenants": 200
  }
}

2. Configure GrydAuth ​

csharp
// Program.cs
builder.Services.AddGrydAuth(builder.Configuration);

// Middleware pipeline (order matters!)
app.UseAuthentication();
app.UseGrydAuth();  // Validates the token and sets the request's tenant from its tenant_id claim
app.UseAuthorization();

3. Apply Tenant Filter to Entities ​

csharp
using Gryd.Domain.Abstractions;

public class Product : BaseEntity<Guid>, IRequireTenant
{
    public string Name { get; set; } = string.Empty;
    public decimal Price { get; set; }
    
    // Multi-tenancy
    public Guid TenantId { get; set; }
}

Tenant Resolution Strategies ​

GrydAuth primarily uses Claim-Based Resolution from JWT tokens. The tenant_id claim is automatically extracted from the authenticated token.

Header-Based Resolution (X-App-Id) ​

For application-specific routing, GrydAuth uses the X-App-Id header:

http
POST /api/v1/auth/login
X-App-Id: my-frontend-app
Content-Type: application/json

{
  "email": "user@example.com",
  "password": "Password123!"
}

Claim-Based Resolution (Primary) ​

The tenant_id claim of the validated session is the request's tenant, and nothing else is: UseGrydAuth() ends with the Core session middleware (UseGrydTenantSession()), placed after the token processor has checked the user's link to that tenant. A tenant named in a header (X-Tenant-ID), a query string (?tenantId=) or a route value is never read. A global (selector) token and a platform session run with no tenant; to act in another tenant, switch tenant. A host without GrydAuth registers the same pieces with services.AddGrydTenancy() and app.UseGrydTenantSession() after app.UseAuthentication().

json
{
  "sub": "user-id",
  "tenant_id": "550e8400-e29b-41d4-a716-446655440000",
  "permissions": ["read:products"]
}

Smart Federation ​

GrydAuth implements Smart Federation for multi-tenant authentication:

  1. Login - Returns Global Token (if user has multiple tenants)
  2. Switch Tenant - Exchange Global Token for Tenant Token
  3. Auto-Switch - If user has only one tenant, automatically issues Tenant Token
http
POST /api/v1/auth/switch-tenant
Authorization: Bearer {global-or-tenant-token}
Content-Type: application/json

{
  "tenantId": "550e8400-e29b-41d4-a716-446655440002"
}

Tenant Management ​

Tenant Hierarchy (Holding / Group) ​

GrydAuth now supports a 2-level tenant hierarchy for holding structures:

  • Group tenant: root holding (Type = Group, ParentTenantId = null)
  • Company tenant: standalone or child company (Type = Company)
  • Child company: ParentTenantId points to a Group tenant

Domain Fields ​

Tenant now includes:

  • Type (Company or Group)
  • ParentTenantId (Guid?)
  • ParentTenant / ChildTenants navigation
  • helper flags: IsGroupTenant, IsCompanyTenant, IsChildTenant, IsRootTenant

Hierarchy API Endpoints ​

The TenantsController exposes hierarchy management endpoints:

  • GET /api/v{version}/tenants/{id}/children
    Returns direct children of a group tenant.
  • GET /api/v{version}/tenants/{id}/hierarchy
    Returns tenant + direct children.
  • POST /api/v{version}/tenants/{id}/children
    Creates a child tenant under the group (manage:child-tenants).
  • PUT /api/v{version}/tenants/{id}/group
    Assigns an existing tenant to a group (manage:child-tenants).
  • DELETE /api/v{version}/tenants/{id}/group
    Removes tenant from group (manage:child-tenants).

Tenant List Filters (GET /api/v1/tenants) ​

The tenant listing endpoint now supports hierarchy-aware server-side filters:

  • type (company or group)
  • hierarchyScope (all, root, children)
  • parentTenantId (Guid)

Supported behavior:

  • hierarchyScope=all (default) returns tenants without additional hierarchy restriction.
  • hierarchyScope=root returns only root tenants (ParentTenantId = null), including groups and standalone companies.
  • hierarchyScope=children&parentTenantId={groupId} returns only direct child companies of the informed group.

Validation rule:

  • parentTenantId is only valid when hierarchyScope=children.
  • hierarchyScope=children requires parentTenantId.
  • Invalid combinations are rejected with 400 Bad Request (TENANT_FILTER_COMBINATION_INVALID).

Examples:

http
GET /api/v1/tenants?hierarchyScope=all
GET /api/v1/tenants?hierarchyScope=root
GET /api/v1/tenants?type=group
GET /api/v1/tenants?hierarchyScope=children&parentTenantId=550e8400-e29b-41d4-a716-446655440000

Tenant Token Group Claims ​

Every tenant token — login, switch-tenant, refresh and the post-MFA session — carries, when the tenant belongs to a group or is the group itself:

  • group_id
  • group_name

They are read from the database at each issue (a company moved to another group carries the new group from the next refresh on) and omitted for standalone tenants. They are topology, not entitlement: group-scoped reads are authorized against the database, never by these claims.

GroupAdmin ​

The GroupAdmin role carries the group-scoped READ entitlements. It no longer carries inherited switch access: since ADR 0007 (A8) assuming a tenant's identity requires an active UserTenant link, for everyone, and switch:any-group-tenant was removed.

Role template permissions (AuthorizationCatalogDefinitions.GroupAdminRolePermissions), granted to the role in every tenant by the bootstrap and by the seed — before ADR 0006 / US 2.2 the role was provisioned with none of them, which is why read:group-analytics gated nothing:

  • read:group-tenants
  • read:group-analytics — group aggregates (ADR 0006, G3)
  • read:group-data — group records owned by other tenants of the group (ADR 0006, G3)
  • manage:child-tenants

Both group-read permissions are evaluated in the group tenant, never in the tenant of the token (ADR 0006, G4).

Behavior:

  • switch-tenant into a child requires a UserTenant link in that child. Holding GroupAdmin in the parent group does not authorize it (ADR 0007, A8).
  • A new child is therefore reachable by nobody until someone is linked to it — creating a tenant no longer widens anyone's reach on its own.

Creating Tenants ​

http
POST /api/v1/tenants
Authorization: Bearer {super-admin-token}
Content-Type: application/json

{
  "name": "Acme Corporation",
  "identifier": "acme",
  "domain": "acme.yourapp.com",
  "settings": {
    "timezone": "America/New_York",
    "language": "en-US",
    "features": ["advanced-reports", "api-access"]
  }
}

Tenant Entity ​

csharp
public class Tenant : AggregateRoot<Guid>
{
    public string Name { get; private set; } = string.Empty;
    public string Identifier { get; private set; } = string.Empty;
    public string? Domain { get; private set; }
    public bool IsActive { get; private set; } = true;
    public DateTime CreatedAt { get; private set; }
    
    // Settings stored as JSON
    public TenantSettings Settings { get; private set; } = new();
    
    // Navigation
    public ICollection<UserTenant> UserTenants { get; private set; } = new List<UserTenant>();
}

User-Tenant Relationship ​

Assigning Users to Tenants ​

http
POST /api/v1/tenants/{tenantId}/users
Authorization: Bearer {admin-token}
Content-Type: application/json

{
  "userId": "550e8400-e29b-41d4-a716-446655440001",
  "roles": ["Manager", "User"]
}

User Belonging to Multiple Tenants ​

csharp
public class UserTenant : BaseEntity<Guid>
{
    public Guid UserId { get; set; }
    public User User { get; set; } = null!;
    
    public Guid TenantId { get; set; }
    public Tenant Tenant { get; set; } = null!;
    
    // Roles within this tenant
    public ICollection<Role> Roles { get; set; } = new List<Role>();
    
    public bool IsDefault { get; set; }
    public DateTime JoinedAt { get; set; }
}

Tenant Isolation ​

Isolation is fixed behaviour, not configuration (ADR 0011, D19–D20).

Reads fail closed ​

ApplyTenantQueryFilters puts a filter on every entity marked IRequireTenant or IOptionalTenant:

SessionIRequireTenantIOptionalTenant (CurrentTenantOrGlobal, the default)
Tenant Arows of Arows of A and global rows
No tenant (anonymous, global token, platform session, job)noneglobal rows only
csharp
public class AppDbContext : GrydAuthDbContext, ITenantQueryContext
{
    protected override void OnModelCreating(ModelBuilder modelBuilder)
    {
        base.OnModelCreating(modelBuilder);

        // Filters every IRequireTenant / IOptionalTenant entity by the tenant of the flow,
        // read at query time from the tenant snapshot (ADR 0011, D17).
        modelBuilder.ApplyTenantQueryFilters(this);
    }
}

Reading Across Tenants ​

A request never switches the filter off. A screen that consolidates a group or the whole platform declares its scope (?scope=group, ?scope=global) and the scope model decides the reach (ADR 0011). Outside requests — jobs, hosted services, provisioning — the single bypass is ITenantAmbient.BeginSystemScope(reason), recorded in the scope audit trail:

csharp
await using (ambient.BeginSystemScope("reports: nightly sweep across every tenant"))
{
    var everything = await _context.Products.ToListAsync();
}

A query that must read before any session exists (a lookup by domain, a sweep) may use IgnoreQueryFilters() only in the members listed in build/ignore-query-filters-exceptions.txt, and restates the tenant and soft-delete predicates itself.

Writes are guarded ​

TenantSaveChangesInterceptor is attached to every DbContext with a tenant entity, GrydAuth's included. For every marked entity it saves:

  1. A new IRequireTenant row without a tenant is stamped with the session's; with no session tenant it is refused. An IOptionalTenant row is never stamped.
  2. A change of TenantId is refused.
  3. A tenant session never writes a row owned by another tenant (a global row is not another tenant's). Under a global scope, or with the tenant filter bypassed by a system flow, the row keeps the tenant its code chose: the scope model already decided the reach.
  4. Nothing is written under a group scope.

Tenant Federation ​

Smart Federation ​

Users can belong to multiple tenants with different roles:

csharp
// User logs in and selects tenant
var loginResult = await _authService.LoginAsync(new LoginRequest
{
    Email = "user@example.com",
    Password = "password",
    TenantId = selectedTenantId // User selects which tenant to access
});

Switching Tenants ​

http
POST /api/v1/auth/switch-tenant
Authorization: Bearer {current-token}
Content-Type: application/json

{
  "tenantId": "550e8400-e29b-41d4-a716-446655440002"
}

Response:

json
{
  "isSuccess": true,
  "data": {
    "token": "eyJhbGciOiJSUzI1NiIs...",
    "expiresAt": "2026-01-29T14:00:00Z",
    "isGlobal": false,
    "tokenType": "Tenant",
    "currentTenant": {
      "id": "550e8400-e29b-41d4-a716-446655440002",
      "name": "Another Corp",
      "isDefault": false
    }
  }
}

Global Tokens ​

GrydAuth uses Global Tokens for multi-tenant authentication:

  • Global Token: 2 minutes TTL, scope tenant-selector-only
  • Tenant Token: 10 minutes TTL (max 15), full access within tenant

When a user with multiple tenants logs in without specifying a preferredTenantId:

  1. A Global Token is issued
  2. User must call POST /api/v1/auth/switch-tenant to select a tenant
  3. A full Tenant Token is returned

Tenant Context ​

Accessing Current Tenant ​

The tenant of the session is read through ITenantSession — never from a property of the request (ADR 0011, D23):

csharp
public class ProductService(ITenantSession session)
{
    public Product Create(CreateProductRequest request) =>
        new() { Name = request.Name, TenantId = session.RequiredTenantId() };
}

ITenantSession Properties ​

PropertyTypeDescription
TenantIdGuid?Tenant of the session (null in a platform session)
TenantNamestring?Its display name, when known
GroupId / GroupNameGuid? / string?The tenant's group, from the token — topology, not entitlement
ScopeTenantScopeThe scope the read runs under (the granted one, or the session tenant's)
SessionKindstringtenant or platform
SnapshotTenantSnapshotThe whole immutable context of the flow

The context is established by the session middleware that UseGrydAuth() adds, from the tenant_id claim of the validated token. Only entry points change it, through ITenantAmbient.Begin, and the handle restores the previous context when it is disposed.

Tenant-Specific Configuration ​

Per-Tenant Settings ​

csharp
public class TenantSettings
{
    public string Timezone { get; set; } = "UTC";
    public string Language { get; set; } = "en-US";
    public string Currency { get; set; } = "USD";
    public HashSet<string> EnabledFeatures { get; set; } = new();
    public Dictionary<string, object> CustomSettings { get; set; } = new();
}

// Usage
var tenant = await _tenantRepository.GetByIdAsync(tenantId);
var timezone = tenant.Settings.Timezone;

Feature Flags per Tenant ​

csharp
public class FeatureService(ITenantSession session, ITenantRepository tenants)
{
    public async Task<bool> IsFeatureEnabledAsync(string featureName)
    {
        var tenant = await tenants.GetByIdAsync(session.RequiredTenantId());
        return tenant?.Settings.EnabledFeatures.Contains(featureName) ?? false;
    }
}

// Usage in controller
if (await _featureService.IsFeatureEnabledAsync("advanced-reports"))
{
    return await GenerateAdvancedReportAsync();
}
else
{
    return BadRequest("This feature is not available for your tenant.");
}

Best Practices ​

  1. Always declare a marker - IRequireTenant or IOptionalTenant on every entity with a TenantId
  2. Test Tenant Isolation - Write tests to verify data isolation
  3. Declare Scope, Don't Bypass - Cross-tenant reads go through ?scope=; only jobs use the audited BeginSystemScope
  4. Tenant Comes From the Session - Only the tenant_id claim, never a header or query string
  5. Cache Tenant Data - Tenant resolution can be performance-critical
  6. Expect fail-closed reads - Without a tenant in session, tenant-owned rows are not returned

Released under the MIT License.