Igor Cova
Igor Cova

Reputation: 3514

C# .net Core JWT Token Get values

I have some Claim from JwtSecurityToken that look like this:

{  
   "profile":{  
      "roles":{  
         "Rolename":{  
            "Type":27
         }
      }
   }
}

I need get value Type (now it's 27)

Rolename it's name the role - it can be different (and there can be more than one role)

Task for me it get name the role and get value of Type

How I do it:

JwtSecurityTokenHandler handler = new JwtSecurityTokenHandler();
JwtSecurityToken tokenS = handler.ReadToken(token) as JwtSecurityToken;
string profile = tokenS.Claims.First(claim => claim.Type == "profile").Value;
JObject o = JObject.Parse(profile);
string cardType = o.SelectToken("$.roles." + "Rolename" + ".Type").ToString();

It's work well, but I don't know how to take rolename and how to be when I'll have more that one role

Upvotes: 1

Views: 4056

Answers (2)

AlbertK
AlbertK

Reputation: 13167

If there is always one role you can do this:

JObject o = JObject.Parse(profile);
var role = ((JObject)o["roles"]).Properties().First();

string roleName = role.Name;

int cardType = (int)role.Value["Type"];

if there can be several roles you can loop through an array of JProperty like this:

var roles = ((JObject)o["roles"]).Properties();
foreach (var role in roles)
{
    string roleName = role.Name;

    int cardType = (int)role.Value["Type"];
}

Upvotes: 1

Phael
Phael

Reputation: 99

Roles as in plural should be an array. Then you can get all the values in that array the way you want with a loop. Example:

var roleTypes = new List<string>();
foreach (var role in profile.roles)
{
    //populate a list
}

Upvotes: 0

Related Questions