Daniel Rabelo
Daniel Rabelo

Reputation: 29

How to read JWT token data with correct typing C#

I have a problem when reading the data saved in JWT, it is returning everything as a string, the correct thing would be to ensure that the returned values ​​are in the correct typing, for example the firstAccess field saves a boolean true or false but is returning a string "true" or "false", I believe that this is not a good practice. How can I ensure that it returns the correct typing?

JWT:

{
  "id": 1,
  "first_access": false,
  "nbf": 1722250357,
  "exp": 1722279157,
  "iat": 1722250357
}

C#:

 string token = HttpContext.Request.Headers["Authorization"].ToString().Replace("Bearer ", 
 "");
 var jwtToken = new JwtSecurityTokenHandler().ReadToken(token) as JwtSecurityToken;
 var firstAccess = jwtToken.Claims.FirstOrDefault(c => c.Type == "first_access")?.Value;

  if (firstAccess == "false")
      return BadRequest(new { message = ErrorMessages.ChangePasswordDenied });

Upvotes: 0

Views: 60

Answers (1)

sa-es-ir
sa-es-ir

Reputation: 5082

Claims are saved as Type/Value with the string type, Check

So there is no built-in way to get value as a boolean but you can map token payload to a custom model:

public class TokenPayloadModel
{
    public int Id { get; set; }

    [JsonPropertyName("first_access")]
    public bool FirstAccess { get; set; }

    //other props if needed
}

JwtSecurityToken has a property called RawPayload which we can use it to deserialize payload to our model:

var jwtToken = new JwtSecurityTokenHandler().ReadToken(token) as JwtSecurityToken;

var payload = JsonSerializer.Deserialize<TokenPayloadModel>(jwtToken.RawPayload);

if(payload?.FirstAccess)
{/*.....*/}

Upvotes: 1

Related Questions