C# / .NET Compendium PLEN
.NET / C# / Security

Multi-tenancy and Web API security: what a tenant is

The word tenant has two related meanings in the context of API security. The shared conclusion: a tenant is a boundary of isolation and trust which the API has to guard at every step. The basics of authentication and authorization are in the topic Securing a Web API.

1. A tenant in a multi-tenant application (multi-tenancy)

In the SaaS model a single instance of the application and API serves many independent customers (companies, organisations), and each of them is a separate tenant. Company A's users must not be able in any way to see, change or even detect company B's data.

An example: an invoicing system whose customers are the companies Acme and Globex. Both use api.invoices.com, but each sees only its own invoices, users and settings.

The main threat is a cross-tenant data leak. It is a special case of BOLA/IDOR: it isn't about somebody else's record within a company, but about a record of another company. In SaaS such a bug can be catastrophic, because it affects many customers at once.

2. A tenant in Microsoft Entra ID (formerly Azure AD)

Here a tenant is an organisation's identity directory: its users, groups and applications. It has an identifier (tenant id, a GUID) and appears:

  • in the identity provider's address: https://login.microsoftonline.com/{tenantId}/v2.0,
  • in the JWT token as the tid claim, and the issuer (iss) contains the same identifier.

An application (API) is registered in Entra as:

  • single-tenant - available only to the users of one organisation (typical internal applications),
  • multi-tenant - available to the users of many organisations (typical SaaS).

In multi-tenant applications tokens come from different tenants, so you must not validate the issuer "blindly". With the common and organizations endpoints the issuer varies, so you have to use your own IssuerValidator to allow only the tenants that are your customers (an allow-list). Otherwise anybody from any company using Entra could sign in to your API.

3. How the API determines which tenant it is (tenant resolution)

Source Example Notes
A claim in the token tid or a custom tenant_id the safest, because it is signed by the identity provider
Subdomain acme.invoices.com convenient, but must match the tenant from the token
Header X-Tenant-Id: acme don't trust it without checking, the client can swap it
Path /tenants/acme/orders as above: check that the user belongs to this tenant

The golden rule: take the tenant from a trusted source (a signed token), and treat everything the client sent as data to be verified. If a header or subdomain points to a different tenant than the token, reject the request (403).

4. Data isolation models

Model Description Isolation Cost and scale
A database per tenant every tenant has its own database the strongest the most expensive, harder migrations
A schema per tenant one database, separate schemas strong medium
A shared database and a TenantId column all the data in the same tables the weakest, requires discipline in the code the cheapest, the best scalability

With the TenantId column model, one forgotten Where(o => o.TenantId == ...) means a data leak. That is why the filter is enforced centrally, rather than by hand in every query.

5. Implementation in .NET: the tenant from the token and a global EF Core filter

The key elements are: a tenant provider reading the claim from the signed token, a global query filter (HasQueryFilter) and a SaveChanges that sets the TenantId of new records itself. The effect: GET /api/orders/3 for another company's order returns 404, because the filter doesn't "see" it at all.

using System.Security.Claims;
using Microsoft.EntityFrameworkCore;

// Where the current tenant comes from.
public interface ITenantProvider
{
    string TenantId { get; }
}

// Production implementation: the tenant comes from the SIGNED token ("tid" claim),
// never from a header or body supplied by the client.
public class ClaimsTenantProvider(IHttpContextAccessor accessor) : ITenantProvider
{
    public string TenantId =>
        accessor.HttpContext?.User.FindFirstValue("tid")
        ?? throw new UnauthorizedAccessException("No tenant claim in the token");
}

// Used for seeding data and for background work that has no HTTP request.
public class FixedTenantProvider(string tenantId) : ITenantProvider
{
    public string TenantId => tenantId;
}

public interface ITenantEntity
{
    string TenantId { get; set; }
}

public class Order : ITenantEntity
{
    public int Id { get; set; }
    public string TenantId { get; set; } = string.Empty;
    public string Item { get; set; } = string.Empty;
}

public class AppDbContext : DbContext
{
    private readonly ITenantProvider _tenant;

    public AppDbContext(DbContextOptions<AppDbContext> options, ITenantProvider tenant) : base(options)
        => _tenant = tenant;

    public DbSet<Order> Orders => Set<Order>();

    protected override void OnModelCreating(ModelBuilder modelBuilder)
    {
        // Global query filter: EVERY query on Orders is limited to the current tenant,
        // so a forgotten Where(...) cannot leak data between tenants.
        modelBuilder.Entity<Order>().HasQueryFilter(o => o.TenantId == _tenant.TenantId);
    }

    public override int SaveChanges(bool acceptAllChangesOnSuccess)
    {
        ApplyTenant();
        return base.SaveChanges(acceptAllChangesOnSuccess);
    }

    public override Task<int> SaveChangesAsync(bool acceptAllChangesOnSuccess, CancellationToken cancellationToken = default)
    {
        ApplyTenant();
        return base.SaveChangesAsync(acceptAllChangesOnSuccess, cancellationToken);
    }

    private void ApplyTenant()
    {
        foreach (var entry in ChangeTracker.Entries<ITenantEntity>())
        {
            if (entry.State == EntityState.Added)
                entry.Entity.TenantId = _tenant.TenantId;                    // the client cannot choose the tenant
            else if (entry.State == EntityState.Modified)
                entry.Property(nameof(ITenantEntity.TenantId)).IsModified = false; // a row cannot be moved to another tenant
        }
    }
}

Wiring it up in the API (note the X-Tenant-Id header, which may only confirm the tenant from the token):

using System.IdentityModel.Tokens.Jwt;
using System.Security.Claims;
using System.Text;
using Microsoft.AspNetCore.Authentication.JwtBearer;
using Microsoft.EntityFrameworkCore;
using Microsoft.IdentityModel.Tokens;

var builder = WebApplication.CreateBuilder(args);

// DEMO ONLY: in production tokens come from an identity provider (e.g. Entra ID with its "tid" claim)
// and the key is not stored in code.
const string Issuer = "https://demo.local";
const string Audience = "orders-api";
var signingKey = new SymmetricSecurityKey(Encoding.UTF8.GetBytes("demo-key-change-me-at-least-32-bytes-long!!"));

builder.Services
    .AddAuthentication(JwtBearerDefaults.AuthenticationScheme)
    .AddJwtBearer(o =>
    {
        o.MapInboundClaims = false; // keep claim names as in the token ("sub", "tid")
        o.TokenValidationParameters = new TokenValidationParameters
        {
            ValidateIssuer = true, ValidIssuer = Issuer,
            ValidateAudience = true, ValidAudience = Audience,
            ValidateLifetime = true,
            ValidateIssuerSigningKey = true, IssuerSigningKey = signingKey,
            ValidAlgorithms = new[] { SecurityAlgorithms.HmacSha256 }
        };
    });
builder.Services.AddAuthorization();

builder.Services.AddHttpContextAccessor();
builder.Services.AddScoped<ITenantProvider, ClaimsTenantProvider>();
builder.Services.AddDbContext<AppDbContext>(o => o.UseInMemoryDatabase("tenants-demo"));

var app = builder.Build();

// Seed: each tenant gets its own orders (a context with a FIXED tenant, no HTTP request here).
using (var scope = app.Services.CreateScope())
{
    var options = scope.ServiceProvider.GetRequiredService<DbContextOptions<AppDbContext>>();
    var seed = new Dictionary<string, string[]>
    {
        ["acme"] = new[] { "Laptop", "Mouse" },
        ["globex"] = new[] { "Keyboard" }
    };
    foreach (var (tenant, items) in seed)
    {
        using var db = new AppDbContext(options, new FixedTenantProvider(tenant));
        db.Orders.AddRange(items.Select(i => new Order { Item = i }));
        db.SaveChanges(); // TenantId is filled in by the context
    }
}

app.UseAuthentication();

// A tenant sent by the client (header) may only CONFIRM the tenant from the token, never override it.
app.Use(async (ctx, next) =>
{
    if (ctx.User.Identity?.IsAuthenticated == true
        && ctx.Request.Headers.TryGetValue("X-Tenant-Id", out var header)
        && header != ctx.User.FindFirstValue("tid"))
    {
        ctx.Response.StatusCode = StatusCodes.Status403Forbidden;
        return;
    }
    await next();
});

app.UseAuthorization();

// demo users: user -> (password, tenant)
var users = new Dictionary<string, (string Password, string Tenant)>
{
    ["alice"] = ("alice123", "acme"),
    ["carol"] = ("carol123", "acme"),
    ["bob"] = ("bob123", "globex")
};

app.MapPost("/login", (LoginRequest request) =>
{
    if (!users.TryGetValue(request.Username, out var u) || u.Password != request.Password)
        return Results.Unauthorized();

    var claims = new[]
    {
        new Claim("sub", request.Username),
        new Claim("tid", u.Tenant) // the tenant is part of the SIGNED token
    };
    var token = new JwtSecurityToken(Issuer, Audience, claims,
        expires: DateTime.UtcNow.AddMinutes(10),
        signingCredentials: new SigningCredentials(signingKey, SecurityAlgorithms.HmacSha256));

    return Results.Ok(new { access_token = new JwtSecurityTokenHandler().WriteToken(token), tenant = u.Tenant });
});

// No Where(TenantId) here on purpose: the global query filter does it.
app.MapGet("/api/orders", async (AppDbContext db) => await db.Orders.ToListAsync())
   .RequireAuthorization();

// Another tenant's order simply does not exist for the caller -> 404 (not even a hint that it exists).
// Note: FirstOrDefaultAsync applies the query filter (do not rely on Find for this).
app.MapGet("/api/orders/{id:int}", async (int id, AppDbContext db) =>
{
    var order = await db.Orders.FirstOrDefaultAsync(o => o.Id == id);
    return order is null ? Results.NotFound() : Results.Ok(order);
}).RequireAuthorization();

// The client sends only the item; TenantId is assigned by the server.
app.MapPost("/api/orders", async (NewOrder input, AppDbContext db) =>
{
    var order = new Order { Item = input.Item };
    db.Orders.Add(order);
    await db.SaveChangesAsync();
    return Results.Created($"/api/orders/{order.Id}", order);
}).RequireAuthorization();

// ANTI-PATTERN, on purpose: IgnoreQueryFilters bypasses the tenant filter and leaks all tenants' data.
// Such a call must never be reachable by ordinary users - review every use of IgnoreQueryFilters.
app.MapGet("/api/debug/leak", async (AppDbContext db) => await db.Orders.IgnoreQueryFilters().ToListAsync())
   .RequireAuthorization();

app.Run();

record LoginRequest(string Username, string Password);
record NewOrder(string Item);

The project (TenantIsolationDemo.csproj, the JwtBearer and EF Core InMemory packages):

<Project Sdk="Microsoft.NET.Sdk.Web">

  <PropertyGroup>
    <TargetFramework>net8.0</TargetFramework>
    <Nullable>enable</Nullable>
    <ImplicitUsings>enable</ImplicitUsings>
  </PropertyGroup>

  <ItemGroup>
    <PackageReference Include="Microsoft.AspNetCore.Authentication.JwtBearer" Version="8.0.10" />
    <PackageReference Include="Microsoft.EntityFrameworkCore.InMemory" Version="8.0.10" />
  </ItemGroup>

</Project>

How to try it

dotnet run, then a requests.http file (VS Code with REST Client, Rider, Visual Studio) or curl. The users: alice and carol (tenant acme), bob (tenant globex). The passwords have the form name123.

Request Result
alice: GET /api/orders only the acme tenant's orders (Laptop, Mouse)
alice: GET /api/orders/3 (an order of the globex tenant) 404
alice with the header X-Tenant-Id: globex 403
bob: POST /api/orders an order with the globex tenant, invisible to alice
alice: GET /api/debug/leak a leak of the orders of all tenants (a deliberate anti-pattern)

The pitfalls of this approach

  • IgnoreQueryFilters() and raw SQL (FromSqlRaw) bypass the filter, so they have to be controlled in code review.
  • Background tasks and queue consumers have no HttpContext, so the tenant has to reach them in the message and be set explicitly (like FixedTenantProvider when seeding data).
  • Find/FindAsync is not suitable for reliable isolation, use FirstOrDefaultAsync with the filter.
  • Global tables (lookups shared by everyone) shouldn't have the filter.
  • Migrations and administrative reports require a deliberate, audited bypass of the filter.

6. What else a tenant means for security

  • Authorization has two levels: first "does this user belong to this tenant", then "what is he allowed to do within the tenant". Roles and policies work inside the tenant. A tenant administrator is not the same as a platform administrator.
  • The cache must include the tenant in the key (orders:{tenantId}:{id}), otherwise tenant A will get tenant B's response from the cache.
  • Rate limiting and resource limits per tenant, so that one customer doesn't take up the whole platform (the "noisy neighbour" problem, see Rate limiting).
  • Keys and encryption per tenant (separate keys in Key Vault) in demanding industries, which limits the effects of a single key leaking.
  • Logs and audit with the tenant identifier, so that an incident at a specific customer can be investigated.
  • Isolation tests: automated tests in which tenant A tries to read and change tenant B's data and must get 403 or 404.
  • The customer's secrets and integrations (e.g. the tenant's own API keys) keep separately for each tenant.

The answer in an interview in brief

A tenant is a customer (an organisation) using one shared instance of a SaaS application, and in Entra ID an organisation's identity directory, whose identifier is in the token's tid claim. In the security context what matters most is tenant isolation: I determine the tenant from the signed token, not from a header sent by the client, and I enforce data access centrally (e.g. a global EF Core filter), so that no data leaks between customers. In a multi-tenant application the issuer validation must let through only the allowed tenants.

Interview questions

  • What is a tenant? A customer (an organisation) using a shared instance of an application, and in Entra ID an organisation's identity directory (the tid claim).
  • How do you ensure data isolation in multi-tenancy? A database or schema per tenant, or a shared database with a TenantId column enforced centrally (an EF Core global query filter).
  • Where do you get the tenant from in a request? From the signed token, and a header or subdomain only compared against it, never trusted on their own.
  • What is the risk of a multi-tenant app in Entra without issuer validation? Any organisation could sign in, so you have to allow only known customers (a tenant allow-list).
  • How can an ordinary TenantId filter fail? IgnoreQueryFilters, raw SQL, Find, background tasks without an HTTP context, and a cache without the tenant in the key.
  • How does BOLA/IDOR differ from a cross-tenant leak? It is the same class of bug, but with multi-tenancy it concerns another company's data, so the consequences are much more serious.
Buy me a coffee