Search code examples
c#.netjwtrsaidentitymodel

Safe handle error on generating JWT token with RSA


I am trying to generate JWT toekn with RSA algorithm for signing. But i am getting this exception System.ObjectDisposedException: 'Safe handle has been closed' on converting token to json format on this method.

jwtToken = handler.WriteToken(token);

Below is the code used for generating 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;
}

Using this nuget library for jwt . System.IdentityModel.Tokens.Jwt

I am not facing this issue while generating token using symmetric key signing with HMACSHA256.


Solution

  • This is not occurrinng in the latest version(5.4.0) the library System.IdentityModel.Tokens.Jwt.

    Earlier i was using the version 5.0.0 of the library.