Pular para o conteúdo

Azure Key Vault

Este conteúdo não está disponível em sua língua ainda.

Azure Key Vault logo

Azure Key Vault helps safeguard cryptographic keys and secrets used by cloud applications and services. The Aspire Azure Key Vault integration enables you to connect to existing Azure Key Vault instances.

The Azure Key Vault hosting integration models an Azure Key Vault resource as the AzureKeyVaultResource type. To access this type and APIs, add the 📦 Aspire.Hosting.Azure.KeyVault NuGet package in your AppHost project:

Aspire CLI — Adicionar pacote Aspire.Hosting.Azure.KeyVault
aspire add azure-keyvault

A Aspire CLI é interativa; escolha o resultado adequado quando solicitado:

Aspire CLI — Exemplo de saída
Select an integration to add:
> azure-keyvault (Aspire.Hosting.Azure.KeyVault)
> Other results listed as selectable options...

In your AppHost project, call AddAzureKeyVault on the builder instance to add an Azure Key Vault resource:

C# — AppHost.cs
var builder = DistributedApplication.CreateBuilder(args);
var keyVault = builder.AddAzureKeyVault("key-vault");
builder.AddProject<Projects.ExampleProject>()
.WithReference(keyVault);
// After adding all resources, run the app...

The WithReference method configures a connection in the ExampleProject named "key-vault".

Connect to an existing Azure Key Vault instance

Section titled “Connect to an existing Azure Key Vault instance”

You might have an existing Azure Key Vault instance that you want to connect to. You can chain a call to annotate that your resource is an existing resource:

C# — AppHost.cs
var builder = DistributedApplication.CreateBuilder(args);
var existingKeyVaultName = builder.AddParameter("existingKeyVaultName");
var existingKeyVaultResourceGroup = builder.AddParameter("existingKeyVaultResourceGroup");
var keyvault = builder.AddAzureKeyVault("key-vault")
.AsExisting(existingKeyVaultName, existingKeyVaultResourceGroup);
builder.AddProject<Projects.ExampleProject>()
.WithReference(keyvault);

If you’re new to Bicep, it’s a domain-specific language for defining Azure resources. With Aspire, you don’t need to write Bicep by-hand, instead the provisioning APIs generate Bicep for you. When you add an Azure Key Vault resource, the following Bicep is generated:

:::code language=“bicep” source=”../snippets/azure/AppHost/key-vault/key-vault.bicep”:::

Generated Bicep — key-vault.bicep
@description('The location for the resource(s) to be deployed.')
param location string = resourceGroup().location
resource key_vault 'Microsoft.KeyVault/vaults@2024-11-01' = {
name: take('keyvault-${uniqueString(resourceGroup().id)}', 24)
location: location
properties: {
tenantId: tenant().tenantId
sku: {
family: 'A'
name: 'standard'
}
enableRbacAuthorization: true
}
tags: {
'aspire-resource-name': 'key-vault'
}
}
output vaultUri string = key_vault.properties.vaultUri
output name string = key_vault.name

The preceding Bicep is a module that provisions an Azure Key Vault resource. Additionally, role assignments are created for the Azure resource in a separate module:

Generated Bicep — key-vault-roles.bicep
@description('The location for the resource(s) to be deployed.')
param location string = resourceGroup().location
param key_vault_outputs_name string
param principalType string
param principalId string
resource key_vault 'Microsoft.KeyVault/vaults@2024-11-01' existing = {
name: key_vault_outputs_name
}
resource key_vault_KeyVaultSecretsUser 'Microsoft.Authorization/roleAssignments@2022-04-01' = {
name: guid(key_vault.id, principalId, subscriptionResourceId('Microsoft.Authorization/roleDefinitions', '4633458b-17de-408a-b874-0445c86b69e6'))
properties: {
principalId: principalId
roleDefinitionId: subscriptionResourceId('Microsoft.Authorization/roleDefinitions', '4633458b-17de-408a-b874-0445c86b69e6')
principalType: principalType
}
scope: key_vault
}

The generated Bicep is a starting point and is influenced by changes to the provisioning infrastructure in C#. Customizations to the Bicep file directly will be overwritten, so make changes through the C# provisioning APIs to ensure they are reflected in the generated files.

All Aspire Azure resources are subclasses of the AzureProvisioningResource type. This type enables the customization of the generated Bicep by providing a fluent API to configure the Azure resources using the ConfigureInfrastructure API. For example:

C# — AppHost.cs
var builder = DistributedApplication.CreateBuilder(args);
builder.AddAzureKeyVault("key-vault")
.ConfigureInfrastructure(infra =>
{
var keyVault = infra.GetProvisionableResources()
.OfType<KeyVaultService>()
.Single();
keyVault.Properties.Sku = new()
{
Family = KeyVaultSkuFamily.A,
Name = KeyVaultSkuName.Premium,
};
keyVault.Properties.EnableRbacAuthorization = true;
keyVault.Tags.Add("ExampleKey", "Example value");
});

The preceding code:

  • Chains a call to the ConfigureInfrastructure API:
    • The infra parameter is an instance of the AzureResourceInfrastructure type.
    • The provisionable resources are retrieved by calling the GetProvisionableResources method.
    • The single KeyVaultService resource is retrieved.
    • The Sku property is set to a new KeyVault.KeyVaultSku instance.
    • The KeyVaultProperties.EnableRbacAuthorization property is set to true.
    • A tag is added to the resource with a key of ExampleKey and a value of Example value.

There are many more configuration options available to customize the Key Vault resource. For more information, see Azure.Provisioning customization.

To get started with the Aspire Azure Key Vault client integration, install the 📦 Aspire.Azure.Security.KeyVault NuGet package:

.NET CLI — Add Aspire.Azure.Security.KeyVault package
dotnet add package Aspire.Azure.Security.KeyVault

The client integration provides two ways to access secrets from Azure Key Vault:

  • Add secrets to app configuration, using either the IConfiguration or the IOptions<T> pattern.
  • Use a SecretClient to retrieve secrets on demand.

In the Program.cs file of your client-consuming project, call the AddAzureKeyVaultSecrets extension method on the IConfiguration to add the secrets as part of your app’s configuration. The method takes a connection name parameter:

builder.Configuration.AddAzureKeyVaultSecrets(connectionName: "key-vault");

You can then retrieve a secret-based configuration value through the normal IConfiguration APIs, or by binding to strongly-typed classes with the options pattern.

public class ExampleService(IConfiguration configuration)
{
// Use configuration...
private string _secretValue = configuration["SecretKey"];
}
public class ExampleService(IOptions<SecretOptions> options)
{
// Use options...
private string _secretValue = options.Value.SecretKey;
}

Additional AddAzureKeyVaultSecrets API parameters are available optionally for the following scenarios:

  • Action<AzureSecurityKeyVaultSettings>? configureSettings: To set up some or all the options inline.
  • Action<SecretClientOptions>? configureClientOptions: To set up the SecretClientOptions inline.
  • AzureKeyVaultConfigurationOptions? options: To configure the AzureKeyVaultConfigurationOptions inline.

Alternatively, you can use the SecretClient directly to retrieve the secrets on demand. This requires a slightly different registration API.

In the Program.cs file of your client-consuming project, call the AddAzureKeyVaultClient extension on the IHostApplicationBuilder instance to register a SecretClient for use via the dependency injection container:

builder.AddAzureKeyVaultClient(connectionName: "key-vault");

After adding the SecretClient to the builder, you can get the SecretClient instance using dependency injection:

public class ExampleService(SecretClient client)
{
// Use client...
}

There might be situations where you want to register multiple SecretClient instances with different connection names. To register keyed Azure Key Vault clients, call the AddKeyedAzureKeyVaultClient method:

builder.AddKeyedAzureKeyVaultClient(name: "feature-toggles");
builder.AddKeyedAzureKeyVaultClient(name: "admin-portal");

Then you can retrieve the SecretClient instances using dependency injection:

public class ExampleService(
[FromKeyedServices("feature-toggles")] SecretClient featureTogglesClient,
[FromKeyedServices("admin-portal")] SecretClient adminPortalClient)
{
// Use clients...
}

The Azure Key Vault integration provides multiple options to configure the SecretClient.

The Azure Key Vault integration supports Microsoft.Extensions.Configuration. It loads the AzureSecurityKeyVaultSettings from appsettings.json or other configuration files using Aspire:Azure:Security:KeyVault key:

{
"Aspire": {
"Azure": {
"Security": {
"KeyVault": {
"DisableHealthChecks": true,
"DisableTracing": false,
"ClientOptions": {
"Diagnostics": {
"ApplicationId": "myapp"
}
}
}
}
}
}
}

The Azure Key Vault integration supports named configuration for multiple instances:

{
"Aspire": {
"Azure": {
"Security": {
"KeyVault": {
"vault1": {
"VaultUri": "https://myvault1.vault.azure.net/",
"DisableHealthChecks": true,
"ClientOptions": {
"Diagnostics": {
"ApplicationId": "myapp1"
}
}
},
"vault2": {
"VaultUri": "https://myvault2.vault.azure.net/",
"DisableTracing": true,
"ClientOptions": {
"Diagnostics": {
"ApplicationId": "myapp2"
}
}
}
}
}
}
}
}

Use the connection names when calling AddAzureKeyVaultSecrets:

builder.AddAzureKeyVaultSecrets("vault1");
builder.AddAzureKeyVaultSecrets("vault2");

You can also pass the Action<AzureSecurityKeyVaultSettings> delegate to set up options inline:

builder.AddAzureKeyVaultSecrets(
connectionName: "key-vault",
configureSettings: settings => settings.VaultUri = new Uri("KEY_VAULT_URI"));

You can also configure the SecretClientOptions:

builder.AddAzureKeyVaultSecrets(
connectionName: "key-vault",
configureClientOptions: options => options.DisableChallengeResourceVerification = true);

The following configurable options are exposed through the AzureSecurityKeyVaultSettings class:

NameDescription
CredentialThe credential used to authenticate to the Azure Key Vault.
DisableHealthChecksA boolean value that indicates whether the Key Vault health check is disabled or not.
DisableTracingA boolean value that indicates whether the OpenTelemetry tracing is disabled or not.
VaultUriA URI to the vault on which the client operates. Appears as “DNS Name” in the Azure portal.

By default, Aspire integrations enable health checks for all services. The Azure Key Vault integration includes the following health checks:

  • Adds the AzureKeyVaultSecretsHealthCheck health check, which attempts to connect to and query the Key Vault
  • Integrates with the /health HTTP endpoint, which specifies all registered health checks must pass for app to be considered ready to accept traffic

The Azure Key Vault integration uses the following log categories:

  • Azure.Core
  • Azure.Identity

The Azure Key Vault integration emits the following tracing activities using OpenTelemetry:

  • Azure.Security.KeyVault.Secrets.SecretClient

The Azure Key Vault integration currently doesn’t support metrics by default due to limitations with the Azure SDK.

Pergunte & RespondaColaboreComunidadeDiscutirAssistir