How to get a list of policies from Asp.Net Core Authentication?

I am building a web application using Asp.Net Core 1.1.1 and its authorization / authentication system.

In my startup.cs file, I configured various policies that I need:

public void ConfigureServices(IServiceCollection services)
{
        servizi.AddAuthorization(options =>
        {
            options.AddPolicy("Insert", policyBuilder => policyBuilder .RequireClaim("AllowInsert"));
            options.AddPolicy("Update", policyBuilder => policyBuilder .RequireClaim("AllowUpdate"));
            options.AddPolicy("Delete", policyBuilder => policyBuilder .RequireClaim("AllowDelete"));
        });
}

Then, in the controller, I assigned claims to the role (administrator role):

    public async Task<IActionResult> AssignClaimstoAdminRole()
    {
        await _roleManager.AddClaimAsync(await _roleManager.FindByNameAsync("Administrator"), new Claim("AllowInsert", "true"));
        await _roleManager.AddClaimAsync(await _roleManager.FindByNameAsync("Administrator"), new Claim("AllowUpdate", "true"));
        await _roleManager.AddClaimAsync(await _roleManager.FindByNameAsync("Administrator"), new Claim("AllowDelete", "true"));

        await _loginManager.RefreshSignInAsync(await _userManager.FindByNameAsync(User.Identity.Name));
        return RedirectToAction("SomeAction", "MyController");
    }

and finally, I protected my views by introducing an authorization service:

@using Microsoft.AspNetCore.Authorization
@inject IAuthorizationService AuthorizationService

@if (await AuthorizationService.AuthorizeAsync(User, "Insert"))
{
     <i role="submit" class="fa fa-floppy-o fa-2x"></i>
}

My question: I would like to get a list of policies created in startup.cs, so in the end I can create a page to add other users / roles, assigning them one or more policies already in the system.

Is there an object that provides a collection of previously added policies? Thanks in advance!

+4
2

IActionDescriptorCollectionProvider.

var policies = actionDescriptorCollectionProvider.ActionDescriptors.Items
       .SelectMany(actionDescriptor => actionDescriptor.FilterDescriptors.SelectMany(filter => (filter.Filter as AuthorizeFilter)?.AuthorizeData?.Select(authData => authData.Policy) ?? new string[0]))
       .Where(policy => !string.IsNullOrEmpty(policy))
       .Distinct();
0

Source: https://habr.com/ru/post/1672359/


All Articles