使用 RSA 生成 JWT 令牌时的安全处理错误

Safe handle error on generating JWT token with RSA

我正在尝试使用 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;
}

为 jwt 使用这个 nuget 库。 System.IdentityModel.Tokens.Jwt

我在使用 HMACSHA256 对称密钥签名生成令牌时没有遇到这个问题。

最新版本 (5.4.0) 库中没有出现这种情况 System.IdentityModel.Tokens.Jwt。

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