c# - 使用 RSA 生成 JWT 令牌时出现安全处理错误
问题描述
我正在尝试使用 RSA 算法生成 JWT toekn 进行签名。但是我System.ObjectDisposedException: 'Safe handle has been closed'
在使用这种方法将令牌转换为 json 格式时遇到了这个异常。
jwtToken = handler.WriteToken(token);
下面是用于生成 jwt 的代码。
public static string GetRsaToken()
{
string jwtToken;
RsaSecurityKey securityKey;
using (RSA privateRsa = RSA.Create())
{
var privateKeyXml = File.ReadAllText("../../private-key.xml");
privateRsa.FromXmlString(privateKeyXml);
securityKey = new RsaSecurityKey(privateRsa);
SecurityTokenDescriptor descriptor = new SecurityTokenDescriptor
{
Audience = "Noob",
Issuer = "Saibot",
Subject = new ClaimsIdentity(new[] {
new Claim(ClaimTypes.Name, ""),}),
Expires = DateTime.UtcNow.AddMinutes(30),
SigningCredentials = new SigningCredentials(securityKey,SecurityAlgorithms.RsaSha256)
};
JwtSecurityTokenHandler handler = new JwtSecurityTokenHandler();
JwtSecurityToken token = handler.CreateJwtSecurityToken(descriptor);
jwtToken = handler.WriteToken(token); // exception on this line
}
return jwtToken;
}
将此 nuget 库用于 jwt 。System.IdentityModel.Tokens.Jwt
使用带有 HMACSHA256 的对称密钥签名生成令牌时,我没有遇到这个问题。
解决方案
System.IdentityModel.Tokens.Jw
这在库t的最新版本(5.4.0)中没有发生。
早些时候我使用的是库的 5.0.0 版本。
推荐阅读
- java - 在处理 3 上平滑 kinect 的用户地图
- python - 具有多个时间戳的日志记录格式?
- vue.js - Vuejs跨行匹配某些条件
- sapui5 - 承诺不起作用(对我来说)
- javascript - Adobe Acrobat - 用另一个选项填充下拉列表或列表
- javascript - Twig JS (gulp-twig) - 考虑 DRY 原则遍历大型数据结构
- python-3.x - 'var' 未在'for' 循环中定义
- symfony - TinyMCE 菜单不会粘在工具栏上
- javascript - 使用新用户输入重复通过 Firebase 显示的数据
- python - 如何获取和修改嵌套字典的值?