首页 > 解决方案 > 使用 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 的对称密钥签名生成令牌时,我没有遇到这个问题。

标签: c#.netjwtrsaidentitymodel

解决方案


System.IdentityModel.Tokens.Jw这在库t的最新版本(5.4.0)中没有发生。

早些时候我使用的是库的 5.0.0 版本。


推荐阅读