使用Microsoft.IdentityModel.Tokens创建无过期JWT的技术问题
使用Microsoft.IdentityModel.Tokens生成无过期时间的JWT令牌
可以通过CreateJwtSecurityToken实现,但不能仅通过忽略expires参数达成——因为默认情况下,SecurityTokenDescriptor会自动为Expires属性赋值(通常是当前时间加1小时),导致生成的JWT依然带有exp声明。
正确的做法是显式将Expires设置为null,这样生成的令牌就不会包含过期声明,实现无过期效果。示例代码如下:
var tokenHandler = new JwtSecurityTokenHandler(); // 替换为你的实际密钥,建议使用更长更安全的密钥 var securityKey = new SymmetricSecurityKey(Encoding.UTF8.GetBytes("your-strong-secret-key")); var tokenDescriptor = new SecurityTokenDescriptor { Subject = new ClaimsIdentity(new List<Claim> { new Claim(ClaimTypes.NameIdentifier, "user123"), new Claim(ClaimTypes.Email, "user@example.com") }), Expires = null, // 关键:显式禁用过期时间 SigningCredentials = new SigningCredentials(securityKey, SecurityAlgorithms.HmacSha256) }; JwtSecurityToken jwtToken = tokenHandler.CreateJwtSecurityToken(tokenDescriptor); string tokenString = tokenHandler.WriteToken(jwtToken);
需要注意:部分JWT验证逻辑可能强制要求令牌包含exp声明,所以生成无过期令牌前,请确认接收方的验证规则是否允许这种格式,避免出现验证失败的情况。
内容的提问来源于stack exchange,提问作者M. Gar
相关产品推荐
相关产品推荐

