ASP.NET Identity “Role-based” Claims

江枫思渺然 提交于 2019-11-30 06:27:16

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.

You can store roles using the ClaimType Role

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.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!