Azure Resource Manager SDK for .Net


Click here to change the theme.

The article Azure Resource Manager SDK for .Net provides a procedure to prepare for an application that uses the Azure Resource Manager SDK. The sample code shows how to do authentication and uses Azure Active Directory. The code however needs revision.

The first hurdle for me was, where to get the library from. Apparently the sample code in the article is actually for Active Directory, not Azure. The current version can be installed using NuGet; look for "Active Directory Authentication Library". Install it into your project, then add a using for "Microsoft.IdentityModel.Clients.ActiveDirectory".

Also in NuGet, for "Querying Azure subscriptions attached to the authenticated application" you will need "Newtonsoft.Json".

The next problem is that the current version does not have "AcquireToken" so we must convert it to "AcquireTokenAsync".

Another problem is that the authority URL specified in the AuthenticationContext construtor has changed.

The following is a small console program with the code from the "Receiving the AccessToken from code" (the first portion of code) that works for me.

using System;
using System.Threading.Tasks;
using Microsoft.IdentityModel.Clients.ActiveDirectory;

namespace AzureResourceManagerConsole
{
    class Program
    {
        static void Main(string[] args)
        {
            // provide your application's tenantId, clientId and clientSecret
            // in the following
            string tenantId = "{tenantId}";
            string clientId = "{clientId}";
            string clientSecret = "{clientSecret}";
            Console.WriteLine("Aquiring Access Token from Azure AD for:");
            Console.WriteLine("\ttenantId: {0}", tenantId);
            Console.WriteLine("\tclientId: {0}", clientId);
            Console.WriteLine("\tclientSecret: {0}", clientSecret);
            Task<AuthenticationResult> tasktoken =
				GetAccessToken(tenantId, clientId, clientSecret);
            if (tasktoken.Result == null)
                return;
            Console.WriteLine($"Token: {tasktoken.Result.AccessToken}");
        }

        private static async Task<AuthenticationResult>
			GetAccessToken(string tenantId, string clientId, string clientSecret)
        {
            AuthenticationResult token = null;
            try
            {
            AuthenticationContext authContext = new AuthenticationContext
                ("https://login.windows.net/" +
                $"{tenantId}/FederationMetadata/2007-06/FederationMetadata.xml");
            var credential = new ClientCredential(clientId, clientSecret);
            token = await authContext.AcquireTokenAsync("https://management.azure.com/",
				credential);
            }
            catch (Exception ex)
            {
                Console.WriteLine("GetAccessToken error: "+ex.Message);
                return null;
            }
            return token;
        }
    }
}