ASP.NET Core 2.0如何在策略中访问UserManager?

时间:2018-12-04 09:33:38

标签: c# asp.net-core asp.net-core-identity

我有这个需求类,需要访问usermanager

public class NoAdminRequirment : IAuthorizationRequirement
{
    bool NoAdmins { get; set; }
    private readonly UserManager<IdentityUser> userManager;

    public NoAdminRequirment(UserManager<IdentityUser> userManager)
    {
        this.userManager = userManager;
            NoAdmins = userManager.GetUsersInRoleAsync("administrators").Result.Count() == 0;
    }
}

我的理解是,由于我已经在应用程序中进行了设置,因此依赖项注入会自动初始化usermanager

这不是很有用,因为我现在需要通过策略中的usermanager

services.AddAuthorization(option =>
{
    option.AddPolicy("NoAdmins", policy => policy.Requirements.Add(new { /*???*/ }));
});

有人可以建议一种替代方法或方法来访问用户管理器吗?

2 个答案:

答案 0 :(得分:0)

我认为这应该可以解决问题:

public class ExcludeRoleRequirement : IAuthorizationRequirement
{
  public string Role { get; private set; }

  public ExcludeRoleRequirement(string role)
  {
    Role = role;
  }
}

由于ExcludeRoleHandler已注册到DI容器中,并且我假设UserManager也已注册,因此可以将UserManager添加到构造函数中

public class ExcludeRoleHandler : AuthorizationHandler<ExcludeRoleRequirement>
{
  private readonly UserManager<IdentityUser> _manager;
  public ExcludeRoleHandler(UserManager<IdentityUser> manager)
  {
    _manager = manager;
  }
  protected override async Task HandleRequirementAsync(AuthorizationHandlerContext context, 
    ExcludeRoleRequirement requirement)
  {
    var usersInRole = await _manager.GetUsersInRoleAsync(requirement.Role);
    if (!usersInRole.Any())
    {
      context.Succeed(requirement);
    }

    return Task.CompletedTask;
  }
}

然后在Startup.cs中:

services.AddAuthorization(option => {
  options.AddPolicy("NoAdmin", policy =>
    policy.Requirements.Add(new ExcludeRoleRequirement("administrators")));  
});


services.AddSingleton<IAuthorizationHandler, ExcludeRoleHandler>();

希望这会有所帮助

编辑:我忘记添加

[Authorize(Policy = "NoAdmin")]
public class NotForAdminController : ControllerBase
{
}

答案 1 :(得分:-1)

services.AddAuthorization(option => {
    option.AddPolicy("NoAdmins", policy => 
                policy.Requirements.Add(services.BuildServiceProvider().GetService<NoAdminRequirment>()));
});