ASP.NET标识"基于角色"的声明

Dav*_*New 18 c# claims-based-identity asp.net-authentication asp.net-identity asp.net-web-api2

我知道我可以使用声明来声明用户:

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

但是,我应该如何存储"基于角色"的声明?例如:

用户是超级管理员.

claims.Add(new Claim("IsSuperAdmin, "true"));
Run Code Online (Sandbox Code Playgroud)

值参数"true"感觉完全冗余.如何使用索赔表达此陈述?

tra*_*max 27

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

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

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

  • 我应该指出`IPrincipal.IsInRole("xx")`在搜索匹配的声明时不一定使用`ClaimTypes.Role`.例如,您在执行Windows身份验证后可能会收到的"WindowsPrincipal"实际上使用`ClaimTypes.GroupSid`来指定角色.而是使用`ClaimsIdentity.RoleClaimType`属性. (4认同)
  • 嗨@trailmax.这有点深奥,但请注意[ClaimsPrincipal.IsInRole()](https://referencesource.microsoft.com/#mscorlib/system/security/claims/ClaimsPrincipal.cs,771)使用属性`RoleClaimType`来测试是否包含的身份具有所需的声明.您可以在ClaimsIdentity的引用源中看到此属性的支持字段默认为`ClaimsType.Role`,但`WindowsIdentity`构造函数为此字段传递`ClaimTypes.GroupSid`.我没有潜在的原因,但这就是为什么最好使用`RoleClaimType`属性. (3认同)

JCS*_*JCS 17

您可以使用ClaimType 角色存储角色

claims.Add(new Claim(ClaimTypes.Role, "SuperAdmin"));
Run Code Online (Sandbox Code Playgroud)

  • 我在上面做了评论,但它也适用于:在添加角色时使用`ClaimsIdentity.RoleClaimType`属性会更可靠. (3认同)
  • @AlexanderChristov同一类型的多个索赔. (2认同)