Reputation: 175
I am using the below piece of code to generate access token to connect my application code to Azure SQL using AAD auth. I needed to find out the expiry time of this token
To find the expiry, I tried two ways:
1) Create one console app that connects to Azure SQL and perform some data operations using AAD auth. Run this app continuously in a loop for more than a hour. Here the token was found to expire after 1 hr
2) Create a Web App and host in iisexpress. In the web app, write the same data access code as in Console app. Invoke the Web App url in a loop multiple times for more than a hour. Here also the token was expiring in about an hr
3) Same as point 2 except for the fact that the Web App is hosted in Azure with Managed Identities enabled. Here the token wasn't expiring after 1 hr.
So the token expiry is linked to the environment from which the call is made. I need to find out the exact expiry time for token for different scenarios. I couldn't find any documentation. All that I find is that the token will be cached in memory and will be renewed when expired.
var provider = new AzureServiceTokenProvider();
string token = provider.GetAccessTokenAsync("https://database.windows.net/").Result;
SqlConnection con = new SqlConnection("connstring");
con.AccessToken = token;
Upvotes: 1
Views: 9894
Reputation: 58908
Managed Identity access tokens expire in 24 hours.
Tokens acquired via the App Authentication library currently are refreshed when less than 5 minutes remains until they expire. So it caches the token for 23 hours 55 minutes in the default case.
You can see where the library defines the expiry time here: https://github.com/Azure/azure-sdk-for-net/blob/e3bc748ea19040f9f18375aa907246f5b8b882a7/src/SdkCommon/AppAuthentication/Azure.Services.AppAuthentication/AppAuthenticationResult.cs#L40-L44
You should always cache the tokens until less than 5 minutes remains as the Managed Identity endpoint itself caches the tokens until that time. If you try to get a new token when more than 5 minutes remains, you will just get the same token.
Upvotes: 7
Reputation: 41
That hasn't been my experience. In a similar scenario you provided, I was able to use a token for 24hrs, and even in the generation process I could see where the token lifetime was set (86400 sec). But, that was using a VM system-assigned managed ID. This was tested within the last week.
We have seen differences in token lifetimes depending which service class/category is requesting the token (eg. Compute(VM), Management and Governance(AA), etc)
Upvotes: 2