Microsoft Azure – Using Azure Key Vaults
In this article, you will learn how to use secure configuration for Azure Functions with Azure Key Vault. You can secure secrets in Azure Key Vault and read them easily in an Azure Function. Azure Key Vault is a cloud service for securely storing and accessing secrets. A secret is anything that you want to tightly control access to, such as API keys, passwords, certificates, or cryptographic keys.
Follow the below steps to use secure configuration for azure functions with Azure key vault:
Step 1: In Visual Studio 2019. Create a new Azure Function here. You can also use Visual Studio Code or another tool to do this if you want.
Step 2: Give it a name and hit “Create”.
Step 3: Now, pick the HTTP trigger and set that to anonymous so that you can test it easily.
Step 4: Now, in the function add a couple of lines of code. These read the application settings called, MySecret from the configuration of the function, and it will show the value in the log.
Step 5: Finally, publish it. Again, create a new Azure Function.
Step 6: Pick your resource group and select another location. While this is working, switch to the Azure portal.
Step 7: Here, you are going to create an Azure Key Vault. Select your resource group again and give the Key Vault a name. Create it.
Step 8: Switch to the Azure Function. This has now been published to Azure. Here, you need to go to Platform features and Identity. Because there you can create an Azure Managed Service Identity for the function, you will use that to connect to Azure Key Vault without needing API keys.
Step 9: Now, go back to the Key Vault that has now been deployed. In here, go to “Access policies”, and add one here.
Step 10: Add an Access policy for the Azure Function Managed Identity and it will be able to do whatever it wants with Key Vault secrets. Save it.
Step 11: Now add a secret. Generate and import, name it as you want, and give it a value, which is secret value and create it.
Step 12: The secret has one version, and has the details. You will need the Secret Identifier, so copy it and now go back to the Azure Function.
Step 13: Go to Configuration. Here, you will add a new item. The name of the item will be MySecret. This has nothing to do with a Key Vault secret, but it has to do with the value that the code in the Azure function will read. Now, here is a nifty part. In the value, you put this, this format references the Azure Key Vault and gets the secret with the identifier that you have just copied. So you don’t have to connect to the Key Vault in any way, just use this format as the Managed Service Identity. Now save it.
Step 14: Now, test the function and run it. Take a look at the log. The secret value comes directly from Azure Key Vault. Connecting Azure Key Vault to Azure Functions is easy.
Hence, this is how you can use Azure Functions and secure configuration with Azure Key Vaults.