c# – Updating Micorsoft.IdentityModel.Tokens from 6.27 To 8.15


I am attempting to update all of our out of date Nuget packages, one being the identity model. We use this for jwt token generation and validation. I am having a few issues and I was wondering if someone can point in the right direction of changes between all the versions so I can try and figure out what needs updating.

Issue 1

I have a small tool in my testing environment which I can use to generate tokens, however it seems that my security key is too small for HmacSha256Signature. When this was created over 2 years ago, was our secret just way to small. This is the code we have to create a new tokenenter image description here

I know my Secrect from converting it from base64 is 24 bits. Does anybody know if this was changed or was it a flaw that Microsoft subsequently fixed. Would it be best to convert the key (which is in our api web config file) to a base64 string then we convert that to bytes? Example below:

// Secret is a base64 string
    SymmetricSecurityKey securityKey = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(Secret));
    ClaimsIdentity claimsIdentity = new ClaimsIdentity(Claims);
    JwtSecurityTokenHandler handler = new JwtSecurityTokenHandler();
    SecurityTokenDescriptor descriptor = new SecurityTokenDescriptor
    {
        Audience = Audience,
        Issuer = Issuer,
        Subject = claimsIdentity,
        SigningCredentials = new SigningCredentials(securityKey, SecurityAlgorithms.HmacSha256Signature),
        IssuedAt = DateTime.UtcNow
    };
    
    if (ExpiryDate.HasValue)
    {
        descriptor.Expires = ExpiryDate;
    }
    else
    {
        handler.SetDefaultTimesOnTokenCreation = false;
    }
    
    JwtSecurityToken token = handler.CreateJwtSecurityToken(descriptor);
    return handler.WriteToken(token);

I believe that Encoding.UTF8.GetBytes(Secret) produces 32 bits which I think will help, but I am unsure if this is the correct way to go.

Issue 2

While trying to test our API, we keep failing on the validation of the token being passed through in particular when trying to get the claims principle.enter image description here

The error message we keep getting is the kid is missing. I am also assuming the fact we cannot seem to create a token due to the security key being to small we may also have this problem here as well. I am contemplating doing something like this in the generation of the token so this part needs not to be changed.

SymmetricSecurityKey securityKey = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(Secret));
securityKey.KeyId = NewID;
ClaimsIdentity claimsIdentity = new ClaimsIdentity(Claims);

This way I am hoping that the security key now has a key long enough and a kid. Can someone confirm if this is correct or can someone please point me in the right direction.

Thank you

Leave a Reply

Your email address will not be published. Required fields are marked *