在 ASP.NET 核心 MVC 中使用声明或仅使用角色

Using claims or just roles in ASP.NET Core MVC

在我的ASP.NETCore MVC项目中,我有这样一个场景:一个管理员可以在web应用程序中做任何事情,你可以称之为超级管理员,而且只有一个用户。这个“超级”管理员可以添加其他更受限制的管理员,例如这些管理员不能创建管理员类型的用户,或者不能看到一些信息。

从技术上讲,它们有很多共同点。我已经有很多角色类型,所以我不想创建另一个称为超级经理的角色类型,我将只创建一个用户。那么在这种情况下我应该使用声明吗?还是只创建两个角色更好?我知道它会不那么复杂,但我想知道最佳实践。

我是 ASP.NET Core 的新手,所以非常感谢可以帮助我的示例或文章,谢谢!

在我看来,通过声明或角色声明添加超级管理员没有区别,角色声明也是一种声明。

在我看来,如果你没有特殊需求需要通过声明添加用户超级管理员,最好的方法是使用声明。由于您可以直接使用 [Authorize(Roles = "Superadmin")] 而无需编写其他代码来使用身份工厂添加声明。

如果你想通过声明添加超级管理员,你应该像这样使用 UserClaimsPrincipalFactory and add the claims policy like this article 显示。

我建议如果你需要创建很多角色,你使用 Claims-based authorization .

您可以使用 Authorize[Roles = "Admin"] 属性 或者您可以创建自定义 AuthorizeAttribute,例如:

  public class AuthorizeAccess : AuthorizeAttribute, IAuthorizationFilter
    {
        public string UniqueCode { get; set; }

        public void OnAuthorization(AuthorizationFilterContext context)
        {
            if (!context.HttpContext.User.HasClaim(c => c.Type == "CustomAccess" && c.Value.Equals(UniqueCode)))
            {
                // Redirect AccessDenied when the claim not exist.
                context.Result = new RedirectToPageResult("/AccessDenied");
                return;
            }
        }
    }

我们可以使用它

[AuthorizeAccess(UniqueCode = "EDIT")]
public class IndexModel : PageModel
{
         ....
}

在这种情况下,您需要在登录访问中加载声明列表

identity.AddClaim(new Claim("CustomAccess", "HOME_PAGE"));
identity.AddClaim(new Claim("CustomAccess", "EDIT"));
identity.AddClaim(new Claim("CustomAccess", "DELETE"));
identity.AddClaim(new Claim("CustomAccess", "INSERT"));