Calling The Azure Billing API Unattended

In this post I’m going to investigate calling the Azure Billing API unattended. In my previous post I showed how to retrieve your Azure usage using the sample application provided by Microsoft with a few modifications. In this post I’m going to show how you can call the Billing API using a service principal. This will enable scenarios like a Windows service or scheduled tasks calling the Billing API to retrieve your usage without having to authenticate using a GUI.

There is a very detailed explanation around Azure Service Principals here. I’m going to give a short version and also highlight a few things that pertain specifically to calling the Azure Billing API.

To create a service principal you have to create an Azure Directory application and even though it will not be a web app you have to specify it as an web application since you can’t create a service principle for native applications.

Calling The Azure Billing API Unattended

Since users won’t actually be redirected to a URL to authenticate you can type in any valid URL that can be converted to URI in your code.

Calling The Azure Billing API Unattended

After the application is created you have to generate a key, this key and your client id above it will be used to authenticate at runtime. Heed the warning to copy the key since, there is really no way to retrieve it but at the same time you can just create another key if needed.

Calling The Azure Billing API Unattended

You also have to grant the AD application permissions to access the Azure Management API.

Calling The Azure Billing API Unattended

It might seem obvious but the requests you make using this service principal won’t be in the context of your user, that is the whole point of the service principal. For the service principal to access your subscription you have to grant it permission to do so at the subscription level using RBAC. Log in to the new Azure portal and click on Subscriptions and the Access icon. Add your application (Bill in this case) to the Reader Role.

Calling The Azure Billing API Unattended

Now you can use the client id and secret key to authenticate and receive a token to call the Billing API.

var authenticationContext = new AuthenticationContext(YourTenantURL,`  false);
var credential = new ClientCredential(YourAppClientId, YourAppSecretKey);
var result = authenticationContext.AcquireToken("https://management.core.windows.net/", credential);

string token = result.AccessToken;

Francois Delport

Published by

Francois Delport

I am a cloud and devops consultant, technology fan and previously a professional C# developer with a keen interest in system design and architecture. Currently I am involved in projects using Azure, the Microsoft stack and DevOps. I am based in Melbourne, Australia. Email: [email protected]

Leave a Reply

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