简体   繁体   中英

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. 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.

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.

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.

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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