Managing Azure Functions API Keys

Context

I’ve been working on example code to use the JavaScript MongoDB driver to work with the Azure Cosmos DB. To connect to the DB I’ve had to manage my DB API keys – the secrets that allow only me to get at my data. Here’s how to do that in Azure Functions.

Azure Functions Environment Variables

The simplest way to store API keys for use in Azure functions is to write them to the environment variables using the Portal web interface and then read in the environment variable as the script runs.

Setting Environment Variables

To set an environment variable open up the Azure Portal, navigate to your Function app and click the “Applications Settings” link.

2018-04-30 06_38_43-sleepsuntil - Microsoft Azure

Once you open applications settings tile, go down to the “Applications settings” area and click the plus sign to add a new setting. Give the new setting the key “example” and the value anything you like. You then must scroll back to the top of the page and click “Save”.

In your JavaScript function you read the application setting value from the process.env array.

Here is some code to show you the value that you just set.

module.exports = function (context, req) {
    context.res.body = process.env["example"];

    context.done();
};

API Keys From Applications Settings

Now we have a simple way to look after API keys: set the value in an application setting and read into our code using process.env. My code to connect to my Azure CosmosDB is something like this:

let url = 
  `mongodb://${process.env["cosmosdb_name"]}:${process.env["primary_master_key"]}@${process.env["cosmosdb_name"]}.documents.azure.com:10255/mean-dev?ssl=true&sslverifycertificate=false`;

One thought on “Managing Azure Functions API Keys

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

w

Connecting to %s