Setting up Azure Key Vault

Key Vault is an Azure module, which lets you safely store your secrets/keys. This way your developers do not have to store credentials or connection strings in the code, but can simpy ask Key Vault to provide them. The application will be handed the password and will be able to log in without the developer even knowing it. Let us create a key vault!

Creating Key Vault

image

To create a Key Vault (just like you probably expect), simply search for it in Azure. When creating your Key Vault you may specify access policies for your account. For now, you can leave it with default values. You may experiment it with more, once you set up the service.

Registering you app with Azure Active Directory

To enable access to the secrets by Function App, you have to register your app in Azure Active Directory. Only then will you app be able to authenticate with Key Vault.

Open your Function App and navigate to Platform features:

image

Click on Managed service indentity and register with AAD:

image

 

 

Alternatively, you can use Powershell:

 

Now that the app is registered with AAD, you can add it in access policies in your Key Vault. To do that, go to access policies:

image

Click add new, select principal (you app name), specify permissions and click OK:

image

Now, your app can access your secrets! Even if you have no permission to see the secrets, you still can use them in an app.

Creating a secret

image

Go to Secrets in the main Settings pane. In there you can enter your passwords, which will be accessable only by specified people/apps. Click on Generate/Import and add a password:

 

image
image

 

After creating a secret, copy its identifier. This URL can be specified as an environmental variable or pasted into the code like in the example below.

image

Accessing secrets through Function App

Now, you are ready to create a function and access the secret with code.

Go to Visual Studio and create a new function with HTTP Trigger.

image
image

You have to include two namespaces:

 

Next add three lines into the code:

 

Also change what the function returns to:

 

Whole code:

 

After you publish the function, you can run the function from within Azure portal to get your secret:

image

Hope this helps.

Michał

Leave a Reply

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