简体   繁体   English

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

[英]ASP.NET Identity “Role-based” Claims

I understand that I can use claims to make statements about a user: 我知道我可以使用声明来声明用户:

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

But how should I store "role-based" claims? 但是,我应该如何存储“基于角色”的声明? For example: 例如:

The user is a super administrator. 用户是超级管理员。

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

The value parameter "true" feels completely redundant. 值参数“true”感觉完全冗余。 How else can this statement be expressed using claims? 如何使用索赔表达此陈述?

This is already done for you by the framework. 这已经由框架为您完成。 When user is logged in, all user roles are added as claims with claims type being ClaimTypes.Role and values are role name. 当用户登录时,所有用户角色都将添加为声明类型为ClaimTypes.Role声明。角色和值是角色名称。

And when you execute IPrincipal.IsInRole("SuperAdmin") the framework actually checks if the claim with type ClaimTypes.Role and value SuperAdmin is present on the user. 当您执行IPrincipal.IsInRole("SuperAdmin") ,框架实际上会检查用户是否存在类型为ClaimTypes.Role和值为SuperAdmin

So don't need to do anything special. 所以不需要做任何特别的事情。 Just add a user to a role. 只需将用户添加到角色即可。

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

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

You need to specify the Role in a claim with a type of ClaimsType.Role and then specify the claim type that contains the role in the ClaimsIdentity as shown below. 您需要在声明中使用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);

This will then allow you to use the [Authorize(Roles = "SuperAdmin")] attribute in your controllers. 这将允许您使用控制器中的[Authorize(Roles = "SuperAdmin")]属性。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM