Owin claims - Add multiple ClaimTypes.Role

Jeppe Christensen picture Jeppe Christensen · Mar 14, 2017 · Viewed 25k times · Source

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.

Answer

Parameswar Rao picture Parameswar Rao · Mar 14, 2017

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");