DEV Community

Jack Lin
Jack Lin

Posted on • Edited on

Using Key Vault in Azure Functions

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

Test the Function App locally

Create a Function App:

func init KeyVaultFunction --dotnet
Enter fullscreen mode Exit fullscreen mode

Install Key Vault's dependencies:

cd KeyVaultFunction
dotnet restore
dotnet add package Azure.Identity
dotnet add package Azure.Security.KeyVault.Secrets
Enter fullscreen mode Exit fullscreen mode

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

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}");
            }
        }
    }
}
Enter fullscreen mode Exit fullscreen mode

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 .

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

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
Enter fullscreen mode Exit fullscreen mode

Test whether the Function App can get the secret:

curl http://localhost:7071/api/HttpTrigger
Hello World
Enter fullscreen mode Exit fullscreen mode

Test Function App in Azure Portal

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

Image description

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

Image description

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

Then push the Function App to Azure:

func azure functionapp publish Jack1
Enter fullscreen mode Exit fullscreen mode

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

Top comments (0)