user584018
user584018

Reputation: 11304

how to cache and refresh managed identity token

I am using azure managed identity and below code generates the required token to authenticate the api's. I am using <PackageReference Include="Azure.Identity" Version="1.4.0" />

var credential = new ManagedIdentityCredential();
            var accessToken = await credential.GetTokenAsync(new Azure.Core.TokenRequestContext(new[] {"my_scope"}));
            return accessToken.Token;

Now in each api call I am calling above method to get token. Question is what are the ways to cache this token and refresh automatically? Is this something inbuild available?

Upvotes: 3

Views: 5109

Answers (2)

Uchitha
Uchitha

Reputation: 1038

Latest SDK release (August 2022) mentions that caching is now enabled for both DefaultAzureCredential and ManagedIdentityCredential. No code changes required.

https://devblogs.microsoft.com/azure-sdk/azure-sdk-release-august-2022/

Upvotes: 7

udayxhegde
udayxhegde

Reputation: 381

Unfortunately, there is no inbuilt caching within the Azure identity library for ManagedIdentityCredential available today. The caching is implemented within the other SDKs (such as Azure storage, KeyVault etc) when they call getToken.

However, you may want to evaluate if the token caching that already exists within the Managed identity endpoint on the App service/Functions/VM where your code is running is sufficient for your purpose. It is a local endpoint, so the latency may meet your needs, even though a local cache within your code will certainly be faster. And you may also want to evaluate how often your code makes the token request, since I hear that if you have too many requests within a second, the managed identity endpoint may throttle those requests.

Upvotes: 1

Related Questions