In this example, authorization is a simple check that the UserId of the resource (an Article) is equal to the ID of the user requesting it. The check happens in a controller action after the resource is retrieved from a database via a repository.
Create a custom requirement class, and implement a requirement handler class.
In my case the requirement class is an empty class implementing IAuthorizationRequirement:
The requirement handler:
ClaimTypes.NameIdentifier here is the claim type for the user ID claim (it is the default value of the ClaimsIdentityOptions.UserIdClaimType property).
Register the requirement and handler in Program.cs:
This is the setup needed in Program.cs:
Inject IAuthorizationService into the controller:
A controller action using this:
Signature of this IAuthenticationServiceAuthorizeAsync overload:
Other comments:
HttpContext.User is one way to get the current ClaimsPrincipal.
Adding [Authorize] to the controller/action would be somewhat similar to the user == null check.
Sending a Not Found response instead of Forbidden for when the resource was found but the user was not authorized to see it is a good practice as it prevents giving away the existence of the resource.