Using Key Vault in Azure Functions
Tags: csharp, azure, cloudskills
Published: 2022-12-09 05:02:34

## Create a Key Vault

First, create a Key Vault in Azure named jack-keyvault, which contains:

| Secret  | Value       |
| ------- | ----------- |
| TestKey | Hello World |

As shown below:

![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/rfl9k8u6vp3t7nyljdoi.png)

## Test the Function App locally

Create a Function App:

```
func init KeyVaultFunction --dotnet
```

Install Key Vault's dependencies:

```
cd KeyVaultFunction
dotnet restore
dotnet add package Azure.Identity
dotnet add package Azure.Security.KeyVault.Secrets
```

Then add a Http-Triggered function, I named it **HttpTrigger.cs** and paste the following code:

```csharp
using System;
using Azure.Security.KeyVault.Secrets;
using Azure.Identity;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Azure.WebJobs;
using Microsoft.Azure.WebJobs.Extensions.Http;
using Microsoft.AspNetCore.Http;
using Microsoft.Extensions.Logging;

namespace KeyVaultFunction
{
    public class HttpTrigger
    {
        [FunctionName("HttpTrigger")]
        public IActionResult Run(
            [HttpTrigger(AuthorizationLevel.Anonymous, "get", "post", Route = null)]
                HttpRequest req,
            ILogger log
        )
        {
            try {
                string keyVaultUrl = Environment.GetEnvironmentVariable("KEY_VAULT_URL")!;
                string secretName = Environment.GetEnvironmentVariable("SECRET_NAME")!;

                var client = new SecretClient(new Uri(keyVaultUrl), new DefaultAzureCredential());
                KeyVaultSecret secret = client.GetSecret(secretName);
                log.LogInformation($"Successfully get Key Vault from: {keyVaultUrl}. Secret name: {secretName}");

                return new OkObjectResult(secret.Value);
            }
            catch (Exception ex)
            {
                log.LogInformation($"Exception occurred. Source: {ex.Source}. Message: {ex.Message}");
                return new BadRequestObjectResult($"Exception occurred. Source: {ex.Source}. Message: {ex.Message}");
            }
        }
    }
}
```

When the user triggers this function, this code will read the values of `KEY_VAULT_URL` and `SECRET_NAME` from **local.settings.json**, then request Key Vault to return the value of the secret, and finally display the result and return it to the user through `OkObjectResult` .

```json
{
    "IsEncrypted": false,
    "Values": {
        "AzureWebJobsStorage": "UseDevelopmentStorage=true",
        "FUNCTIONS_WORKER_RUNTIME": "dotnet",
        "KEY_VAULT_URL": "https://jack-keyvault.vault.azure.net/",
        "SECRET_NAME": "TestKey"
    }
}
```

Now you can test it locally. First log in to Azure to allow `SecretClient` to verify the identity of you, and then execute the Function App:

```
az login
func start
```

Test whether the Function App can get the secret:

```
curl http://localhost:7071/api/HttpTrigger
Hello World
```

## Test Function App in Azure Portal

First create a Function App, I named it Jack1, then enable its Identity, and press Save:

![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/070halmzpaaoj1bmidr0.png)

Fill in the `KEY_VAULT_URL` and `SECRET_NAME` that just appeared in **local.settings.json** into Configuration, and then press Save:

![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/8whlv6v34nrc3ey03exz.png)

Then go back to Key Vault to add an Access Policy, and then press Save, so that Function App can get the secret data:

![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/7iken6p2ah5j3zhhz8ji.png)

Then push the Function App to Azure:

```
func azure functionapp publish Jack1
```

Then open https://jack1.azurewebsites.net/api/httptrigger through the browser to see the Hello World string.