In this lesson, you will learn how to enforce multi-tenant isolation by ensuring users can only interact with shared resources that belong to their specific organization.
The Multi-Tenant Boundary
When building a system where multiple organizations (tenants) share the same database, the biggest security risk is data leakage. Even if a user is authenticated, you must verify that the OrganizationId associated with their identity matches the OrganizationId of the resource they are trying to access.
Without this check, a user from "Company A" could potentially manipulate a resource ID belonging to "Company B," leading to an unauthorized data breach.
Implementing Tenant-Aware Authorization
To enforce this, we don't just rely on roles or claims; we combine the user's OrganizationId claim with the resource's ownership property. The most effective way to handle this is by creating a Resource-Based Authorization requirement.
Consider a service where a Document belongs to an OrganizationId:
public class DocumentRequirement : IAuthorizationRequirement
{
public string Operation { get; set; }
}
public class DocumentAuthorizationHandler : AuthorizationHandler<DocumentRequirement, Document>
{
protected override Task HandleRequirementAsync(AuthorizationHandlerContext context,
DocumentRequirement requirement, Document resource)
{
// Extract the user's organization from their claims
var userOrgId = context.User.FindFirst("OrganizationId")?.Value;
// Compare the claim against the resource's owner
if (userOrgId != null && userOrgId == resource.OrganizationId.ToString())
{
context.Succeed(requirement);
}
return Task.CompletedTask;
}
}
By passing the Document object directly into the AuthorizationService.AuthorizeAsync method, your handler acts as a gatekeeper. It forces the application to validate the organizational boundary before any business logic is executed. This pattern ensures that even if you accidentally pass the wrong ID, the authorization layer will fail because the OrganizationId mismatch prevents the operation.
Always ensure your OrganizationId claim is populated during the sign-in process via a custom claims provider, establishing a "source of truth" for the user's tenancy.
Key Takeaway: Multi-tenant security requires an explicit validation step that compares the user's organizational claim against the specific resource's ownership ID before access is granted.