Sri Harsha Velicheti
Sri Harsha Velicheti

Reputation: 497

Not able to retrieve roles from GenericIdentity

I am setting up a GenericPrincipal adding a GenericIdentity & roles to it, but when I try to retrieve roles from it I am getting nothing. However, if I call Principal.IsInRole, it returns the correct value.

What am I missing?

Example: https://dotnetfiddle.net/Uan3ru

var identity = new GenericIdentity("Test", "Test");
var pricipal = new GenericPrincipal(identity, new[] { "Role1", "Role2" });
var cls = identity.Claims
                  .Where(c => c.Type == ClaimTypes.Role)
                  .Select(c => c.Value);
foreach(var c in cls)
{
    Console.WriteLine(c);
}
Console.WriteLine("complete");

Upvotes: 2

Views: 2508

Answers (1)

Alexander
Alexander

Reputation: 2318

In your code, you're adding the roles to the GenericPrincipal object, not the GenericIdentity object.

Therefore, the identity object doesn't have any role claims associated with it, whereas the principal object does.


Getting Roles From GenericPrincipal

You should be able to get the roles from the GenericPrincipal object like so:

var identity = new GenericIdentity("Test", "Test");
var principal = new GenericPrincipal(identity, new[] { "Role1", "Role2" });

// We need to get the claims associated with the Principal instead of the Identity
var roles = principal.Claims
                     .Where(c => c.Type == ClaimTypes.Role)
                     .Select(c => c.Value);

Console.WriteLine("Roles associated with the GenericPrincipal:");
foreach(var role in roles)
{
    Console.WriteLine(role);
}

Example: https://dotnetfiddle.net/wCxmIR


Getting Roles From GenericIdentity

If you need to track roles for a specific GenericIdentity object, you'll have to explicitly add the role claims to the instance. Then, you can get the roles from the identity object like so:

var roles = new[] { "Role1", "Role2" };
var identity = new GenericIdentity("Test", "Test");

// Explicitly add role Claims to the GenericIdentity
foreach (var role in roles)
{
    identity.AddClaim(new Claim(ClaimTypes.Role, role));
}

Console.WriteLine(String.Empty);
Console.WriteLine("All Claims associated with the GenericIdentity:");
foreach (var claim in identity.Claims)
{
    Console.WriteLine(claim);
}

Upvotes: 6

Related Questions