Design a multi-tenant .NET application that prevents one customer from reading another customer’s data.
PhonePe · Full Stack Developer · 3-4-years · technical
Published
Year not specified · .NET, Authentication & Security, System Design
Community answers
Posted by wasAsked editorial collection
Resolve tenant identity from authenticated claims or a trusted server-side mapping and carry it through a scoped context. Never authorize a tenant merely because its ID appears in the URL or request body.
Every tenant-owned table and unique/index relationship should include RestaurantId and OutletId. Every SELECT, INSERT, UPDATE, and DELETE must apply both values; use query filters only as defense-in-depth because IgnoreQueryFilters and raw SQL can bypass them. Validate related entity ownership and include tenant keys in cache keys, events, blobs, jobs, and audit records. Add negative integration tests that attempt cross-tenant reads and writes, and use database row-level security where appropriate as an additional barrier.
Backbencher Developer · · 0 likes
Tenant isolation must be enforced on the server at every layer, not just in the UI.
1. Establish the tenant reliably
- Derive the tenant from the authenticated identity (a tenant_id claim in the token issued by your identity provider), not from a header or query string the client can change.
- If a user can belong to several tenants, validate the requested tenant against the user's memberships on every request.
2. Enforce isolation in data access
- Shared database: every tenant-owned table has a TenantId column. In EF Core, apply a global query filter:
modelBuilder.Entity<Invoice>().HasQueryFilter(i => i.TenantId == _tenantContext.TenantId);
and set TenantId automatically on insert in SaveChanges.
- Add defence in depth with SQL Server Row-Level Security or PostgreSQL RLS policies, so even a bug or raw SQL query cannot cross tenants.
- Include TenantId in unique indexes and foreign keys so references cannot point to another tenant's rows.
- For stricter requirements, use schema-per-tenant or database-per-tenant isolation, at the cost of more operational work.
3. Authorization
- Check access to each resource by ID and tenant (resource-based authorization), returning 404 rather than 403 so IDs cannot be probed.
- Avoid guessable sequential IDs in URLs where possible.
4. Other shared resources
- Prefix cache keys, blob paths, search indexes and message topics with the tenant ID.
- Background jobs must carry the tenant ID explicitly, because there is no HTTP request.
- Logs and exports should be tenant-scoped.
5. Verify it
- Automated tests that log in as tenant A and attempt to read, update and list tenant B's data through every endpoint.
- Code review and static checks for queries that bypass the filter (IgnoreQueryFilters, raw SQL).
- Penetration testing focused on IDOR (insecure direct object reference) issues.