Connect to Azure Key Vault
此内容尚不支持你的语言。
This page describes how consuming apps connect to an Azure Key Vault resource that’s already modeled in your AppHost. For the AppHost API surface — adding a Key Vault resource, role assignments, secret references, and infrastructure customization — see Azure Key Vault Hosting integration.
When you reference an Azure Key Vault resource from your AppHost, Aspire injects the vault URI into the consuming app as an environment variable. Your app can either read that environment variable directly — the pattern works the same from any language — or, in C#, use the Aspire Azure Key Vault client integration for automatic dependency injection, health checks, and telemetry.
Connection properties
Section titled “Connection properties”Aspire exposes each property as an environment variable named [RESOURCE]_[PROPERTY]. For instance, the Uri property of a resource called key-vault becomes KEY_VAULT_URI.
The Azure Key Vault resource exposes the following connection property:
| Property Name | Description |
|---|---|
Uri | The Key Vault endpoint URI, typically https://<vault-name>.vault.azure.net/ |
Example connection value:
Uri: https://keyvault-abc123.vault.azure.net/Connect from your app
Section titled “Connect from your app”Pick the language your consuming app is written in. Each example assumes your AppHost adds an Azure Key Vault resource named key-vault and references it from the consuming app.
For C# apps, the recommended approach is the Aspire Azure Key Vault client integration. It registers an SecretClient through dependency injection and adds health checks and telemetry automatically. The integration also provides an optional configuration provider that surfaces vault secrets through the standard IConfiguration API.
Install the client integration
Section titled “Install the client integration”Install the 📦 Aspire.Azure.Security.KeyVault NuGet package in the client-consuming project:
dotnet add package Aspire.Azure.Security.KeyVault#:package Aspire.Azure.Security.KeyVault@*<PackageReference Include="Aspire.Azure.Security.KeyVault" Version="*" />Add the Azure Key Vault client
Section titled “Add the Azure Key Vault client”In Program.cs, call AddAzureKeyVaultClient on your IHostApplicationBuilder to register a SecretClient:
builder.AddAzureKeyVaultClient(connectionName: "key-vault");Resolve the SecretClient through dependency injection:
public class ExampleService(SecretClient secretClient){ public async Task<string> GetSecretAsync(string secretName) { var secret = await secretClient.GetSecretAsync(secretName); return secret.Value.Value; }}Add secrets to configuration
Section titled “Add secrets to configuration”Alternatively, call AddAzureKeyVaultSecrets to surface vault secrets through the IConfiguration API. This is useful for reading secrets with the options pattern or IConfiguration directly:
builder.Configuration.AddAzureKeyVaultSecrets(connectionName: "key-vault");You can then read secrets by name through IConfiguration or bind them to strongly-typed options:
public class ExampleService(IConfiguration configuration){ private string _apiKey = configuration["my-secret-name"];}public class ExampleService(IOptions<MyOptions> options){ private string _apiKey = options.Value.MySecretName;}Add keyed Azure Key Vault clients
Section titled “Add keyed Azure Key Vault clients”To register multiple SecretClient instances with different vault names, use AddKeyedAzureKeyVaultClient:
builder.AddKeyedAzureKeyVaultClient(name: "feature-toggles");builder.AddKeyedAzureKeyVaultClient(name: "admin-portal");Then resolve each instance by key:
public class ExampleService( [FromKeyedServices("feature-toggles")] SecretClient featureTogglesClient, [FromKeyedServices("admin-portal")] SecretClient adminPortalClient){ // Use clients...}For more information, see .NET dependency injection: Keyed services.
Configuration
Section titled “Configuration”The Aspire Azure Key Vault client integration offers multiple ways to provide configuration.
Connection strings. When using a connection string from the ConnectionStrings configuration section, pass the connection name to AddAzureKeyVaultClient:
builder.AddAzureKeyVaultClient("key-vault");The connection string is resolved from the ConnectionStrings section:
{ "ConnectionStrings": { "key-vault": "https://myvault.vault.azure.net/" }}Configuration providers. The client integration supports Microsoft.Extensions.Configuration. It loads AzureSecurityKeyVaultSettings from appsettings.json (or any other configuration source) by using the Aspire:Azure:Security:KeyVault key:
{ "Aspire": { "Azure": { "Security": { "KeyVault": { "DisableHealthChecks": true, "DisableTracing": false, "ClientOptions": { "Diagnostics": { "ApplicationId": "myapp" } } } } } }}Inline delegates. Pass an Action<AzureSecurityKeyVaultSettings> to configure settings inline:
builder.AddAzureKeyVaultClient( connectionName: "key-vault", configureSettings: settings => settings.DisableHealthChecks = true);Client integration health checks
Section titled “Client integration health checks”Aspire client integrations enable health checks by default. The Azure Key Vault client integration adds:
- The
AzureKeyVaultSecretsHealthCheck, which attempts to connect to and query the vault. - Integration with the
/healthHTTP endpoint, where all registered health checks must pass before the app is considered ready to accept traffic.
Observability and telemetry
Section titled “Observability and telemetry”The Aspire Azure Key Vault client integration automatically configures logging and tracing through OpenTelemetry.
Logging categories:
Azure.CoreAzure.Identity
Tracing activities:
Azure.Security.KeyVault.Secrets.SecretClient
Metrics: The Azure Key Vault integration currently doesn’t support metrics by default due to limitations with the Azure SDK.
Install the Azure Key Vault Secrets client library for Go and the Azure Identity library for authentication:
go get github.com/Azure/azure-sdk-for-go/sdk/security/keyvault/azsecretsgo get github.com/Azure/azure-sdk-for-go/sdk/azidentityRead the Aspire-injected vault URI and create a client:
package main
import ( "context" "fmt" "os"
"github.com/Azure/azure-sdk-for-go/sdk/azidentity" "github.com/Azure/azure-sdk-for-go/sdk/security/keyvault/azsecrets")
func main() { // Read the Aspire-injected vault URI vaultURI := os.Getenv("KEY_VAULT_URI")
cred, err := azidentity.NewDefaultAzureCredential(nil) if err != nil { panic(err) }
client, err := azsecrets.NewClient(vaultURI, cred, nil) if err != nil { panic(err) }
resp, err := client.GetSecret(context.Background(), "my-secret-name", "", nil) if err != nil { panic(err) }
fmt.Println("Secret value:", *resp.Value)}Install the Azure Key Vault Secrets client library and the Azure Identity library:
pip install azure-keyvault-secrets azure-identityRead the Aspire-injected vault URI and create a client:
import osfrom azure.identity import DefaultAzureCredentialfrom azure.keyvault.secrets import SecretClient
# Read the Aspire-injected vault URIvault_uri = os.getenv("KEY_VAULT_URI")
credential = DefaultAzureCredential()client = SecretClient(vault_url=vault_uri, credential=credential)
secret = client.get_secret("my-secret-name")print("Secret value:", secret.value)Install the Azure Key Vault Secrets client library and the Azure Identity library:
npm install @azure/keyvault-secrets @azure/identityRead the Aspire-injected vault URI and create a client:
import { SecretClient } from '@azure/keyvault-secrets';import { DefaultAzureCredential } from '@azure/identity';
// Read the Aspire-injected vault URIconst vaultUri = process.env.KEY_VAULT_URI!;
const credential = new DefaultAzureCredential();const client = new SecretClient(vaultUri, credential);
const secret = await client.getSecret('my-secret-name');console.log('Secret value:', secret.value);