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

时间:2019-06-07 06:37:17

标签: c# .net jwt rsa identitymodel

我正在尝试使用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使用对称密钥签名生成令牌时,我没有遇到这个问题。

1 个答案:

答案 0 :(得分:0)

在最新版本(5.4.0)库System.IdentityModel.Tokens.Jw t中未发生这种情况。

我以前使用的是该库的5.0.0版本。