How to create ServiceClientCredential to be used with Microsoft.Azure.Management.Compute

user5748653 picture user5748653 · Feb 5, 2016 · Viewed 17.7k times · Source

I am trying to programmatically retrieve the HostedServices from Microsoft.Azure.Management.Compute using C#. This requires ServiceClientCredential and I do not know how to get it.

How can I instantiate this class?

I am able to get them using Microsoft.WindowsAzure.Management.Compute but here it returns only the instances under ResourceManager not the classic instances.

Answer

Ahmed Ashmawy picture Ahmed Ashmawy · May 31, 2016

First you need to create Active Directory application. See How to: Use the portal to create an Azure AD application and service principal that can access resources

The sample code below uses the nuget package Microsoft.Azure.Management.Compute 13.0.1-prerelease:

public class CustomLoginCredentials : ServiceClientCredentials
{
    private string AuthenticationToken { get; set; }
    public override void InitializeServiceClient<T>(ServiceClient<T> client)
    {
        var authenticationContext = new AuthenticationContext("https://login.windows.net/{tenantID}");
        var credential = new ClientCredential(clientId: "xxxxx-xxxx-xx-xxxx-xxx", clientSecret: "{clientSecret}");

        var result = authenticationContext.AcquireToken(resource: "https://management.core.windows.net/", clientCredential: credential);

        if (result == null) throw new InvalidOperationException("Failed to obtain the JWT token");

        AuthenticationToken = result.AccessToken;
    }
    public override async Task ProcessHttpRequestAsync(HttpRequestMessage request, CancellationToken cancellationToken)
    {
        if (request == null) throw new ArgumentNullException("request");

        if (AuthenticationToken == null) throw new InvalidOperationException("Token Provider Cannot Be Null");
        
        request.Headers.Authorization = new AuthenticationHeaderValue("Bearer", AuthenticationToken);
        request.Headers.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));

        //request.Version = new Version(apiVersion);
        await base.ProcessHttpRequestAsync(request, cancellationToken);
    }
}

Then you can initialize the client like this:

netClient = new Microsoft.Azure.Management.Compute.ComputeManagementClient(new CustomLoginCredentials());
netClient.SubscriptionId = _subscriptionId;