How do you implement resource-based authorization, where the authorization decision depends on the specific object being accessed, not just the user's general permissions?
Short answer
Resource-based authorization uses IAuthorizationService.AuthorizeAsync(user, resource, requirement) directly within your action/endpoint (rather than a declarative attribute, since the resource instance isn't known until the object is loaded), combined with a custom…
Advertisement
AModel answer
Resource-based authorization uses IAuthorizationService.AuthorizeAsync(user, resource, requirement) directly within your action/endpoint (rather than a declarative attribute, since the resource instance isn't known until the object is loaded), combined with a custom IAuthorizationHandler<TRequirement, TResource> that inspects both the user and the specific resource (e.g., checking if the user is the resource's owner) to make the decision.
public class OwnerAuthorizationHandler : AuthorizationHandler<OwnerRequirement, Document> {
protected override Task HandleRequirementAsync(AuthorizationHandlerContext context, OwnerRequirement requirement, Document resource) {
if (resource.OwnerId == context.User.FindFirst("sub")?.Value)
context.Succeed(requirement);
return Task.CompletedTask;
}
}
// Usage in an endpoint:
var document = await _repository.GetAsync(id);
var result = await _authorizationService.AuthorizeAsync(User, document, "DocumentOwner");
if (!result.Succeeded) return Forbid();Real-world example
A document management system ensures users can only edit documents they own by checking resource-based authorization against the actual loaded Document entity's OwnerId, something a declarative [Authorize] attribute alone couldn't express since it has no access to the specific resource instance.
Likely follow-ups
- Why can't resource-based authorization be expressed with a declarative attribute alone?
- How do multiple resource-based handlers for the same requirement combine?
Related topics