Owin claims - Add multiple ClaimTypes.Role

霸气de小男生 提交于 2021-01-16 08:11:58

问题


I have an application in which users can be assigned the following roles:

  • SuperAdmin
  • Admin
  • User

One user may have assigned two or more roles, eg. both SuperAdmin and User. My application uses claims, and therefore i want to authenticate user roles through claims too. like:

[Authorize(Roles="Admin")]

Unfortunately, i dont know how i can add multiple roles to my ClaimTypes.Role. I have the following code:

var identity = new ClaimsIdentity(new[] {
                new Claim(ClaimTypes.Name, name),
                new Claim(ClaimTypes.Email, email),
                new Claim(ClaimTypes.Role, "User", "Admin", "SuperAdmin")
        },
            "ApplicationCookie");

As you can see, i tried to add more roles for the sake of illustrating, but obviously its done in a wrong way, and therefore doesn't work. Any help is therefore much appreciated.


回答1:


A claims identity can have multiple claims with the same ClaimType. That will make it possible to use the HasClaim method for checking if a specific user role is present.

var identity = new ClaimsIdentity(new[] {
            new Claim(ClaimTypes.Name, name),
            new Claim(ClaimTypes.Email, email),
            new Claim(ClaimTypes.Role, "User"),
            new Claim(ClaimTypes.Role, "Admin"), 
            new Claim(ClaimTypes.Role,"SuperAdmin")
    },
        "ApplicationCookie");



回答2:


@Parameswar Rao explained well but in case of dynamic roles

For example a user object already has property role of type list like

then using localfunctions

  ClaimsIdentity getClaimsIdentity()
                {
                    return new ClaimsIdentity(
                        getClaims()
                        );

                   Claim[] getClaims()
                    {
                        List<Claim> claims = new List<Claim>();
                        claims.Add(new Claim(ClaimTypes.Name, user.UserName));
                        foreach (var item in user.Roles)
                        {
                            claims.Add(new Claim(ClaimTypes.Role, item));
                        }
                        return claims.ToArray();
                    }

                }
                    var tokenDescriptor = new SecurityTokenDescriptor
                    {


                        Subject = getClaimsIdentity()
                    }


来源:https://stackoverflow.com/questions/42791416/owin-claims-add-multiple-claimtypes-role

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