ASP.NET Core Identity Role, Claim and User

前端 未结 2 1327
星月不相逢
星月不相逢 2021-01-11 14:14

I am an ASP.NET Core beginner. I\'m stuck in role, claim and user relationship.

I have a user Ben, user belongs to Admin role.

2条回答
  •  傲寒
    傲寒 (楼主)
    2021-01-11 14:41

    I have had to deal with this issue recently and to solve the problem of locating Users by a particular Claim that came from a Role is to create a new Claim object with the values from the Role Claim:

    var role = await roleManager.FindByNameAsync(yourRoleName);
    if(role != null)
    {
        var roleClaims = await roleManager.GetClaimsAsync(role);
        if(roleClaims != null && roleClaims.Count() > 0)
        {
            foreach(var claim in roleClaims.ToList())
            {
                var users = await userManager.GetUsersForClaimAsync(new Claim(claim.Type, claim.Value));
                if(users != null && users.Count() > 0)
                {
                    foreach(var user in users.ToList())
                    {
                       //This is an example of only removing a claim, but this is the
                       //area where you could remove/add the updated claim
                       await userManager.RemoveClaimAsync(user, new Claim(claim.Type, claim.Value));
                    }
                }
            }
        }
    }
    

    This allowed me to Update/Delete a role with claims and pass those changes to the Users to be Re-Issued/Removed that were assigned the roles and claims. However, I am still looking for something more elegant/easier with less code.

提交回复
热议问题