Authaz logoAuthaz
DocumentationAPI Reference
  • Get Started

    • Authaz
    • Core Concepts
    • Set up your app
    • Quickstart — cURL
  • Authentication

    • Authentication Settings
    • Signup
    • Invitations
    • Password Authentication
    • Multi-Factor Auth
    • Magic Link
    • OAuth / Social Login
    • Passkey (WebAuthn)
    • SAML SSO
    • Machine-to-Machine (M2M)
    • API Keys
  • Authorization

    • Authorization
    • Resources
    • Policies
    • Roles
    • Access Explorer
  • Tenancy

    • Multi-tenancy
    • Tenancy Customization
  • Brand & Host

    • Branding
    • Custom Domains
    • Communications & Email Templates
  • Operate

    • Users
    • Analytics
    • Audit Logs
    • Application Settings
  • SDK Quickstarts

    • Quickstart — Next.js
    • Quickstart — React SPA
    • Quickstart — Hono
    • Quickstart — .NET (Authaz.Sdk)
  • Recipes

    • Recipes & Cookbook
    • Next.js — first integration
    • Next.js — B2B SaaS (multi-tenant)
    • Hono — first integration
    • Hono — B2B SaaS (multi-tenant)
    • React SPA — first integration
    • React SPA — B2B SaaS (multi-tenant)
    • .NET — first integration
    • .NET — B2B SaaS (multi-tenant)
  • Reference

    • Tokens
    • API Reference
    • Errors & Troubleshooting
  • Documentation

    • How Authaz is Built
  1. Authaz
  2. Docs
  3. Recipes
  4. .NET — B2B SaaS (multi-tenant)

Recipes

.NET — B2B SaaS (multi-tenant)

2 min read·Updated Jun 19, 2026

← All recipes · First time? Set up your app (60 seconds — keys + redirect URI)

An ASP.NET Core app where each customer is a tenant, users may belong to multiple tenants, and roles are scoped per tenant. Builds on the single-tenant recipe — read that first; this page only shows the deltas.

1. What you'll build#

A B2B SaaS .NET backend where the user signs in, picks a tenant (Authaz Sign-In handles this UI), and every endpoint reads tenant_id from the access token to scope its work — including authorization checks against Zeratul.

2. Application setup#

Create the app as multi-tenant, shared pool:

POST https://your-app.authaz.io/api/v1/applications
X-API-Key: mgmt_01h...
 
{
  "name": "my-saas",


Previous
.NET — first integration
Next
Tokens
"tenancy_type": "multi_tenant",
"tenancy_mode": "shared"
}

Provision a tenant per customer using the SDK:

var tenants = new TenantsApiClient(httpClientFactory, logger);
var tenant = await tenants.CreateAsync(new CreateTenantRequest { Name = "Acme Corp" });
 
var invitations = new InvitationsApiClient(httpClientFactory, logger);
await invitations.SendAsync(new SendInvitationRequest
{
    Email = "founder@acme.com",
    Roles = new[] { "admin" },
    TenantId = tenant.Id,
});

3. Install#

Same packages as single-tenant: Authaz.Sdk + Microsoft.AspNetCore.Authentication.OpenIdConnect.

4. Configure#

appsettings.json is identical to single-tenant — tenant binding happens at login time, not in config.

5. Wire it up#

The OIDC + DI wiring from the single-tenant recipe is unchanged. Add one piece: a tenant-aware authorization handler.

TenantPermissionRequirement.cs:

using Authaz.Sdk;
using Microsoft.AspNetCore.Authorization;
 
public sealed record TenantPermissionRequirement(string Resource, string Action)
    : IAuthorizationRequirement;
 
public sealed class TenantPermissionHandler(
    PermissionCheckApiClient authz,
    IHttpContextAccessor http)
    : AuthorizationHandler<TenantPermissionRequirement>
{
    protected override async Task HandleRequirementAsync(
        AuthorizationHandlerContext context,
        TenantPermissionRequirement requirement)
    {
        var sub = context.User.FindFirst("sub")?.Value;
        var tenantId = context.User.FindFirst("tenant_id")?.Value;
 
        if (!Guid.TryParse(sub, out var userId)) return;
        if (!Guid.TryParse(tenantId, out var tenantGuid)) return;
 
        var result = await authz.CheckAsync(new PermissionCheckRequest
        {
            UserId = userId,
            Permission = $"{requirement.Resource}:{requirement.Action}",
            TenantId = tenantGuid,
        });
 
        if (result.Allowed) context.Succeed(requirement);
    }
}

Register and wire policies:

builder.Services.AddHttpContextAccessor();
builder.Services.AddScoped<PermissionCheckApiClient>();
builder.Services.AddScoped<IAuthorizationHandler, TenantPermissionHandler>();
 
builder.Services.AddAuthorizationBuilder()
    .AddPolicy("invoices:create", p =>
        p.Requirements.Add(new TenantPermissionRequirement("invoices", "create")))
    .AddPolicy("invoices:read", p =>
        p.Requirements.Add(new TenantPermissionRequirement("invoices", "read")));

6. Read tenant from the access token#

The tenant_id claim is set by Authaz when the user picks their tenant during sign-in. Pull it from User:

public static class TenantContext
{
    public static (Guid UserId, Guid TenantId)? Resolve(ClaimsPrincipal user)
    {
        if (!Guid.TryParse(user.FindFirst("sub")?.Value, out var uid)) return null;
        if (!Guid.TryParse(user.FindFirst("tenant_id")?.Value, out var tid)) return null;
        return (uid, tid);
    }
}

7. Protect a tenant-scoped endpoint#

app.MapPost("/invoices", (HttpContext ctx, CreateInvoiceRequest req) =>
{
    var ctxIds = TenantContext.Resolve(ctx.User);
    if (ctxIds is null) return Results.Forbid();
    var (userId, tenantId) = ctxIds.Value;
 
    // …create the invoice scoped to tenantId…
    return Results.Created($"/invoices/{Guid.CreateVersion7()}",
        new { userId, tenantId, req.Amount });
})
.RequireAuthorization("invoices:create");

Calling Management API endpoints scoped to a tenant uses path parameters, not a query string:

app.MapGet("/team", async (HttpContext ctx, UsersApiClient users) =>
{
    var ids = TenantContext.Resolve(ctx.User);
    if (ids is null) return Results.Forbid();
    var (_, tenantId) = ids.Value;
 
    var team = await users.ListByTenantAsync(tenantId, pageSize: 50);
    return Results.Ok(team.Data);
})
.RequireAuthorization("invoices:read");

8. Common gotchas#

  • Never read tenant_id from a header, query string, or request body. It must come from HttpContext.User. Anything else is a cross-tenant escalation vector.
  • Pass tenant_id to every PermissionCheckApiClient.CheckAsync call. A check without it falls back to a global scope, which a B2B SaaS almost never wants.
  • Tenant switching is a re-login. A user changing tenants must hit /login again. The token is bound to one tenant_id for its lifetime; don't try to swap it server-side.
  • Don't key your own session cache by user alone. Key it by (user_id, tenant_id) — the same user has different roles in different tenants.
  • ManagementApiException.StatusCode == 403 usually means the API key lacks the right scope for the tenant-scoped endpoint, not that the user lacks permission. The user check is separate (Zeratul).

9. Next steps#

  • Multi-tenancy guide — shared vs isolated pools, tenant lifecycle, JWT claims
  • Architecture — tenant isolation — JWT binding, RLS, cryptographic isolation per organization
  • Authorization — Zeratul permission model, role hierarchy, authority levels