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

Posted by Blake on 6/25/2018
)

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);
    }