0

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;
}
  • 2
    The usage of `.Result` most likely causes the deadlock. Usually async/await needs to be used across the whole call chain. – juunas Sep 06 '22 at 13:08
  • Using this: taskAccessToken.Wait(); var AccessToken = result.AccessToken; instead of var AccessToken = taskAccessToken.Result; results in the same error.. – aron.wissing Sep 06 '22 at 13:16
  • See a similar question here : https://stackoverflow.com/questions/73120433/correct-way-to-use-async-await-with-acquiretokenforclient-executeasync – XouDo Sep 06 '22 at 13:22

1 Answers1

0

I put the task into a Thread and this seemed to stop the Deadlock..

For anyone who has the same issue:

private static HttpClient httpClient;
private static string AccessToken;
private static AuthenticationResult? result;

public static HttpClient getHttpClient()
{
    Thread testThread = new Thread(test);
    testThread.Start();
    testThread.Join();
    var httpClient = new HttpClient();
    
    httpClient.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", AccessToken);
    return httpClient;
}

private static void test()
{
    var taskAccessToken = getAccessToken();
    AccessToken = taskAccessToken.Result;
}