【问题标题】:ASP.NET Identity "Role-based" ClaimsASP.NET 身份“基于角色”的声明
【发布时间】:2015-04-09 06:00:23
【问题描述】:

我了解我可以使用声明来对用户进行陈述:

var claims = new List<Claim>();
claims.Add(new Claim(ClaimTypes.Name, "Peter"));
claims.Add(new Claim(ClaimTypes.Email, "peter@domain.com"));

但我应该如何存储“基于角色”的声明?例如:

用户是超级管理员。

claims.Add(new Claim("IsSuperAdmin, "true"));

值参数“true”感觉完全多余。这个陈述还能如何使用声明来表达?

【问题讨论】:

    标签: c# asp.net-web-api2 asp.net-identity claims-based-identity asp.net-authentication


    【解决方案1】:

    您可以使用 ClaimType Role 存储角色

    claims.Add(new Claim(ClaimTypes.Role, "SuperAdmin"));
    

    【讨论】:

    • 我在上面做了评论,但它也适用于这里:添加角色时使用ClaimsIdentity.RoleClaimType 属性会更可靠。
    • 如果有多个角色呢?
    • 逗号分隔?同一类型的多个索赔?其他?
    • @AlexanderChristov 具有相同类型的多个声明。
    【解决方案2】:

    框架已经为您完成了这项工作。当用户登录时,所有用户角色都作为声明添加,声明类型为ClaimTypes.Role,值为角色名称。

    当您执行IPrincipal.IsInRole("SuperAdmin") 时,框架实际上会检查用户上是否存在类型为ClaimTypes.Role 和值SuperAdmin 的声明。

    所以不需要做任何特别的事情。只需将用户添加到角色即可。

    【讨论】:

    • Role 类型的 Claims 和 AspNetRoles 表有什么关系?
    • @Tymski AspNetRoles 包含角色列表。当用户登录时,所有这些角色都作为ClaimTypes.Role 类型的声明添加到cookie 中。 cookie 中的声明是短暂的。数据库中的记录只是复制到 cookie 中。
    • 我应该指出IPrincipal.IsInRole("xx") 在搜索匹配声明时不一定使用ClaimTypes.Role。例如,您在进行 Windows 身份验证后可能收到的 WindowsPrincipal 实际上使用 ClaimTypes.GroupSid 来指定角色。而是使用 ClaimsIdentity.RoleClaimType 属性。
    • @Rob 上下文为王。 IsInRoleIPrincipal 接口 (referencesource.microsoft.com/#mscorlib/system/security/…) 的一部分,并且任何实现它的对象都可以做任何事情。这里我们讲ClaimsPrincipal (referencesource.microsoft.com/#mscorlib/system/security/claims/…) 并且它使用Claims来定义角色。如果你碰巧在 MVC 应用程序的 Identity 框架中得到 WindowsPrincipal,那么你做错了。
    • 嗨@trailmax。这有点深奥,但请注意ClaimsPrincipal.IsInRole() 使用属性RoleClaimType 来测试包含的身份是否具有所需的声明。您可以在 ClaimsIdentity 的参考源中看到,此属性的支持字段默认为 ClaimsType.Role,但 WindowsIdentity 构造函数为此字段传递 ClaimTypes.GroupSid。我不知道根本原因,但这就是为什么最好使用RoleClaimType 属性。
    【解决方案3】:

    您需要在类型为 ClaimsType.Role 的声明中指定角色,然后在 ClaimsIdentity 中指定包含该角色的声明类型,如下所示。

    var claimsIdentity = new ClaimsIdentity(new[]
    {
        new Claim(ClaimTypes.Email, "peter@domain.com"),
        new Claim(ClaimTypes.Name, "Peter"),
        new Claim(ClaimTypes.Role, "SuperAdmin"),
    },
    "ApplicationCookie", ClaimTypes.Email, ClaimTypes.Role);
    

    这将允许您在控制器中使用[Authorize(Roles = "SuperAdmin")] 属性。

    【讨论】:

      猜你喜欢
      • 2013-08-19
      • 1970-01-01
      • 2020-09-23
      • 1970-01-01
      • 1970-01-01
      • 2014-02-28
      • 1970-01-01
      • 2014-07-27
      • 2012-12-12
      相关资源
      最近更新 更多