Part 3 – Console application to call a API with Azure Active Directory Authentication

3 minute read

This post is the third and last in a series of three posts and will help you with the creation of identity pass-through authentication from a client application to a API and then to an Azure SQL Database. In this post we will create a console application to query the API published in Azure.

Previous Posts:

Add new Application to Azure Active Directory

In order to call our API we need to have a registered application within Azure Active Directory that has delegated permissions for the API application.

  1. Navigate to the Azure Portal (https://portal.azure.com/)
  2. Open the “Azure Active Directory” blade.
  3. In the blade click on “App Registrations”.
  4. In the “App Registrations” blade click on “New application registration”.
  5. Fill in a Name (like ConsoleApplication), Application Type: Native and Redirect Url: https://localhost. With everything filled in click on “Create”.

Add Application

  1. With the application registration created click on the registered application in the application list.
  2. In this window copy the ClientId of the application and click on “Required permissions”.

Console Application Permissions

  1. Click “Add” in the Required permissions blade to give the console application delegated permissions on the API we created.
  2. In the “Select an API” search for your created API application and select it.
  3. The permission step will open, make sure you select your application under “Delegated Permissions” and click “Select”.
  4. In the steps blade click “Done”.

Create console application

  1. Open Visual Studio and create a new Console Application.
  2. Open the NuGet Package manager and add the following package:
    • Microsoft.IdentityModel.Clients.ActiveDirectory – Version: 2.22.302111727

Note: Make sure you install version: 2.22.302111727. This version contains the option to prompt for user credentials.

Client authentication with authentication prompt

  1. In the “Program.cs” file add the below methods.
private static void TestApi(string url) {

    var authResult = GetToken();
    string token = authResult.AccessToken;
    if (token != null) {

        HttpClient client = new HttpClient();
        client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", token);

        var response = client.GetAsync(new Uri(url));

        string content = response.Result.Content.ReadAsStringAsync().Result;
        Console.WriteLine(content);
    }
}

private static AuthenticationResult GetToken() {

    string aadInstance = "https://login.windows.net/{0}";
    string ResourceId = ConfigurationManager.AppSettings["ResourceId"];
    string tenantId = ConfigurationManager.AppSettings["TenantId"];
    string clientId = ConfigurationManager.AppSettings["ClientId"];
    string replyAddress = ConfigurationManager.AppSettings["ReplyAddressConfigured"];
    AuthenticationContext authenticationContext =
      new AuthenticationContext(string.Format(aadInstance, tenantId));

    AuthenticationResult authenticationResult = authenticationContext.AcquireToken(ResourceId, clientId, new Uri(replyAddress), PromptBehavior.RefreshSession);

    return authenticationResult;
}

The methods will call the API with the URL as specified in the “url” parameter but also retrieve a token for the user that logs in to the prompt. The “GetToken” method makes sure this prompt is shown by the "PromptBehavior" enumeration.

  1. With the methods in the “Program.cs” file we need to adjust the main method.
static void Main(string[] args) {

    string url = ConfigurationManager.AppSettings["Url"];

    if (string.IsNullOrEmpty(url)) {
        Console.WriteLine("Please fill in your URL:");
        url = Console.ReadLine();
    }

    Console.WriteLine("Calling url: " + url);

    TestApi(url);
    Console.WriteLine("Done processing, press any key to close....");
    Console.ReadKey();
}

  1. As you may have seen in the previous methods we will save the settings in the configuration file. Open the file and add those settings.
<appSettings>