ASP.NET Core Interview Question #236
How would you implement multi-tenant data isolation?
Senior ASP.NET Core Real-World Scenarios Senior Advanced
Quick Interview Answer
Identify the tenant from a trusted source, such as authenticated claims, a validated host mapping, or another controlled tenant-resolution mechanism. Do not trust an arbitrary tenant ID from the request without verifying the user is entitled to that tenant.
Detailed Explanation
Identify the tenant from a trusted source, such as authenticated claims, a validated host mapping, or another controlled tenant-resolution mechanism. Do not trust an arbitrary tenant ID from the request without verifying the user is entitled to that tenant.
Carry tenant context through the application and enforce it at the data-access boundary. Depending on requirements, tenants may share tables with TenantId columns, use separate schemas, or use separate databases.
Defense in depth is important: authorization, query filtering, unique constraints that include tenant identity, tests, and careful administrative tooling should all prevent cross-tenant access.
Code Example
var tenantId = _tenantContext.TenantId;
var orders = await db.Orders
.Where(o => o.TenantId == tenantId)
.ToListAsync(ct);