Azure Key Vault
此内容尚不支持你的语言。
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.
Hosting integration
Section titled “Hosting integration”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 add azure-keyvaultAspire CLI 是交互式的;按提示选择合适的搜索结果:
Select an integration to add:
> azure-keyvault (Aspire.Hosting.Azure.KeyVault)> Other results listed as selectable options...#:package Aspire.Hosting.Azure.KeyVault@*<PackageReference Include="Aspire.Hosting.Azure.KeyVault" Version="*" />Add Azure Key Vault resource
Section titled “Add Azure Key Vault resource”In your AppHost project, call AddAzureKeyVault on the builder instance to add an Azure Key Vault resource:
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:
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);Provisioning-generated Bicep
Section titled “Provisioning-generated Bicep”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”:::
@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.nameThe 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:
@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.
Customize provisioning infrastructure
Section titled “Customize provisioning infrastructure”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:
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
ConfigureInfrastructureAPI:- The
infraparameter is an instance of theAzureResourceInfrastructuretype. - The provisionable resources are retrieved by calling the
GetProvisionableResourcesmethod. - The single
KeyVaultServiceresource is retrieved. - The
Skuproperty is set to a newKeyVault.KeyVaultSkuinstance. - The
KeyVaultProperties.EnableRbacAuthorizationproperty is set totrue. - A tag is added to the resource with a key of
ExampleKeyand a value ofExample value.
- The
There are many more configuration options available to customize the Key Vault resource. For more information, see Azure.Provisioning customization.
Client integration
Section titled “Client integration”To get started with the Aspire Azure Key Vault client integration, install the 📦 Aspire.Azure.Security.KeyVault NuGet package:
dotnet add package Aspire.Azure.Security.KeyVault#:package Aspire.Azure.Security.KeyVault@*<PackageReference Include="Aspire.Azure.Security.KeyVault" Version="*" />The client integration provides two ways to access secrets from Azure Key Vault:
- Add secrets to app configuration, using either the
IConfigurationor theIOptions<T>pattern. - Use a
SecretClientto retrieve secrets on demand.
Add secrets to configuration
Section titled “Add secrets to configuration”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.
Retrieve IConfiguration instance
Section titled “Retrieve IConfiguration instance”public class ExampleService(IConfiguration configuration){ // Use configuration... private string _secretValue = configuration["SecretKey"];}Retrieve IOptions<T> instance
Section titled “Retrieve IOptions<T> instance”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 theSecretClientOptionsinline.AzureKeyVaultConfigurationOptions? options: To configure theAzureKeyVaultConfigurationOptionsinline.
Add an Azure Secret client
Section titled “Add an Azure Secret client”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...}Add keyed Azure Key Vault client
Section titled “Add keyed Azure Key Vault 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...}Configuration
Section titled “Configuration”The Azure Key Vault integration provides multiple options to configure the SecretClient.
Use configuration providers
Section titled “Use configuration providers”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" } } } } } }}Use named configuration
Section titled “Use named configuration”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");Use inline delegates
Section titled “Use inline delegates”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);Configuration options
Section titled “Configuration options”The following configurable options are exposed through the AzureSecurityKeyVaultSettings class:
| Name | Description |
|---|---|
Credential | The credential used to authenticate to the Azure Key Vault. |
DisableHealthChecks | A boolean value that indicates whether the Key Vault health check is disabled or not. |
DisableTracing | A boolean value that indicates whether the OpenTelemetry tracing is disabled or not. |
VaultUri | A URI to the vault on which the client operates. Appears as “DNS Name” in the Azure portal. |
Client integration health checks
Section titled “Client integration health checks”By default, Aspire integrations enable health checks for all services. The Azure Key Vault integration includes the following health checks:
- Adds the
AzureKeyVaultSecretsHealthCheckhealth check, which attempts to connect to and query the Key Vault - Integrates with the
/healthHTTP endpoint, which specifies all registered health checks must pass for app to be considered ready to accept traffic
Observability and telemetry
Section titled “Observability and telemetry”Logging
Section titled “Logging”The Azure Key Vault integration uses the following log categories:
Azure.CoreAzure.Identity
Tracing
Section titled “Tracing”The Azure Key Vault integration emits the following tracing activities using OpenTelemetry:
Azure.Security.KeyVault.Secrets.SecretClient
Metrics
Section titled “Metrics”The Azure Key Vault integration currently doesn’t support metrics by default due to limitations with the Azure SDK.