About the issue
When validating RSA signed JWT security tokens in .NET, you may encounter an issue like the following:
IDX10511: Signature validation failed. Keys tried: 'Microsoft.IdentityModel.Tokens.RsaSecurityKey, KeyId: '***', InternalId: '***'.'. Number of keys in TokenValidationParameters: '1'. Number of keys in Configuration: '0'. Matched key was in 'TokenValidationParameters'. kid: '5ea546c1-0044-4ab2-be75-b76523126567'. Exceptions caught: 'System.ObjectDisposedException: Cannot access a disposed object. Object name: 'System.Security.Cryptography.RSAImplementation+RSASecurityTransforms'.
In some cases, you may see the following issue:
Token validation failed: Invalid signature. IDX10517: Signature validation failed. The token's kid is missing.
In most cases, there are no issues with your kid especially if you are not even using it in your JWT header and backend issuer system. I spent a few hours to debug this issue hence I thought I will document it here especially all LLMs I tried won't be able to resolve this issue either.
Unveil the real issue
If you are confident your private RSA key and public key are correct, then try to enable PII for debug in .NET. You can simply add the following lines into your code:
IdentityModelEventSource.ShowPII = true; IdentityModelEventSource.LogCompleteSecurityArtifact = true;
Then the actual exception will surface as mentioned in the first section.
To be more specific, I used using
while .NET tried to reuse RSA key instances for performance reasons.
using var rsa = RSA.Create();
This issue generally occurs when you try to validate the tokens very frequently.
The solution
We could try to run the same validation logic multiple times as for my case the issue only occurs every second time. This can be fragile as you won't know the timing exactly when the instance is disposed.
I eventually decided to remove using
and let GC to handle the instance and all the issues are gone.
There might be side effects but this is the most straightforward fix I can find for now. If you have other better suggestions, please leave a comment.
References
https://github.com/AzureAD/azure-activedirectory-identitymodel-extensions-for-dotnet/wiki/PII