In today’s world, secrets and certificates are critical components of any secure application or service. And if you’re running your services in the cloud, you need a secure and scalable way to manage your secrets and certificates. This is where Azure Key Vault comes into play.
Azure Key Vault is a cloud-based service that provides a secure way to store and manage secrets, keys, and certificates. It integrates with both Azure and on-premises resources, allowing you to easily secure your applications and services.
In this tutorial, we will explore how to manage secrets and certificates with Azure Key Vault. We will cover the following topics:
- Creating an Azure Key Vault
- Managing secrets in Azure Key Vault
- Managing certificates in Azure Key Vault
- Using Azure Key Vault with Azure App Service
- Using Azure Key Vault with Azure Functions
Let’s get started!
Creating an Azure Key Vault
Before we can start managing secrets and certificates with Azure Key Vault, we need to create an Azure Key Vault instance. To do this, we will use the Azure Portal.
- Log in to the Azure Portal.
- Click on the “+ Create a resource” button in the left-hand menu.
- Search for “Key Vault” in the search bar and select “Key Vault” from the search results.
- Click on the “Create” button on the Key Vault overview page.
- Fill out the required information on the “Basics” tab, including a name for your Key Vault, your subscription, your resource group, and your preferred region.
- Click on the “Review + create” button to confirm the settings and create the Key Vault.
- Wait for the deployment to complete.
Congratulations! You have created an Azure Key Vault instance.
Managing secrets in Azure Key Vault
Now that we have a Key Vault, let’s add a secret. A secret is a secure value that can be used by your applications or services. Secrets can be anything from connection strings to API keys.
- Navigate to your Azure Key Vault instance in the Azure Portal.
- Click on the “Secrets” blade in the left-hand menu.
- Click on the “+ Generate/Import” button to add a new secret.
- Fill out the required information, including a name for your secret and the secret value.
- You can also add optional metadata and tags to your secret for better organization and searchability.
- Click on the “Create” button to add the secret to your Key Vault.
That’s it! You have now added a secret to your Azure Key Vault. But how do we access this secret from our applications and services?
To access the secret from your applications or services, you will need to authenticate with Azure Key Vault.
Azure Key Vault supports several ways to authenticate, including Azure AD identities, certificates, and shared access signatures. In this tutorial, we will use Azure AD identities for authentication.
To authenticate with Azure Key Vault using Azure AD identities, you will need to create an Azure AD application and assign it the appropriate permissions.
- Navigate to your Azure Key Vault instance in the Azure Portal.
- Click on the “Access policies” blade in the left-hand menu.
- Click on the “+ Add Access Policy” button to add a new access policy.
- Select the “Secret Management” permission and select the Azure AD application or user you want to grant access to.
- Click on the “Add” button to add the access policy.
Now that we have granted access to our Azure AD application, we can use the Azure Key Vault REST API to access our secret.
GET https://{vault-name}.vault.azure.net/secrets/{secret-name}/{secret-version}?api-version=7.2
Authorization: Bearer [access_token]
The access token must include the appropriate permissions that we assigned to our Azure AD application in the previous step.
Here’s an example of how to access the secret using the Azure Key Vault PowerShell Module:
$secret = Get-AzKeyVaultSecret -VaultName "mykeyvault" -Name "mysecret"
$secretValue = $secret.SecretValueText
That’s it! You have now successfully accessed your secret from your application or service.
Managing certificates in Azure Key Vault
In addition to secrets, Azure Key Vault also supports certificates. Certificates are used to secure communications between two parties by providing a trusted identity. Certificates can be used for a variety of purposes, including HTTPS, SSL/TLS, and code signing.
Let’s add a certificate to our Azure Key Vault instance.
- Navigate to your Azure Key Vault instance in the Azure Portal.
- Click on the “Certificates” blade in the left-hand menu.
- Click on the “+ Add” button to add a new certificate.
- Fill out the required information, including a name for your certificate, the certificate file, and a password if necessary.
- You can also add optional metadata and tags to your certificate for better organization and searchability.
- Click on the “Create” button to add the certificate to your Key Vault.
Now that we have added the certificate to our Azure Key Vault instance, let’s use it to secure an Azure App Service.
Using Azure Key Vault with Azure App Service
Azure App Service is a platform-as-a-service (PaaS) offering that allows you to easily deploy and scale web applications and APIs. App Service also supports integration with Azure Key Vault, allowing you to securely store and retrieve secrets and certificates.
To use Azure Key Vault with Azure App Service, you will need to follow these steps:
- Grant your Azure App Service access to your Azure Key Vault instance.
- Update your web app or API to use the specified secrets and certificates.
Let’s walk through these steps in more detail.
Grant your Azure App Service access to your Azure Key Vault instance
- Navigate to your Azure Key Vault instance in the Azure Portal.
- Click on the “Access policies” blade in the left-hand menu.
- Click on the “+ Add Access Policy” button to add a new access policy.
- Select the “Certificate Management” permission and select the Azure AD application or user for your Azure App Service.
- Click on the “Add” button to add the access policy.
Now that we have granted access to our Azure App Service, we can use the Azure Key Vault REST API to access our certificate.
Update your web app or API to use the specified secrets and certificates
To use your secrets and certificates with your web app or API, you will need to update your application code to retrieve the values from Azure Key Vault.
Here’s an example of how to retrieve a secret from Azure Key Vault in .NET Core:
using Azure.Extensions.AspNetCore.Configuration.Secrets;
using Azure.Identity;
using Microsoft.AspNetCore.Hosting;
using Microsoft.Extensions.Hosting;
public class Program
{
public static void Main(string[] args)
{
CreateHostBuilder(args).Build().Run();
}
public static IHostBuilder CreateHostBuilder(string[] args) =>
Host.CreateDefaultBuilder(args)
.ConfigureWebHostDefaults(webBuilder =>
{
webBuilder.UseStartup<Startup>()
.ConfigureAppConfiguration((context, configBuilder) =>
{
var builtConfig = configBuilder.Build();
var secretClient = new SecretClient(new(builtConfig["KeyVault:Url"]),
new DefaultAzureCredential());
configBuilder.AddAzureKeyVault(secretClient, new());
});
});
}
This code uses the AddAzureKeyVault
method from the Microsoft.Extensions.Configuration.AzureKeyVault NuGet package to retrieve the secrets from Azure Key Vault.
Here’s an example of how to retrieve a certificate from Azure Key Vault in .NET Core:
using Azure.Identity;
using Azure.Security.KeyVault.Certificates;
using Azure.Security.KeyVault.Secrets;
using System.Security.Cryptography.X509Certificates;
private async Task<X509Certificate2> GetCertificateAsync()
{
var secretClient = new SecretClient(new Uri("https://{vault-name}.vault.azure.net/"),
new DefaultAzureCredential());
var certificateClient = new CertificateClient(new Uri("https://{vault-name}.vault.azure.net/"),
new DefaultAzureCredential());
var secret = await secretClient.GetSecretAsync("my-cert-secret");
var certificate = await certificateClient.GetCertificateAsync("my-cert");
var certBytes = Convert.FromBase64String(secret.Value.Value);
var privateKeyBytes = certificate.Value.Key.Export(CertificateKeyFormat.Pem);
var certWithPrivateKeyBytes = new byte[certBytes.Length + privateKeyBytes.Length];
Buffer.BlockCopy(certBytes, 0, certWithPrivateKeyBytes, 0, certBytes.Length);
Buffer.BlockCopy(privateKeyBytes, 0, certWithPrivateKeyBytes, certBytes.Length, privateKeyBytes.Length);
return new X509Certificate2(certWithPrivateKeyBytes, "",
X509KeyStorageFlags.MachineKeySet | X509KeyStorageFlags.PersistKeySet | X509KeyStorageFlags.Exportable);
}
This code uses the SecretClient
and CertificateClient
from the Azure SDK for .NET to retrieve the secret and certificate from Azure Key Vault, respectively. It then combines the private key with the certificate to create an X.509 certificate object.
That’s it! You have now successfully secured your Azure App Service using certificates stored in Azure Key Vault.
Using Azure Key Vault with Azure Functions
Azure Functions is a serverless compute service that allows you to run code on demand, without having to manage infrastructure. Like Azure App Service, Azure Functions also supports integration with Azure Key Vault.
To use Azure Key Vault with Azure Functions, you will need to follow these steps:
- Grant your Azure Function app access to your Azure Key Vault instance.
- Update your function code to use the specified secrets and certificates.
Let’s walk through these steps in more detail.
Grant your Azure Function app access to your Azure Key Vault instance
- Navigate to your Azure Key Vault instance in the Azure Portal.
- Click on the “Access policies” blade in the left-hand menu.
- Click on the “+ Add Access Policy” button to add a new access policy.
- Select the “Certificate Management” permission and select the Azure AD application or user for your Azure Function app.
- Click on the “Add” button to add the access policy.
Now that we have granted access to our Azure Function app, we can use the Azure Key Vault REST API to access our certificate.
Update your function code to use the specified secrets and certificates
To use your secrets and certificates with your function code, you will need to update your function bindings and/or code to retrieve the values from Azure Key Vault.
Here’s an example of how to retrieve a secret from Azure Key Vault in a C# function:
using System.Threading.Tasks;
using Microsoft.Azure.Functions.Worker;
using Microsoft.Azure.Functions.Worker.Http;
using Microsoft.Extensions.Logging;
using Microsoft.Extensions.Configuration.AzureKeyVault;
using Azure.Identity;
using Azure.Security.KeyVault.Secrets;
public static class MyFunction
{
[Function("MyFunction")]
public static async Task<HttpResponseData> RunAsync([HttpTrigger(AuthorizationLevel.Function, "get", "post")] HttpRequestData req,
FunctionContext executionContext)
{
var config = new ConfigurationBuilder()
.AddAzureKeyVault(new SecretClient(new Uri(Environment.GetEnvironmentVariable("KeyVaultEndpoint")),
new DefaultAzureCredential()), new DefaultKeyVaultSecretManager())
.Build();
var secretValue = config["my-secret"];
// Do something with secretValue
var response = req.CreateResponse();
await response.WriteStringAsync($"Secret value: {secretValue}");
return response;
}
}
This code uses the AddAzureKeyVault
method from the Microsoft.Extensions.Configuration.AzureKeyVault NuGet package to retrieve the secrets from Azure Key Vault. Notice that we are passing in an instance of the SecretClient
, which we authenticate using the DefaultAzureCredential
class.
Here’s an example of how to retrieve a certificate from Azure Key Vault in a C# function:
using System.Security.Cryptography.X509Certificates;
using System.Threading.Tasks;
using Microsoft.Azure.Functions.Worker;
using Microsoft.Azure.Functions.Worker.Http;
using Microsoft.Extensions.Logging;
using Azure.Identity;
using Azure.Security.KeyVault.Certificates;
using Azure.Security.KeyVault.Secrets;
public static class MyFunction
{
[Function("MyFunction")]
public static async Task<HttpResponseData> RunAsync([HttpTrigger(AuthorizationLevel.Function, "get", "post")] HttpRequestData req,
FunctionContext executionContext)
{
var secretClient = new SecretClient(new Uri(Environment.GetEnvironmentVariable("KeyVaultEndpoint")),
new DefaultAzureCredential());
var certificateClient = new CertificateClient(new Uri(Environment.GetEnvironmentVariable("KeyVaultEndpoint")),
new DefaultAzureCredential());
var secret = await secretClient.GetSecretAsync("my-cert-secret");
var certificate = await certificateClient.GetCertificateAsync("my-cert");
var certBytes = Convert.FromBase64String(secret.Value.Value);
var privateKeyBytes = certificate.Value.Key.Export(CertificateKeyFormat.Pem);
var certWithPrivateKeyBytes = new byte[certBytes.Length + privateKeyBytes.Length];
Buffer.BlockCopy(certBytes, 0, certWithPrivateKeyBytes, 0, certBytes.Length);
Buffer.BlockCopy(privateKeyBytes, 0, certWithPrivateKeyBytes, certBytes.Length, privateKeyBytes.Length);
var x509Cert = new X509Certificate2(certWithPrivateKeyBytes, "",
X509KeyStorageFlags.MachineKeySet | X509KeyStorageFlags.PersistKeySet | X509KeyStorageFlags.Exportable);
// Do something with x509Cert
var response = req.CreateResponse();
await response.WriteStringAsync($"Certificate subject: {x509Cert.Subject}");
return response;
}
}
This code uses the SecretClient
and CertificateClient
from the Azure SDK for .NET to retrieve the secret and certificate from Azure Key Vault, respectively. It then combines the private key with the certificate to create an X.509 certificate object.
That’s it! You have now successfully secured your Azure Function app using certificates stored in Azure Key Vault.
Conclusion
In this tutorial, we explored how to manage secrets and certificates with Azure Key Vault. We created an Azure Key Vault instance, added a secret and certificate, and then used them to secure an Azure App Service and Azure Function app.
By using Azure Key Vault to manage your secrets and certificates, you can easily secure your applications and services while scaling seamlessly in the cloud.