Identify the tenant from trusted context
A multi-tenant application serves multiple organizations from one deployment. Tenant context may come from a verified subdomain, authenticated membership or a trusted routing layer. Do not trust a tenant ID supplied in a hidden form field or arbitrary request parameter.
Enforce tenant scope in repositories
Every query that reads or changes tenant-owned data should include the tenant boundary. Centralize this rule in repositories or a data-access layer so developers do not have to remember to add it manually to every controller query.
SELECT id, name
FROM projects
WHERE tenant_id = :tenant_id
AND id = :project_id;
The tenant ID must come from the authenticated and authorized context, not directly from user input. For updates and deletes, include the tenant predicate in the statement itself.
Consider database constraints
Where appropriate, use composite unique keys such as (tenant_id, external_reference) and foreign keys that preserve tenant relationships. This can prevent accidental cross-tenant associations at the database level.
Isolate caches and files
Include tenant identity in cache keys and private storage paths. Authorize file downloads against both the file record and the active tenant. Avoid shared temporary filenames that could collide across tenants.
Test isolation explicitly
Create tests with two tenants and attempt to access each other's records by changing IDs, URLs, API payloads and export parameters. Include background jobs and administrative tools in the test plan.
Checklist
- Resolve tenant from trusted authenticated context.
- Enforce tenant scope in every repository operation.
- Use database constraints where practical.
- Scope cache keys, files and jobs by tenant.
- Test cross-tenant access attempts.
- Audit privileged support and admin access.
References
OWASP Authorization Cheat Sheet · OWASP Multi-Tenant Security