ASP.NET Core: Obtain the requirements/roles from a Policy programmatically


I recently needed to surface a page which listed the currently applied requirements/roles that were included with all policies in a site I was working on. A policy a ASP.Net core can be a requirement that is made up of a set of business logic (such as, users must be over 13 years old) or something more traditional such as an Active Directory security group or an application specific security group.

In order to get at this information you will need to inject an instance of IAuthorizationPolicyProvider into your controller which will allow us to dig into the makeup of these policies. For my simple example I will hard code a policy name and I will return the requirements as a comma delimited string.

C#

// PolicyProvider being a property that is set to the value of the injected IAuthorizationPolicyProvider
var policy = PolicyProvider.GetPolicyAsync("AdminPolicy");
string requirements = "";

foreach (RolesAuthorizationRequirement item in policy.Result.Requirements)
{
    requirements += string.Join(",", item.AllowedRoles);
}

Leave a comment

Please note that we won't show your email to others, or use it for sending unwanted emails. We will only use it to render your Gravatar image and to validate you as a real person.