azure-sdk-for-net: ManagedIdentityCredential token cache not working?
I recently upgraded Azure.Identity to version 1.8.2, hoping I can get rid of my token caching implementation and rely on the internal caching. however, from looking at Application Insights logs, it looks like there is no caching going on, and a token is acquired before every access to the database. Here is a screenshot for example. I highlighted requests for a token and the corresponding database calls.
I am using a ChainedTokenCredential
like this:
private static TokenCredential GetCredential()
{
return new ChainedTokenCredential(
new ManagedIdentityCredential(),
new VisualStudioCredential(),
new EnvironmentCredential()
);
}
and then get a token like this:
public SqlConnection GetConnection()
{
SqlConnection conn = new SqlConnection(Config.ConnectionString);
if (!Config.IsDevEnvironment) //in dev we use an on-prem db
{
TokenCredential credential = GetCredential();
AccessToken token = credential.GetToken(new TokenRequestContext(new[] { "https://database.windows.net/.default" }), CancellationToken.None);
conn.AccessToken = token.Token;
}
return conn;
}
Am I doing something wrong?
About this issue
- Original URL
- State: closed
- Created a year ago
- Comments: 17 (6 by maintainers)
If there are no additional calls to the msi endpoint, then the token is being cached. You can validate with the logging, as it will contain something like this:
[Informational] Azure-Identity: False MSAL 4.49.1.0 MSAL.NetCore .NET 5.0.17 Microsoft Windows 10.0.22621 [2023-05-31 21:40:59Z - tenantGuid] AT expiration time: 5/31/2023 11:10:56 PM +00:00, scopes: https://storage.azure.com/user_impersonation https://storage.azure.com/.default. source: Cache