【问题标题】:Safe handle error on generating JWT token with RSA使用 RSA 生成 JWT 令牌时的安全处理错误
【发布时间】: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


【解决方案1】:

这不会在最新版本 (5.4.0) 库 System.IdentityModel.Tokens.Jwt 中发生。

之前我使用的是 5.0.0 版本的库。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2014-09-12
    • 1970-01-01
    • 2020-09-25
    • 2018-11-12
    • 2018-10-11
    • 2018-02-01
    • 2014-04-13
    相关资源
    最近更新 更多