Home > Software engineering >  Get Claims, Permissions and Roles from JWT Token
Get Claims, Permissions and Roles from JWT Token

Time:10-10

I am implementing a /refresh-token endpoint in my .NET 6 application. The Controller takes the JWT Token from the headers, decode it and issue new token.

The type of Itemvalue for role and permissions is Newtonsoft.Json.Linq.JArray.

Am I doing it properly or there is a better solution?

        var handler = new JwtSecurityTokenHandler();
        var oldTokenDecoded = handler.ReadJwtToken(oldToken);


        List<string> rolesDecoded = new List<string>();
        List<string> permissionsDecoded = new List<string>();
        string UsernameDecoded = "";
        string UserIDDecoded = "";

        foreach(var item in oldTokenDecoded.Payload)
        {
            if(item.Key == "role")
            {
                rolesDecoded = JsonConvert.DeserializeObject<List<string>>(item.Value.ToString());
            }

            if(item.Key == "permissions")
            {
                permissionsDecoded = JsonConvert.DeserializeObject<List<string>>(item.Value.ToString());
            }

            if(item.Key == "Username")
            {
                UsernameDecoded = item.Value.ToString();
            }

            if(item.Key == "UserID")
            {
                UserIDDecoded = item.Value.ToString();
            }
            
        }
        
        var jwtToken = JWTBearer.CreateToken(
                signingKey: "token",
                expireAt: DateTime.UtcNow.AddDays(1),
                claims: new[] { ("Username", UsernameDecoded), ("UserID", UserIDDecoded) },
                roles: rolesDecoded,
                permissions: permissionsDecoded);```

CodePudding user response:

Use .Claims to iterate through claims instead of your current approach:

List<string> roles = new List<string>();
List<string> permissions = new List<string>();
string username;
string userId;
foreach(var item in oldTokenDecoded.Claims)
{
    switch (item.Type)
    {
        case "role":
            roles.Add(item.Value);
            break;
        case "permission":
            permissions.Add(item.Value);
            break;
        case "Username":
            username = item.Value;
            break;
        case "UserID":
            userId = item.Value;
            break;
        // etc
    }
}
  • Related