Azure Cosmos DB + Functions Cookbook — secure client

Matías Quaranta
Microsoft Azure
Published in
3 min readMar 9, 2018

Security is an extremely important topic and we’ll address a way to secure access to the Azure Cosmos DB keys in this next Azure Cosmos DB + Azure Functions Cookbook recipe.

Scenario

You want to be able to interact with Cosmos DB using the DocumentClient but you don’t want to provide direct access to the required Key for security purposes.

While you can store the Cosmos DB Key in the Azure Function’s Application Settings (like we saw in the first recipe), you’d be exposing that information to whoever is creating and managing the Azure Function.

Ingredients

For this recipe we’ll be using the Azure Key Vault service. Not only we’ll be able to securely store the Key, but we’ll be able to manage the access policy through Active Directory so, even if someone else obtains the Key Vault identifier or secret, the Key will only be readable by the whitelisted applications (the Azure Function in this case).

Recipe

First, we need to create an Azure Key Vault:

Creating a Key Vault in the Portal

Then, we need to create a Secret (our Azure Cosmos DB Key), simply add a Manual Secret and use the Key you can obtain from Azure Cosmos DB Portal.

Creating a Secret to store our Cosmos DB Key

Now, this Secret, is represented by a Secret Identifier (a URL). We’ll be able to share this Secret Identifier with anyone who wants to obtain the Key.

Secret Identifier

Since this Secret Identifier would allow anyone to access the Secret, we’ll whitelist only the Azure Function, through Active Directory. To do this, go to your Azure Function’s Platform features and enable Managed service identity.

Enabling managed service identity

Then we go back to our Key Vault and give the Azure Function’s identity, Get permissions over the Keys, we need to select as Principal, the name of our Azure Function:

Give only Get Secret permissions

Now comes the coding part. Add two Application Settings: the Endpoint of your Azure Cosmos DB account and the Secret Identifier of your Key Vault:

Setting Function’s configuration values

The next part contains the actual code that will maintain a static DocumentClient created by obtaining the Account Key from Azure Key Vault using the Secret Identifier (scoped in the GetSecureDocumentClient method):

This requires the Azure Key Vault nuget, which we’ll pull using the project.json file in our Function:

Adding a project.json file

To complete the sample, here is the function.json file with the binding definitions:

With this recipe you are now able to interact with your Cosmos DB account through a securely stored Key that only the defined Function can obtain.

--

--

Matías Quaranta
Microsoft Azure

Software Engineer @ Microsoft Azure Cosmos DB. Your knowledge is as valuable as your ability to share it.