Search code examples
c#jwtwebapi

How to check generated JWT Token is valid or not, because in jwt.io website says invalid signature?


Generated JWT token is mentioned below. In jwt.io website says "invalid signature" :

"eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJ1c2VyTmFtZSI6ImFkbWluIiwiVFRJRCI6IjEyMzQ1NiIsImV4cCI6MTY4Nzc2Mzg3MiwiaXNzIjoic2FtcGxlIiwiYXVkIjoic2FtcGxlIn0.SUHPiDut67KM6LcbzYEF2CCMKiQlB5JMdiqqgIurJHg"

JWT token generation method

private static string generateJwtToken(string username, string password, string TTid)
{
   System.Net.ServicePointManager.ServerCertificateValidationCallback += (se, cert, chain, sslerror)    = { return true; };

     User user = new User();
     user.Username = username;
     user.Password = password;
     user.TTID = '123456';
     var tokenHandler = new JwtSecurityTokenHandler();
     var key = Encoding.ASCII.GetBytes("sample2023TTTTASASA");
     var securityKey = new SymmetricSecurityKey(key);
     var credentials = new SigningCredentials(securityKey, SecurityAlgorithms.HmacSha256);
     var secToken = new JwtSecurityToken(
     signingCredentials: credentials,
     issuer: "sample",
     audience: "sample",
     claims: new Claim[] { new Claim("userName", user.Username.ToString()), new Claim("TTID", '123456'), },
     expires: DateTime.UtcNow.AddDays(1));
     var handler = new JwtSecurityTokenHandler();
     return handler.WriteToken(secToken);
}

Solution

  • I think your token is OK. You just need to specify the key you used to sign the token with in the jwt.io page in the 'your-256-bit-secret' input box in 'Verify signature' part. So put 'sample2023TTTTASASA', it works.

    Reason:

    JWT token's signature is generated as a combination of header + payload + signing key.

    Header is the first part of the token to first dot, in this case 'eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9'.

    Payload is the second part - the part between dots eyJ1c2VyTmFtZSI6ImFkbWluIiwiVFRJRCI6IjEyMzQ1NiIsImV4cCI6MTY4Nzc2Mzg3MiwiaXNzIjoic2FtcGxlIiwiYXVkIjoic2FtcGxlIn0. This part contains the actual claims.

    Third part is the signature and it is generated with use of a specific algorithm, e.g. HMAC SHA256 with a signing key, in this case 'sample2023TTTTASASA' and this you need to specify on the page.