【发布时间】:2019-10-22 15:41:24
【问题描述】:
我正在尝试使用 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 的对称密钥签名生成令牌时,我没有遇到此问题。
【问题讨论】:
-
你试过不使用block吗?
-
@MuhammadHannan 是的。它也给出了同样的错误。
标签: c# .net jwt rsa identitymodel