question-mark
Stuck on an issue?

Lightrun Answers was designed to reduce the constant googling that comes with debugging 3rd party libraries. It collects links to all the places you might be looking at while hunting down a tough bug.

And, if you’re still stuck at the end, we’re happy to hop on a call to see how we can help out.

JwtSecurityTokenHandler.ValidateToken throws ObjectDisposedException

See original GitHub issue

Issue moved from dotnet/aspnetcore#22490


From @vlkchris on Wednesday, June 3, 2020 9:50:59 AM

Describe the bug

I use RSA.Create() to create an RSA instance, and then use .ImportSubjectPublicKeyInfo to import public key.

  • The first time I call my validate token method it runs fine.
  • The second time I call it, I get SecurityTokenInvalidSignatureException (but only when I import the same key) This exception contains ObjectDisposedException
  • The third time it is ok again.
  • The fourth time it fails and so on.

To Reproduce

Please check the following test project. It shows how and when Exceptions occur. https://github.com/vlkchris/JwtHelper

Exceptions (if any)

SecurityTokenInvalidSignatureException message: IDX10503: Signature validation failed. Keys tried: 'Microsoft.IdentityModel.Tokens.RsaSecurityKey, KeyId: ‘’, InternalId: ‘-mBjPYLobIiFBJ_q6K4LP22czPQyTHkg4NrmHV4h_ZE’. , KeyId: '. Exceptions caught: 'System.ObjectDisposedException: Cannot access a disposed object. Object name: ‘RSA’. at System.Security.Cryptography.RSAImplementation.RSACng.ThrowIfDisposed() at System.Security.Cryptography.RSAImplementation.RSACng.GetDuplicatedKeyHandle() at System.Security.Cryptography.RSAImplementation.RSACng.VerifyHash(ReadOnlySpan1 hash, ReadOnlySpan1 signature, HashAlgorithmName hashAlgorithm, RSASignaturePadding padding) at System.Security.Cryptography.RSAImplementation.RSACng.VerifyHash(Byte[] hash, Byte[] signature, HashAlgorithmName hashAlgorithm, RSASignaturePadding padding) at Microsoft.IdentityModel.Tokens.AsymmetricAdapter.VerifyWithRsa(Byte[] bytes, Byte[] signature) at Microsoft.IdentityModel.Tokens.AsymmetricAdapter.Verify(Byte[] bytes, Byte[] signature) at Microsoft.IdentityModel.Tokens.AsymmetricSignatureProvider.Verify(Byte[] input, Byte[] signature) at System.IdentityModel.Tokens.Jwt.JwtSecurityTokenHandler.ValidateSignature(Byte[] encodedBytes, Byte[] signature, SecurityKey key, String algorithm, SecurityToken securityToken, TokenValidationParameters validationParameters) at System.IdentityModel.Tokens.Jwt.JwtSecurityTokenHandler.ValidateSignature(String token, TokenValidationParameters validationParameters) '. token: ‘{“alg”:“RS256”,“typ”:“JWT”}.{“someclaim”:“some value”}’.

Further technical details

  • ASP.NET Core version = netcoreapp3.1

  • Include the output of dotnet --info

dotnet --info .NET Core SDK (reflecting any global.json): Version: 3.1.101 Commit: b377529961

Runtime Environment: OS Name: Windows OS Version: 10.0.17134 OS Platform: Windows RID: win10-x64 Base Path: C:\Program Files\dotnet\sdk\3.1.101\

Host (useful for support): Version: 3.1.1 Commit: a1388f194c

.NET Core SDKs installed: 2.1.505 [C:\Program Files\dotnet\sdk] 2.1.602 [C:\Program Files\dotnet\sdk] 2.1.700-preview-009601 [C:\Program Files\dotnet\sdk] 2.1.700 [C:\Program Files\dotnet\sdk] 2.1.800-preview-009677 [C:\Program Files\dotnet\sdk] 2.1.801 [C:\Program Files\dotnet\sdk] 2.2.105 [C:\Program Files\dotnet\sdk] 3.0.100 [C:\Program Files\dotnet\sdk] 3.1.101 [C:\Program Files\dotnet\sdk]

.NET Core runtimes installed: Microsoft.AspNetCore.All 2.1.9 [C:\Program Files\dotnet\shared\Microsoft.AspNetCore.All] Microsoft.AspNetCore.All 2.1.11 [C:\Program Files\dotnet\shared\Microsoft.AspNetCore.All] Microsoft.AspNetCore.All 2.1.12 [C:\Program Files\dotnet\shared\Microsoft.AspNetCore.All] Microsoft.AspNetCore.All 2.1.13 [C:\Program Files\dotnet\shared\Microsoft.AspNetCore.All] Microsoft.AspNetCore.All 2.2.3 [C:\Program Files\dotnet\shared\Microsoft.AspNetCore.All] Microsoft.AspNetCore.App 2.1.9 [C:\Program Files\dotnet\shared\Microsoft.AspNetCore.App] Microsoft.AspNetCore.App 2.1.11 [C:\Program Files\dotnet\shared\Microsoft.AspNetCore.App] Microsoft.AspNetCore.App 2.1.12 [C:\Program Files\dotnet\shared\Microsoft.AspNetCore.App] Microsoft.AspNetCore.App 2.1.13 [C:\Program Files\dotnet\shared\Microsoft.AspNetCore.App] Microsoft.AspNetCore.App 2.2.3 [C:\Program Files\dotnet\shared\Microsoft.AspNetCore.App] Microsoft.AspNetCore.App 3.0.0 [C:\Program Files\dotnet\shared\Microsoft.AspNetCore.App] Microsoft.AspNetCore.App 3.1.1 [C:\Program Files\dotnet\shared\Microsoft.AspNetCore.App] Microsoft.NETCore.App 2.1.9 [C:\Program Files\dotnet\shared\Microsoft.NETCore.App] Microsoft.NETCore.App 2.1.11 [C:\Program Files\dotnet\shared\Microsoft.NETCore.App] Microsoft.NETCore.App 2.1.12 [C:\Program Files\dotnet\shared\Microsoft.NETCore.App] Microsoft.NETCore.App 2.1.13 [C:\Program Files\dotnet\shared\Microsoft.NETCore.App] Microsoft.NETCore.App 2.2.3 [C:\Program Files\dotnet\shared\Microsoft.NETCore.App] Microsoft.NETCore.App 3.0.0 [C:\Program Files\dotnet\shared\Microsoft.NETCore.App] Microsoft.NETCore.App 3.1.1 [C:\Program Files\dotnet\shared\Microsoft.NETCore.App] Microsoft.WindowsDesktop.App 3.0.0 [C:\Program Files\dotnet\shared\Microsoft.WindowsDesktop.App] Microsoft.WindowsDesktop.App 3.1.1 [C:\Program Files\dotnet\shared\Microsoft.WindowsDesktop.App]

To install additional .NET Core runtimes or SDKs: https://aka.ms/dotnet-download

  • The IDE (VS / VS Code/ VS4Mac) you’re running on, and it’s version Visual Studio Professional 16.3.5

Issue Analytics

  • State:closed
  • Created 3 years ago
  • Reactions:1
  • Comments:5 (3 by maintainers)

github_iconTop GitHub Comments

8reactions
GeoKcommented, Jun 4, 2020

Hi @vlkchris, the issue here is that IdentityModel by default caches signature providers, together with and keys which you disposed.

In your sample, first validation succeeds, and IdentityModel adds a signature provider (with your key) to the cache. In the second validation, IdentityModel recognizes the key and uses a cached signature provider to validate a token, but the key of that provider is now disposed.


There are a few possible workarounds for this issue:

  1. Don’t dispose your RSA key here.

  2. Don’t cache a signature provider for a key, by replacing this line with:

SecurityKey key = new RsaSecurityKey(rsa)
{
    CryptoProviderFactory = new CryptoProviderFactory()
    {
        CacheSignatureProviders = false
    }
};
  1. Don’t cache a signature provider associated with keys from a TokenValidationParameters object, by adding the following here:
var validationParameters = new TokenValidationParameters
{
...
    CryptoProviderFactory = new CryptoProviderFactory()
    {
        CacheSignatureProviders = false
    }
...
};
  1. Turn off caching of signature providers at the app level by adding this line to startup:
CryptoProviderFactory.DefaultCacheSignatureProviders = false;
1reaction
vlkchriscommented, Jun 15, 2020

@GeoK - No worries about the delay, there is no urgency on my side. I am happy using workaround #1 for now, and if necessary I’ll disable caching. I’ll be on the lookout for any development on this, subscribed to #1447

Read more comments on GitHub >

github_iconTop Results From Across the Web

JwtBearerAuthentication Safe Handle Exception
ObjectDisposedException was unhandled by user code HResult=-2146232798 Message=Safe handle has been closed ObjectName="" Source=mscorlib ...
Read more >
[Solved]-JwtSecurityTokenHandler.ValidateToken throwing ...
Coding example for the question JwtSecurityTokenHandler.ValidateToken throwing Lifetime validation failed exception-C#.
Read more >
System.IdentityModel.Tokens.Jwt.xml 2.0.0.17
ObjectDisposedException ">if <see cref="M:System. ... Gets the InboundClaimTypeMap used by JwtSecurityTokenHandler when producing ... ValidateToken(System.
Read more >
ObjectDisposedException in .NET Core middleware with ...
I seem to either get System.InvalidOperationException: An attempt was made to use the context while it is being configured. or System.
Read more >
JwtSecurityTokenHandler.ValidateToken Method
Reads and validates a 'JSON Web Token' (JWT) encoded as a JWS or JWE in Compact Serialized Format.
Read more >

github_iconTop Related Medium Post

No results found

github_iconTop Related StackOverflow Question

No results found

github_iconTroubleshoot Live Code

Lightrun enables developers to add logs, metrics and snapshots to live code - no restarts or redeploys required.
Start Free

github_iconTop Related Reddit Thread

No results found

github_iconTop Related Hackernoon Post

No results found

github_iconTop Related Tweet

No results found

github_iconTop Related Dev.to Post

No results found

github_iconTop Related Hashnode Post

No results found