Skip to content

Caching in Microsoft.IdentityModel

dannybtsai edited this page Jul 21, 2021 · 6 revisions

When signing and verifying tokens, we create SignatureProviders using the CryptoProviderFactory. By default, the value of CryptoProviderFactory.CacheSignatureProviders is set to true and SignatureProviders are cached. The cache key used is composed of security key type, security key internal ID, algorithm, and type of SignatureProvider. If a SignatureProvider with the same key already exists, it is NOT replaced and a new one is NOT added.

Before version 6.9.0, a simple ConcurrentDictionary was used for caching signature providers. This meant that the cache had no size limit or eviction policies, and had the potential of overflowing.

In version 6.9.0, the cache was modified to have a size limit and to automatically evict entries upon reaching 95% of max capacity. We are using our own implementation of a simple LRU cache across all targets (netstandard2.0, net472, net461, and net45). The size limit of this cache can be modified by changing the value of SizeLimit on the CryptoProviderCacheOptions.

Before version 6.12.0, the default CryptoProviderFactory (CryptoProviderFactory.Default) always starts two tasks internally to handle the events of adding and removing providers to/from the cache in a thread-safe manner, and the tasks remains running until the application stops. Starting from version 6.12.0, the behavior has been changed:

  • Start the task when adding providers to the cache and the cache is empty.
  • Stop the task when the last provider is removed from the cache (the cache is empty). If you have test cases or other scenarios that check for active tasks at the end, make sure to remove all providers from the cache and that should stop the internal running task.

IMPORTANT NOTES:

  • When creating a signature provider with CryptoProviderFactory.CacheSignatureProviders = true, it is important not to dispose of the keying material associated with that SignatureProvider while it is still in the cache.
  • SignatureProviders that have key with an empty InternalId property will not be cached.
Clone this wiki locally