0

I am getting back a JWT Token and I am using the System.IdentityModel.Tokens.Jwt to decode it so I can do validation on the token. I am able to strip the claims up to this point:

"{\"Account Manager\":\"true\",\"Administrator\":\"true\",\"Agent\":\"true\"}"

What I want is a List<string> that looks like this:

"Account Manager"
"Administrator"
"Agent"

What is the best way to handle this?

JuanR
  • 7,405
  • 1
  • 19
  • 30
Robert
  • 4,306
  • 11
  • 45
  • 95

2 Answers2

1

You need something like that:
var claims = Newtonsoft.Json.JsonConvert.DeserializeObject<List<string>>(data);

Y.Y.
  • 664
  • 1
  • 6
  • 22
1

@Kirk has a good point, how are you decoding the token? It's a little strange to be dealing with the JSON string directly. Normally you'd decode it into a JwtSecurityToken and access the ClaimsPrincipal and Claims under that (see here for some info that may help). Nevertheless, if you're determined to forge ahead, this is how I'd do it.

You have a bunch of key-value pairs, and I'm assuming you only want a list of the values where the claim value is true. I'd filter them as follows:

    string json = "{\"Account Manager\":\"true\",\"Administrator\":\"true\",\"Agent\":\"true\"}";

    var vals = JsonConvert.DeserializeObject<Dictionary<string, string>>(json);
    var list = vals.Where(v => v.Value == "true").Select(v => v.Key);

    Console.WriteLine(string.Join(Environment.NewLine, list));
pcdev
  • 2,852
  • 2
  • 23
  • 39