Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Get Claims, Permissions and Roles from JWT Token

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?

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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

>Solution :

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
    }
}
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading