如何使用XML格式RSA私钥生成带kid头部声明的JWT令牌
解决方案
kid(密钥ID)是JWT头部用于标识签名所用密钥的字段,你的代码中没有生成该字段,是因为初始化RsaSecurityKey时未指定KeyId属性,系统默认不会自动写入该字段。
方法1:直接设置SecurityKey的KeyId属性(推荐)
这是最符合规范的实现方式,配置后系统会自动把KeyId的值写入JWT的kid头部,修改后的完整代码如下:
public async Task<IActionResult> Generate() { var rsa = RSA.Create(); string key = await System.IO.File.ReadAllTextAsync(options.PrivateKeyFilePath); rsa.FromXmlString(key); // 初始化RsaSecurityKey时指定KeyId,值可自定义为你的密钥唯一标识 var rsaKey = new RsaSecurityKey(rsa) { // 可自定义kid的值,比如用你分配的密钥唯一ID KeyId = "rsa-key-20240501" // 如果需要生成基于公钥哈希的标准kid,可自行计算公钥指纹赋值到此处 }; var credentials = new SigningCredentials(rsaKey, SecurityAlgorithms.RsaSha256); var jwt = new JwtSecurityToken( new JwtHeader(credentials), new JwtPayload( "webapi", "webapi", new List<Claim>(), DateTime.UtcNow, DateTime.UtcNow.AddHours(3) ) ); string token = new JwtSecurityTokenHandler().WriteToken(jwt); return Ok(new { Token = token }); }
方法2:手动往JwtHeader添加kid字段
如果有特殊需求不想修改SecurityKey的配置,也可以直接在构造JwtHeader时手动插入kid字段:
var credentials = new SigningCredentials(new RsaSecurityKey(rsa), SecurityAlgorithms.RsaSha256); var header = new JwtHeader(credentials); // 手动添加kid字段 header["kid"] = "rsa-key-20240501"; var jwt = new JwtSecurityToken( header, new JwtPayload( "webapi", "webapi", new List<Claim>(), DateTime.UtcNow, DateTime.UtcNow.AddHours(3) ) );
结果验证
生成令牌后解析JWT,头部会出现以下格式的内容:
{ "alg": "RS256", "typ": "JWT", "kid": "rsa-key-20240501" }
内容的提问来源于stack exchange,提问作者shakila sameera
相关产品推荐
相关产品推荐

