Some fun with Azure Key Vault REST API and HttpClient – Part 1

Azure Key Vault is not new to Azure developers and architects. It is a cloud-based service to safeguard your sensitive information and crypto implementation and management . Working with Azure Key Vault can be done via Azure Portal, PowerShell or corresponding client libraries. While people may prefer using a specific library (.e.g Azure Key Vault .NET client), I’d prefer practicing with REST API and HttpClient.

Inspired by unclear instruction on using Azure Key Vault REST API, this article is the result of my practice on the REST API and also found some notes around it.

This article is not going to bring out number of advantages or disadvantages of REST. At least you know REST has been promoted nowadays. More importantly, when microservices resonates, REST is much more popular. REST contributes to simplified service communication over HTTP protocol without any additional infrastructure required. With the use of REST in Azure, you’d realize how beneficial it is to your cross-platform. For the sake of REST, I don’t really need to worry about the framework I need. It’s just a call to the endpoint over HTTP. It democratize the cloud development without owning specific .NET skills. This means a Java or Python developers team can work out their applications by just initializing HTTP requests against REST API.

This article shows you the following things:

  • Get Azure AD access token by POST method
  • Build a base HttpClient object
  • Check availability of vault name
  • Create a new vault

Environment variable and configuration management

Follow the article Getting Azure AD access token via REST Call to register a new client application object, and prepare your environment variable in app.config file. The sample app.config file looks like below

In the program.cs , declare your variables

To use CloudConfigurationManager.GetSetting() , you must install Windows.Azure.ConfigurationManager  Nuget package then add directive  using Microsoft.Azure;

Make sure you add your service principal to Subscription. The role must be Owner to create an Azure resource namely Azure Key Vault.

Getting Azure AD access token

Azure AD access token is not the only way to use to authorize against Azure Resource Management endpoint. While you can use certificate-based or Managed Service Identity (MSI), this article is aimed to giving familiarity in the traditional approach of access token retrieval. Make sure you understand that if you would like to perform any operation against Azure Resource Management endpoint, you need to be authorized by Azure AD.

To get access token, you need to create an object which is as known as service principal Azure AD uses. This article provides you the sample code I borrowed from David Ebbo to get access token. The AuthHelper class uses POST method to call to<tenant id>/oauth2/token to get an access token. The parameter named access_token in response contains the token in JWT (JSON Web Token) format that you can use to authenticate to the Azure Key Vault service. This token will be added to Authorization header in an HttpClient object for every call to Azure Key Vault REST API. The sample response body is as follows:

Build your base HttpClient object

In this step, you need to initialize a new HttpClient object and its authorization header. This is very important step for every call to resource endpoint. The authorization header contains your access token you retrieved previously.

The first line is to call AcquireTokenBySPN()  method from AuthHelper class to retrieve access token. Next, initialize a HttpClient object and set default request header for this object. Create a new method named CreateVault()  which we will call inside the Main()  method which looks like as follows:

Checking vault name availability

Your vault name must be globally unique in Azure. It means before creating a new key vault, there must be a method to check availability of your name. Fortunately Azure provides you an endpoint to do so. Before making a method call to /checkNameAvailability, I intend to use Task<String>  to return availability result which I will call from another method.

Now, let’s declare your Url to combine with Uri in a HTTP request call.  This is the endpoint to check your vault name’s availability

Next, build your request body. The request body does not have to be in JSON format. As the endpoint supports POST method, I’d prefer creating a dictionary of string type.

..then encode before passing to PostAync()  method

then make a POST method using  PostAsync() in asynchronous mode.

In the code above, I want to retrieve the value of nameAvailable  property in my return JSON. The purpose is to check if the return is true then start creating a new vault. Otherwise escape the method. Below is the code snippet to check vault name availability

The response will return Boolean type to let you know if the given vault name is globally available.

Creating a new key vault

First, I need to declare an endpoint which combines with the given Uri to create a new vault.

Now I need to get return from CheckVaultName()  method

..then make an If statement to make sure if my vault name available then go create a new vault. The very important part which is hard to find over the Internet is the request body. The instructor you find here is not really helpful especially to those who just get started with Azure REST API.

In the request body, you can declare your location where a new vault is located. Here are some notes:

  • SKU Family is always A.
  • SKU name can be either standard or premium. It is Key Vault plan. The difference between the two plans is HSM-protected keys supportability
  • accessPolicy: this is where you define access policy for your service principal which will be used to create or retrieve your secret, key or certificate in the future. The access policy must be created in a format of array. During the declaration, you must also provide tenant ID, object ID (it is client ID), permission corresponding. For the demonstration purpose, I only provide key and secret access policy.

There are three options you can enable if needed:

  • enabledForDeployment: if you want to deploy a secret-based certificate for your virtual machine, for example in a case you want your virtual machine to retrieve a certificate. This works only with secret.
  • enabledForDiskEncryption: if you want to allow Azure Disk Encryption to retrieve a secret.
  • enabledForTemplateDeployment: this case if where you want to retrieve secret which is declared in your ARM template.

Now, it is time to request a PUT method to the given endpoint. Note that you may like to use PutAsync()  rather than PutAsJsonAsync() . The two methods use different parameter. PutAsync uses HttpContent type while PutAsJsonAsync uses T value.

So below is the full code snippet of my CreateVault()  method

If the request is successful, the response will contain information of the new vault in JSON format.

Make sure you press any key to escape the console. If keeping it for long enough, you might need to reset your modem because HttpClient with using()  open many socket. My modem gets flooded by lots of TCP packet. I had to do twice then realized that using using()  has some negative findings (read mentioned references in Conclusion)


In this article, I just showed you how to work with Azure Key Vault REST API fundamentally. This is fast, cheap right? The code only demonstrates the way of building request body and REST call. It may not be optimized for HttpClient. In terms of the use of HttpClient and disposal, I read through the following articles and kind of agree with the finding

For sample code, I’m in the progress of cleaning and will commit it to this repo soon.

In the next article, let’s have some fun with secret.


Leave a Reply

© 2018 The Soldier of Fortune.