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

如何在C#中为JWT Token添加指定字段?

C#控制台生成指定格式JWT Token示例

以下是修改后的完整代码,可直接生成符合你期望Payload格式的JWT Token:

using System;
using System.IdentityModel.Tokens.Jwt;
using System.Text;
using Microsoft.IdentityModel.Tokens;

namespace JwtGeneratorDemo
{
    class Program
    {
        static void Main(string[] args)
        {
            Console.WriteLine("生成指定格式的JWT Token:");
            
            // 注意:实际生产环境请勿硬编码密钥,建议从配置文件或安全存储读取
            string key = "your_secure_secret_key_here";
            var securityKey = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(key));
            var credentials = new SigningCredentials(securityKey, SecurityAlgorithms.HmacSha256Signature);

            // 构建符合要求的Payload
            var currentUtcTime = DateTime.UtcNow;
            var payload = new JwtPayload
            {
                { "schema", "your_schema_value" },
                { "majver", 1 },
                { "minver", 0 },
                { "sub", "user_subject_identifier" },
                { "scope", "read,write" },
                { "iss", "token_issuer_name" },
                { "exp", currentUtcTime.AddHours(1) }, // 过期时间:当前UTC时间+1小时
                { "nbf", currentUtcTime }, // 生效时间:当前UTC时间
                { "iat", currentUtcTime }, // 签发时间:当前UTC时间
                { "jti", Guid.NewGuid().ToString() }, // 生成唯一Token标识
                { "emp_id", "employee_unique_id" },
                { "act", new 
                  { 
                      typ = "action_type_value", 
                      sub = "action_subject_value" 
                  } 
                }
            };

            var secToken = new JwtSecurityToken(credentials, payload);
            var handler = new JwtSecurityTokenHandler();
            var tokenString = handler.WriteToken(secToken);

            Console.WriteLine("\n生成的Token:");
            Console.WriteLine(tokenString);

            // 可选:解析Token验证Payload格式
            Console.WriteLine("\n解析后的Payload:");
            var parsedToken = handler.ReadJwtToken(tokenString);
            Console.WriteLine(parsedToken.Payload.SerializeToJson());

            Console.ReadLine();
        }
    }
}

关键修改说明

  1. 日期字段处理:exp(过期)、nbf(生效)、iat(签发)均使用UTC时间,避免时区差异导致的Token验证问题,exp可根据业务需求调整过期时长。
  2. 嵌套对象act:直接通过匿名类型添加,JWT处理库会自动序列化为嵌套JSON结构。
  3. 唯一标识jti:用Guid.NewGuid()生成全局唯一字符串,确保每个Token的标识不重复。
  4. 标准与自定义字段兼容:sub、iss等是JWT标准声明字段,schema、emp_id等自定义字段直接以键值对形式添加即可。

依赖安装

需要通过NuGet安装System.IdentityModel.Tokens.Jwt包,可使用以下命令:

Install-Package System.IdentityModel.Tokens.Jwt

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.20 16:15:08