Search code examples
azureoauth-2.0azure-active-directoryazure-managed-identity

Why is AzureServiceTokenProvider returning an expired access token?


I'm trying to use AzureServiceTokenProvider to get an access token to call a custom service, but it's intermittently returning an expired token. I understand that AzureServiceTokenProvider caches the token and retrieves a new one before expiration, but this is a brand new token in a brand new debugging session. Example debugging session:

Current UTC time: 3/6/2021 5:57:16 AM

enter image description here

But token returned is already expired?? 3/6/2021 5:27:40 AM UTC

enter image description here

I'm getting this behavior locally AND when deployed to Azure, but it's intermittent.

Update: I also tried GetAuthenticationResultAsync with forceRefresh set to true based on the recommendation from https://github.com/Azure/azure-sdk-for-net/issues/16718 but still got an expired token with the same 3/6/2021 5:27:40 AM date.


Solution

  • Difficult to say what the problem is. Best guess is that the call to get the new token is failing and therefore returning the cached token.

    However, as stated in the link in your question, this method is legacy and no longer recommended.

    You could therefore "solve" the problem by switching to the Azure Identity Client Library https://learn.microsoft.com/en-us/dotnet/api/overview/azure/identity-readme