Search code examples
c#oauth-2.0console-application

Using OAuth in a C# command line application


Using code that works in an Azure App Service, I am attempting to get an OAuth access token in a command line application.

This is my code:

IConfidentialClientApplication app = ConfidentialClientApplicationBuilder
                .Create(clientId)
                .WithClientSecret(clientSecret)
                .WithAuthority(new Uri(authority))
                .Build();

string accessToken ="";

try
{
    AuthenticationResult authResult = await app.AcquireTokenForClient(scopes).ExecuteAsync();
    accessToken = authResult.AccessToken;
}
catch (MsalServiceException ex)
{
    Console.WriteLine($"Service error occurred: {ex.Message}");
}
catch (MsalClientException ex)
{
    Console.WriteLine($"Client error occurred: {ex.Message}");
}
catch (Exception ex)
{
    Console.WriteLine($"An unexpected error occurred: {ex.Message}");
}

It exits with no error on the AcquireTokenForClient method call. I don't understand why execution terminates. No error is thrown, and the return code is zero. If I'm barking up the wrong tree, OK. I am open to suggestions. I need the access token so I can use it with an exchange web service object.


Solution

  • It turns out my whole problem was that I was using an async method, which was spawning a new thread and exiting the application. I dropped the async keyword from the method and changed

    AuthenticationResult authResult = await app.AcquireTokenForClient(scopes).ExecuteAsync();

    to

    AuthenticationResult authResult = app.AcquireTokenForClient(scopes).ExecuteAsync().Result;

    And now, there is much rejoicing...

    Looks like I have a lot to learn...but what's life without growth?