Search code examples
.netazureauthenticationazure-active-directoryazure-identity

Does Azure.Identity library (e.g. DefaultAzureCredential) support token cache?


I have not found any details on whether Azure.Identity library does cache tokens or not. I am wondering if it properly caches the token per scope and renews it before the expiry or I have to write this functionality myself.

Any pointers to the proper documentation is welcome as well.

There is a SharedTokenCacheCredential in the library, but I do believe it is something else. I am asking about in-memory caching for performance reasons - to not get a new token each time.


Solution

  • It might have caching depending on the credential that gets used. For example the environment variable credential can build e.g. a ClientSecretCredential, which uses an instance of MSAL ConfidentialClientApplication internally (see source). MSAL has an in-memory cache for tokens, so this would work fine.

    The Managed Identity credential does not cache tokens in my experience, though the MI endpoint does. It is still not exactly scalable to call that HTTP endpoint every time you need a token, so when using Managed Identities, an in-memory cache is a good idea that caches tokens until 4-5 minutes before expiry (not more).

    Azure SDKs themselves have a token caching feature in their HTTP pipeline so the credentials aren't technically required to do caching.