Permission-based Authorization in ASP.NET Core with AuthorizationPolicyProvider

Implement AuthorizationPolicyProvider

For this purpose, we can implement AuthorizationPolicyProvider or inherit from DefaultAuthorizationPolicyProvider that registered in DI system as default provider.

public class AuthorizationPolicyProvider : DefaultAuthorizationPolicyProvider
{
public AuthorizationPolicyProvider(IOptions options)
: base(options)
{
}

public override Task GetPolicyAsync(string policyName)
{
if (!policyName.StartsWith(PermissionAuthorizeAttribute.PolicyPrefix, StringComparison.OrdinalIgnoreCase))
{
return base.GetPolicyAsync(policyName);
}

var permissionNames = policyName.Substring(PermissionAuthorizeAttribute.PolicyPrefix.Length).Split(',');

var policy = new AuthorizationPolicyBuilder()
.RequireClaim(CustomClaimTypes.Permission, permissionNames)
.Build();

return Task.FromResult(policy);
}
}

In this implementation, GetPolicyAsync is responsible to find and return one policy based on policyName. However, we can automate the process of defining the policy by overriding it and using an instance of AuthorizationPolicyBuilder. In the body of GetPolicyAsync method, first checked that received policyName starts with “PERMISSION:” or not; then split policyName with ‘,’ character to retrieve permission names. Finally, define policy with retrieved permissions and return it.

Now, To replace this implementation with default registered, use the following code in startup:

services.AddSingleton();

read original article here