How to Implement Tenant ID in Multitenant Applications

Listen to this Post

Featured Image
In multitenant applications, passing a Tenant ID is crucial for isolating data between different tenants. Here are common methods to achieve this:

  1. Request Header – Include the Tenant ID in the HTTP request header.
  2. Cookie – Store the Tenant ID in a browser cookie.
  3. JWT (JSON Web Token) – Embed the Tenant ID in a signed token for security.

Other approaches include:

  • Query String – Pass the Tenant ID as a URL parameter.
  • Identity Claim – Extract it from authenticated user claims (most secure).
  • Database Lookup – Fetch it from the database (may impact performance).

For EF Core, you can implement tenant filtering using global query filters.

🔗 Reference: EF Core Tenant Filtering

You Should Know:

1. Extracting Tenant ID from JWT in .NET

var tenantId = User.Claims.FirstOrDefault(c => c.Type == "tenant_id")?.Value; 

2. Implementing Tenant Filtering in EF Core

protected override void OnModelCreating(ModelBuilder modelBuilder) 
{ 
modelBuilder.Entity<YourEntity>().HasQueryFilter(e => e.TenantId == _tenantId); 
} 
  1. Securing Tenant ID in HTTP Headers (Middleware Example)
    app.Use(async (context, next) => 
    { 
    if (!context.Request.Headers.TryGetValue("X-Tenant-ID", out var tenantId)) 
    { 
    context.Response.StatusCode = 400; 
    await context.Response.WriteAsync("Tenant ID missing"); 
    return; 
    } 
    await next(); 
    }); 
    

4. Using Row-Level Security in PostgreSQL

CREATE POLICY tenant_isolation_policy ON your_table 
USING (tenant_id = current_setting('app.current_tenant_id')); 

5. Linux Command to Inspect JWT (for Debugging)

echo "YOUR_JWT_TOKEN" | jq -R 'split(".") | .[bash] | @base64d | fromjson' 

6. Windows Command to Check HTTP Headers (PowerShell)

Invoke-WebRequest -Uri "https://yourapi.com" -Headers @{"X-Tenant-ID"="123"} 

What Undercode Say:

Multitenancy is a critical architectural pattern, and securing Tenant ID handling is essential. Always prefer JWT claims for security, and avoid exposing Tenant IDs in URLs.

  • For Linux Admins: Use `jq` to decode JWTs for debugging.
  • For Windows Admins: PowerShell helps test API headers.
  • For DB Admins: PostgreSQL RLS and SQL Server Row-Level Security enhance isolation.
  • For .NET Devs: EF Core query filters simplify tenant separation.

🔹 Pro Tip: Always validate Tenant ID in middleware to prevent unauthorized access.

Expected Output:

A secure, well-structured multitenant system where Tenant ID is safely passed via JWT claims, enforced via middleware, and filtered in EF Core.

🔗 Further Reading: EF Core Tenant Filtering

References:

Reported By: Milan Jovanovic – Hackers Feeds
Extra Hub: Undercode MoN
Basic Verification: Pass ✅

Join Our Cyber World:

💬 Whatsapp | 💬 Telegram