My Application seems to deadlock while acquiring a Token for Azure AD
This solution worked for a few weeks but suddenly stopped today.
I narrowed it down to 'result = await pca.AcquireTokenByIntegratedWindowsAuth(scopes).ExecuteAsync(); //Deadlock here' since the program just gets stuck here. It does not throw an error and just deadlocks the application.
I am quite new to tasks, any help would be appreciated!
private static AuthenticationResult? result;
public static HttpClient getHttpClient()
{
var httpClient = new HttpClient();
var taskAccessToken = getAccessToken();
var AccessToken = taskAccessToken.Result;
httpClient.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", AccessToken);
return httpClient;
}
public static async Task<string> getAccessToken()
{
if (result == null || result.ExpiresOn - DateTime.UtcNow < TimeSpan.Zero)
{
var scopes = new[] { "api://{APICLIENTID}/.default" };
var tenantId = "{TENANTID}";
var authority = "https://login.microsoftonline.com/{TENTANTID}";
var clientId = "{CLIENTID}";
var pca = PublicClientApplicationBuilder
.Create(clientId)
.WithAuthority(authority)
.Build();
Debug.WriteLine("Waiting for Token");
try
{
result = await pca.AcquireTokenByIntegratedWindowsAuth(scopes).ExecuteAsync(); //Deadlock here
}
catch(Exception ex)
{
MessageBox.Show(ex.Message);
}
Debug.Write("Acquired Token");
}
return result.AccessToken;
}