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.
