How to validate JWT token in NET 6

Viewed 68

Im using this website to generate a token: https://www.javainuse.com/jwtgenerator enter image description here

infomation: key: "8f1639ff241aee31bed2e148ca5635623483f132" Algorithm: HS256

My code in net 6:

public int? ValidateJwtToken(string token)
{
    if (token == null)
      return null;

    var tokenHandler = new JwtSecurityTokenHandler();
    var pubKey = "8f1639ff241aee31bed2e148ca5635623483f132";
    var hmac = new HMACSHA256(Encoding.UTF8.GetBytes(pubKey));
    var securityKey = new SymmetricSecurityKey(hmac.Key);
           
     try
     {
        tokenHandler.ValidateToken(token, new TokenValidationParameters
        {
            TryAllIssuerSigningKeys = true,
            IssuerSigningKey = securityKey,
            IssuerSigningKeys = new List<SymmetricSecurityKey>() { securityKey},
            ValidateIssuer = false,
            ValidateAudience = false,
            ValidateLifetime = false,
            SignatureValidator = (token, parameters) => new JwtSecurityToken(token)

            }, out SecurityToken validatedToken);

             var jwtToken = (JwtSecurityToken)validatedToken;
             var userId = int.Parse(jwtToken.Claims.First(x => x.Type == "id").Value);

                // return user id from JWT token if validation successful
                return userId;
            }
            catch
            {
                // return null if validation fails
                return null;
            }
        }

So The error here:

Microsoft.IdentityModel.Tokens.SecurityTokenSignatureKeyNotFoundException: 'IDX10503: Signature validation failed. Token does not have a kid. Keys tried: '[PII of type 'System.Text.StringBuilder' is hidden. For more details, see https://aka.ms/IdentityModel/PII.]'. Number of keys in TokenValidationParameters: '2'. Number of keys in Configuration: '0'. Exceptions caught: '[PII of type 'System.Text.StringBuilder' is hidden. For more details, see https://aka.ms/IdentityModel/PII.]'. token: '[PII of type 'System.IdentityModel.Tokens.Jwt.JwtSecurityToken' is hidden. For more details, see https://aka.ms/IdentityModel/PII.]'.'

If I change tokenHandler.ValidateToken to

tokenHandler.ValidateToken(token, new TokenValidationParameters
{
    TryAllIssuerSigningKeys = true,
    IssuerSigningKey = securityKey,
    IssuerSigningKeys = new List<SymmetricSecurityKey>() { securityKey},
    ValidateIssuer = false,
    ValidateAudience = false,
    ValidateLifetime = false,
    SignatureValidator = (token, parameters) => new JwtSecurityToken(token)

  }, out SecurityToken validatedToken);

The validate alway true.

1 Answers

The site you provided for us is not working when I post my solution. But It worked at the beginning.

I copy the token from the https://www.javainuse.com/jwtgenerator and paste to https://jwt.io. Then I get Invalid Signature error like below.

enter image description here

So the root cause maybe related to the generated jwt token. Your code might be no problem.

Suggestion:

I suggest you should generate jwt token by yourself and valid it.

How to validate a JWT token

Related