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

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>
  <add key="TenantId" value="[TenantId]"/>
  <add key="ClientId" value="[ClientId]"/>
  <add key="ResourceId" value="[ResourceId]" />
  <add key="ReplyAddressConfigured" value="[ReplyUrl]"/>
  <add key="Url" value="[API Url]"/>
</appSettings>

Test Application

With everything in place you can test the application and see that the identity moving trough from the Client Application to the API Application and then to Azure SQL Server.

 

Complete source code can be downloaded from GitHub:

https://github.com/MaikvanderGaag/PassThroughIdentity

 

Related Posts

Configure access to a private network for a Azure App Services On-Premise connections for Azure App Services can be created by using Hybrid Connections. Hybrid connections do not need any development or re-configu...
Part 2 – Azure API Application to query the Azure SQL Database This post is the second in a series of three posts and will help you with the creation of identity pass-through authentication from a client applicati...
Part 1 – Azure SQL Database with Azure Active Directory Authentication This post is the first post in a series of three posts and will help you with the creation of identity pass-through authentication from a client appli...
Pass-Through Authentication with Azure Active Directory, Azure SQL, Azure API an... In situations you need to login to an application and use that identity to access an API (pass-through identity) and also get data from Azure SQL Serv...
Using Certificates in Azure App Services In different kind of situations you need to use a certificate for authentication or signing. I needed on because I was setting up a Identity Server th...
SharePoint Rest API Handler SharePoint contains a lot of Rest API’s that can be used for many scenario’s. You could use them for example in desktop and windows phone applications...

Leave a Reply

Your email address will not be published. Required fields are marked *