ASP.NET核心策略库使用带有字符串数组的RequireUser进行授权

zazmityj  于 2023-02-14  发布在  .NET
关注(0)|答案(2)|浏览(152)

我正在创建基于策略的授权,希望允许一个策略中的多个用户访问网页。
我创建了如下所示的策略在启动文件。问题,我怎么能在一个策略中使用多个用户名?我看了.RequireUserName的方法,它只接受字符串用户名。
策略名称AdminServiceAccount是我最感兴趣的添加多个用户。如果我使用参数.RequireUserName("DOMAIN\\USER1,DOMAIN\\USER2"),它会工作吗?我不这样认为,但想检查是否有一个替代方法。

services.AddAuthorization(
                option =>
                {
                    option.AddPolicy("Admin", policy => policy.RequireRole("Domain\\GroupName"));
                    option.AddPolicy("SuperAdminUser", policy => policy.RequireUserName("DOMAIN\\SuperAdminUser"));
                    option.AddPolicy("AdminServiceAccount", policy => policy.RequireUserName("DOMAIN\\USER1"));
                }
        );

**更新1:**x1c 0d1x
更新2:

因此,在我的控制器中,我添加了[Authorize(Policy = "UserNamesPolicy")],如下所示:

[Authorize(Policy = "UserNamesPolicy")]
public class ServersController : Controller
{
    private readonly ServerMatrixDbContext _context;

    public ServersController(ServerMatrixDbContext context)
    {
        _context = context;    
    }

    // GET: Servers
    public async Task<IActionResult> Index()
    {
        // Some code here
        return View();
    }
}

下面是我的启动文件:

services.AddAuthorization(
                option =>
                {
                    option.AddPolicy("UserNamesPolicy",
                                          policy => policy.Requirements.Add(new UserNamesRequirement("DOMAIN\\USER1", "DOMAIN\\USER2"))
                    );
                }
        );
services.AddSingleton<IAuthorizationHandler, UserNamesRequirement();

对于启动文件中的.AddSingleTon,我得到以下错误:

下面是handler类:

public class UserNamesHandler : AuthorizationHandler<UserNamesRequirement>
{

    protected override Task HandleRequirementAsync(AuthorizationHandlerContext context, UserNamesRequirement requirement)
    {
        var userName = context.User.FindFirst(ClaimTypes.NameIdentifier).Value;

        if (requirement.Users.ToList().Contains(userName))
            context.Succeed(requirement);
        return Task.FromResult(0);
    }
}

下面是UserNamesRequirement类:

public class UserNamesRequirement : IAuthorizationRequirement
{
    public UserNamesRequirement(params string[] UserNames)
    {
        Users = UserNames;
    }
    public string[] Users { get; set; }
}

**更新3:**解决!!!

以下是从更新2添加的一些变更:
UserNameshandler类中,将var userName更改为从context.User.Identity.Name;获取值

public class UserNamesHandler : AuthorizationHandler<UserNamesRequirement>
{

    protected override Task HandleRequirementAsync(AuthorizationHandlerContext context, UserNamesRequirement requirement)
    {
        // var userName = context.User.FindFirst(ClaimTypes.NameIdentifier).Value;
        var userName = context.User.Identity.Name;

        if (requirement.Users.ToList().Contains(userName))
            context.Succeed(requirement);
        return Task.FromResult(0);
    }
}

在启动类中,将services.AddSingleton<IAuthorizationHandler, UserNamesRequirement>();修复为services.AddSingleton<IAuthorizationHandler,UserNamesHandler>();
感谢Gevory。:)

wbgh16ku

wbgh16ku1#

public class UserNamesHandler : AuthorizationHandler<UserNamesRequirement>
{
    protected override Task HandleRequirementAsync(AuthorizationHandlerContext context, UserNamesRequirement requirement)
    {
        var userName = context.User.Identity.Name;
        if(requirement.UserNames.ToList().Contains(userName))
            context.Succeed(requirement);
        return Task.CompletedTask; // if it does not compile use Task.FromResult(0);
    }
}

public class UserNamesRequirement : IAuthorizationRequirement
{
    public UserNamesRequirement(params string[] userNames)
    {
        UserNames = userNames;
    }

    public string[] UserNames { get; set; }
}

在startup.cs中添加以下内容

public void ConfigureServices(IServiceCollection services)
{
            services.AddAuthorization(options =>
            {
                options.AddPolicy("UserNamesPolicy",
                                  policy => policy.Requirements.Add(new UserNamesRequirement("ggg","dsds")));
            });
           services.AddSingleton<IAuthorizationHandler, UserNamesHandler>()

}
w1jd8yoj

w1jd8yoj2#

对于任何想使用不同方法的人来说,我一直在努力让UserNamesHandler正确注册,但没有效果。因此,我用不同的方法解决了这个问题:

static readonly string[] myUserList = { "user1", "user2", "user3" };

options.AddPolicy( "MyNameListPolicy", 
          policy => policy.RequireAssertion( 
                context => myUserList.Contains( context.User.Identity.Name ) ) );

这对我很有效。

相关问题