I have a .Net Web API secured with Azure AD and through C# console application I need to generate a token and call the API.
I am using the old ADAL.NET approach as it's a legacy app and supports V1.0 AD endpoints.
The below code works, but for every call, a NEW token is generated with a NEW expiry date/time.
How to cache it till it expiry and automatically silently renew it?
I tried the below code, but seems it's not working.
private async Task<string> GetTokenAsync()
{
// Create the AuthenticationContext with token cache
var authContext = new AuthenticationContext("https://login.windows.net/{tenant_id}", new TokenCache());
var credential = new ClientCredential("ClientID", "ClientSecret");
try
{
// Acquire an access token for the API
var result = await authContext.AcquireTokenAsync("Resource", credential);
return result.AccessToken;
}
catch (AdalSilentTokenAcquisitionException)
{
// If AcquireTokenAsync fails, try refreshing the token using AcquireTokenSilentAsync
try
{
var result = await authContext.AcquireTokenSilentAsync("Resource", credential, UserIdentifier.AnyUser);
return result.AccessToken;
}
catch (AdalException exception)
{
}
}
catch (AdalException exception)
{
}
catch (Exception exception)
{
}
return string.Empty;
}