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

如何使用新版Microsoft.IdentityModel.JsonWebTokens创建JwtSecurityToken?

迁移到Microsoft.IdentityModel.JsonWebTokens的代码示例

下面是把你的原有代码迁移到Microsoft.IdentityModel.JsonWebTokens的实现,核心改动很小:

using System.Text;
using System.Collections.Generic;
using System.Security.Claims;
using Microsoft.IdentityModel.Tokens;
using Microsoft.IdentityModel.JsonWebTokens;

var data = Encoding.UTF8.GetBytes("SomeStringFromConfig1234");
var securityKey = new SymmetricSecurityKey(data);

var claims = new List<Claim>
{
    new Claim(ClaimTypes.Name, "Testuser"),
    new Claim(ClaimTypes.GroupSid, "Tenant1"),
    new Claim(ClaimTypes.Sid, "3c545f1c-cc1b-4cd5-985b-8666886f985b")
};

var signingCredentials = new SigningCredentials(securityKey, SecurityAlgorithms.HmacSha256Signature);

// 使用JsonWebTokenHandler直接生成令牌字符串
var tokenHandler = new JsonWebTokenHandler();
var tokenString = tokenHandler.CreateToken(new SecurityTokenDescriptor
{
    Issuer = "MyIssuer",
    Audience = "MyAudience",
    Claims = claims.ToDictionary(c => c.Type, c => (object)c.Value),
    Expires = DateTime.UtcNow.AddMinutes(120),
    SigningCredentials = signingCredentials
});

关键改动说明:

  1. 替换令牌处理器:用JsonWebTokenHandler替代原有的JwtSecurityTokenHandler,这是新包的核心处理类
  2. 简化令牌生成流程:直接调用CreateToken方法,传入SecurityTokenDescriptor对象配置令牌参数,无需先实例化JwtSecurityToken再手动序列化
  3. 依赖类型复用:SymmetricSecurityKey、SigningCredentials、SecurityAlgorithms这些类型依然来自Microsoft.IdentityModel.Tokens包,不需要替换
  4. 声明处理:声明(Claim)类型保持不变,仅需将列表转换为字典传入SecurityTokenDescriptor的Claims属性

内容的提问来源于stack exchange,提问作者FranzHuber23

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.29 09:02:29