Skip to content

[Bug] Repeat generate jwt error Cannot access a disposed object. Object name: 'System.Security.Cryptography.RSABCrypt'. #3249

@LGinC

Description

@LGinC

Which version of Microsoft.IdentityModel are you using?
Note that to get help, you need to run the latest version.

Where is the issue?

  • M.IM.JsonWebTokens
  • M.IM.KeyVaultExtensions
  • M.IM.Logging
  • M.IM.ManagedKeyVaultSecurityKey
  • M.IM.Protocols
  • M.IM.Protocols.OpenIdConnect
  • M.IM.Protocols.SignedHttpRequest
  • M.IM.Protocols.WsFederation
  • M.IM.TestExtensions
  • M.IM.Tokens
  • M.IM.Tokens.Saml
  • M.IM.Validators
  • M.IM.Xml
  • S.IM.Tokens.Jwt
  • Other (please describe)

Is this a new or an existing app?

Repro

void Main()
{
	
	var privateKeyPem = """
	-----BEGIN PRIVATE KEY-----
	MIIEvQIBADANBgkqhkiG9w0BAQEFAASCBKcwggSjAgEAAoIBAQDYrYfdcnEec2pQ
	29fC397hsTE3gx+b6kqq9pcrE43UN2rrtD63ay6bDQ76ob3Nt6Nzyy/AS0I3eukm
	vrF/uv/K8EM0Z2ZlAkgDE3ZLw5iFueEbvG7CrWTaLx7fDbZPgp7AE4j34RQeOqkc
	0tQX/a8T3b/+gz5FWfQSp9SYXm69oD17cHE2VhN7ZOU+ap43Fo3JGfdSfGJUFFJV
	xee0KtZreVRaCpUw10rj9zlB0HxV+Hoqxhq+aU/EwWh4A3brYTj6vaIJs8a4RGr6
	IL9K0CRYPaLQhHrwHwOtRFgcT9dSJBzqllyUYqBhYPxju/X9GQuB1AJnVfrgbfts
	rb514g4NAgMBAAECggEABFT506dTVCLGFB5FEsgThmsauwuj0OPvALqD3LBcJEtE
	V7iHjXa23JI3A7NCnm+GtMyx5HQMu5u5OBVVaqKUNRw3F7/ed/QC+Q7FTW/4Z2oH
	Ml0C0OETFFqfUSHOzImlv1zUnvIQyybslR8w7tbbTngfO8kncE8DVnElCrPOnnth
	emx8E12FEuLIqqSpkxMxaZO8MgJqgH09y+SYFA9VJjeIpIXDt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ateKeyPem));
	
	try
	{
		Console.WriteLine(GenerateToken(privateKeyPem));
	}
	catch (Exception ex)
	{
		ex.Dump();
	}

	Console.WriteLine(GenerateToken(privateKeyPem));
	
	try
	{
		Console.WriteLine(GenerateToken(privateKeyPem));
	}
	catch (Exception ex)
	{
		ex.Dump();
	}

}

private string GenerateToken(string pem)
{

	using var rsa = RSA.Create();
	rsa.ImportFromPem(pem);
	// Create signing credentials with RSA
	var signingCredentials = new SigningCredentials(
		new RsaSecurityKey(rsa),
		SecurityAlgorithms.RsaSha256
	);
	
	var tokenDescriptor = new SecurityTokenDescriptor
	{
		Subject = new ClaimsIdentity([]),
		Expires = DateTime.UtcNow.AddDays(10),
		Issuer = "myIssuer",
		Audience = "myAudience",
		SigningCredentials = signingCredentials
	};

	var tokenHandler = new JwtSecurityTokenHandler();
	var token = tokenHandler.CreateToken(tokenDescriptor);
	return tokenHandler.WriteToken(token);
}

Expected behavior
4 jwt string output

Actual behavior
1st, 3rd output normal,
2nd, 4th output exception

Image

Possible solution

Additional context / logs / screenshots / links to code

ObjectDisposedException
Cannot access a disposed object.Object name: 'System.Security.Cryptography.RSABCrypt'.
 at System.Security.Cryptography.RSABCrypt.GetKey()
   at System.Security.Cryptography.RSABCrypt.TrySignHash(ReadOnlySpan`1 hash, Span`1 destination, HashAlgorithmName hashAlgorithm, RSASignaturePadding padding, Int32& bytesWritten)
   at System.Security.Cryptography.RSA.TrySignData(ReadOnlySpan`1 data, Span`1 destination, HashAlgorithmName hashAlgorithm, RSASignaturePadding padding, Int32& bytesWritten)
   at Microsoft.IdentityModel.Tokens.AsymmetricAdapter.SignUsingSpanRsa(ReadOnlySpan`1 data, Span`1 destination, Int32& bytesWritten)
   at Microsoft.IdentityModel.Tokens.AsymmetricAdapter.SignUsingSpan(ReadOnlySpan`1 data, Span`1 destination, Int32& bytesWritten)
   at Microsoft.IdentityModel.Tokens.AsymmetricSignatureProvider.Sign(ReadOnlySpan`1 input, Span`1 signature, Int32& bytesWritten)
   at Microsoft.IdentityModel.JsonWebTokens.JwtTokenUtilities.CreateSignature(ReadOnlySpan`1 data, Span`1 destination, SigningCredentials signingCredentials, Int32& bytesWritten)
   at Microsoft.IdentityModel.JsonWebTokens.JsonWebTokenHandler.CreateToken(SecurityTokenDescriptor tokenDescriptor, Boolean setdefaultTimesOnTokenCreation, Int32 tokenLifetimeInMinutes)
   at Microsoft.IdentityModel.JsonWebTokens.JsonWebTokenHandler.CreateToken(SecurityTokenDescriptor tokenDescriptor)

Metadata

Metadata

Assignees

No one assigned

    Labels

    BugProduct is not functioning as expected

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions