When creating Azure Functions in support of database related logic, or with any need to use a sensitive value, you probable already make sure you don’t store it in the code of the function. Bad boy/girl if you did!
Typically, you’d put configuration specific settings in the Configuration of the Azure Function App.
I was quite happy when doing so, but suddenly came across risks with storing it there. It’s stored in a config file somewhere on a filesystem you don’t know how the security of it is handled. Heck, it might even appear in a log file of the function execution.
To mitigate all of these risk, Azure KeyVault comes to the rescue! Store your secrets where they should be stored: in a highly secured encrypted replicated vault that you tightly control who has access to it.
But.. I hear you thinking, how can the function that have access to it? Simple recepy:
- Create a System Managed Identity on the Azure Function
- Assign a access policy to that Identity
- Copy the URL of the secret you want to use
- Create an application configuration setting that retrieves the Keyvault secret
- Reference the value in the function
Create System Manage Identity
In the identity section of your Function App, switch the Status of System assigned managed identity to On. Press Save.
Assign Access Policy
In your Azure Keyvault go to Access Policies and click + Add Access Policy. Only the Get permission on Secrets is required. Select the System Identity you just created in previous step, to give this permission to the Function App Identity. Press Save (you will regret this if you forget).
Retrieve the secret URL
On the secret you want to use, open it in the portal and copy the URL for it. Keep this value for the next step.
Create Application setting that references Key Vault
The cherry on the cake: linking it all together.
Create a new Application Setting in the Function App Configuration section.
Provide a name, and as value use this reference syntax:
Press Save, and your Function App will restart. The configuration value will have a check if the value can be retrieved successfully
You also have a new section in the properties of the setting when you click Edit, where you can follow the status of the link to KeyVault
Reference the setting in the function
I was almost going to say this is an optional step, but probably the most useful for the end result: reference the setting. Nothing changes of course on this side, you can work with the setting as with any other setting. In my example I use a PowerShell script, which you can just use the following syntax:
$secretvalue = $env:mysecret
Enjoy secure Azure Functions!