使用JwtSecurityTokenHandler读取JWT令牌时部分信息丢失的问题
问题
在API认证中使用Microsoft.IdentityModel.JsonWebTokens 7.6.0库的JwtSecurityTokenHandler时遇到异常:创建令牌时已写入所需信息,通过CreateToken(tokenDescriptor)可成功生成,使用WriteToken(token)转换为字符串后,在jwt.io验证仍包含完整信息,但调用ReadToken或ReadJwtToken读取令牌时,payload中的部分信息(包括过期时间)丢失,导致令牌验证受阻。
以下是相关代码:
public string GenerateToken(string userId, string databaseId) { var tokenHandler = new JwtSecurityTokenHandler(); var key = Encoding.ASCII.GetBytes(_secretKey); var tokenDescriptor = new SecurityTokenDescriptor { Subject = new ClaimsIdentity(new[] { new Claim(ClaimTypes.Name, userId), new Claim("databaseId", databaseId) }), Expires = DateTime.UtcNow.AddDays(7), SigningCredentials = new SigningCredentials(new SymmetricSecurityKey(key), SecurityAlgorithms.HmacSha256Signature) }; var token = tokenHandler.CreateToken(tokenDescriptor); // 测试输出 Console.WriteLine(token); // 返回 {"alg":"HS256","typ":"JWT"}.{"unique_name":"13","databaseId":"2","nbf":1717747146,"exp":1718351946,"iat":1717747146} var tokenString = tokenHandler.WriteToken(token); Console.WriteLine(tokenString); // 返回 eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJ1bmlxdWVfbmFtZSI6IjEzIiwiZGF0YWJhc2VJZCI6IjIiLCJuYmYiOjE3MTc3NDcxNDYsImV4cCI6MTcxODM1MTk0NiwiaWF0IjoxNzE3NzQ3MTQ2fQ.4ZRS5RYXzir5mwz8yXlu97y3H29BeJFtC3-3RQ8p0vw SecurityToken newToken = tokenHandler.ReadJwtToken(tokenString); Console.WriteLine(newToken); // 返回 {"alg":"HS256"}.{"unique_name":"13","nbf":1717747146,"iat":1717747146} return tokenHandler.WriteToken(token); }
处理结果
原本希望仅使用微软官方库解决问题,最终因问题无法排查解决,换用了其他第三方库。
内容的提问来源于stack exchange,提问作者SpozeR
相关产品推荐
相关产品推荐

