You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

使用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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.22 16:05:09