ASP.NET 核心 2.1 身份的基于权限的授权

Rights-based authorization with ASP.NET Core 2.1 Identity

过去,在 .NET Framework 上使用 ASP.NET MVC,我总是在内置的基于角色的授权之上实现基于权限的授权层。 "Rights-based",我的意思是将枚举权限列表分配给每个角色,并且在运行时,每个调用都会检查权限,而不是角色。

例如假设 OrdersController 上的 Post 方法需要 AddOrEditOrder 权限。这看起来像 Post 操作中的 [MyAuthorize(MyRights.AddOrEditOrder)]。然后在其他地方你可以配置只有经理和客户代表角色有那个权利。

我一直认为这个小抽象层很容易实现并且大大提高了可维护性,即使权限到角色的映射仅从配置文件而不是 UI 更新。来自基于 Windows 的 IT 设置,这只是 "how it's done right",IMO。

然而,转向 ASP.NET 核心身份,我们对声明有了所有这些新奇的幻想。现在,我意识到索赔和权利根本不是一回事。但是,你能否使用Claims,将它们分配给Roles,并有效地完成我上面描述的事情呢?

根据数据库模式显示,您可以将声明分配给角色,并且可以将角色分配给用户。因此,理论上,将 Claim "AddOrEditOrder" 添加到 "Manager" 和 "CustomerRep" 角色会做我想做的事情。然后我将 [Authorize("AddOrEditOrder")] 放在 OrdersController 的 Post 操作上,中提琴,它会起作用!...对吗?

如果没有严重的 sanfus,我可以这样使用 Claims & Roles 吗?

编辑:使用政策,而不是声明

As the helpful answer from @Ruard-van-Elburg suggests, I mistakenly wrote "Claims" where I meant "Policies". Substitute one for the other, and everything I said works. Another word for "Rights" is "Permissions", and there are some very useful suggestions in this related question and its top answer:

这不是声明的使用方式。声明应该模拟用户的身份,而不是权限。请阅读文章 Identity vs Permissions 以获得一些解释。

在您的情况下,您可以使用 policies

public void ConfigureServices(IServiceCollection services)
{
    services.AddAuthorization(options =>
    {
        options.AddPolicy("AddOrEditOrder", policy =>
            policy.RequireRole("Manager", "CustomerRep"));
    });
}

并使用相同的属性:

[Authorize("AddOrEditOrder")]

还有许多其他选项可以添加 authorization. You can also take a look at the PolicyServer