我明白我可以使用声明(claims)来陈述关于用户的信息:
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"));
使用声明语句,如何在不使用"value"参数为"true"的情况下表达同样的意思。
IPrincipal.IsInRole("xx")
方法在查找匹配声明时,不一定使用ClaimTypes.Role
。例如,在进行 Windows 身份验证后,您可能会收到WindowsPrincipal
,它实际上使用ClaimTypes.GroupSid
来指定角色。因此,请使用ClaimsIdentity.RoleClaimType
属性来代替。 - RobIsInRole
是IPrincipal
接口的一部分(https://referencesource.microsoft.com/#mscorlib/system/security/principal/iprincipal.cs,c78f7d29e063c03c,references),任何实现它的对象都可以执行其功能。在这里,我们谈论的是ClaimsPrincipal
(https://referencesource.microsoft.com/#mscorlib/system/security/claims/ClaimsPrincipal.cs,765),它使用声明来定义角色。如果您在 MVC 应用程序中的身份框架中获得了WindowsPrincipal
,那么您正在做一些非常错误的事情。 - trailmaxWindowsPrincipal
派生自 .Net 4.5 中的ClaimsPrincipal
,我相信如果您配置应用程序使用 Windows 集成身份验证,则在 ASP.Net Web API(和 MVC?)中将收到WindowsPrincipal
。但这里的重点是使用特定的ClaimTypes.Role
来驱动ClaimsPrincipal.IsInRole
是不正确的。请参见 ClaimsPrincipal.IsInRole。 - RobRoleClaimType
来测试包含的标识是否具有所需的声明。您可以在ClaimsIdentity的参考源代码中看到,该属性的后备字段默认为ClaimsType.Role
,但是WindowsIdentity
构造函数将ClaimTypes.GroupSid
传递给此字段。我不知道其根本原因,但这就是为什么最好使用RoleClaimType
属性的原因。 - Rob