You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Azure Service Fabric应用无法读取Azure Key Vault中的密钥

在Azure Service Fabric应用中读取Azure Key Vault密钥的替代实现方式

问题描述

我正尝试在Azure Service Fabric应用中读取Azure Key Vault中的密钥。在Visual Studio中运行时,Service Fabric似乎并未使用我VS中的Azure AD账户进行身份认证,而是尝试使用环境变量或托管身份,但均失败。在Service Fabric应用中是否有其他实现方式?

现有代码

var builder = new ConfigurationBuilder()
        .SetBasePath(_Environment.ContentRootPath)
        .AddJsonFile("appsettings.json", optional: true, reloadOnChange: true)
        .AddJsonFile($"appsettings.{envName}.json", optional: true, reloadOnChange: true)
        .AddEnvironmentVariables();


var keyValutName = Configuration["KeyVaultName"];
builder.AddAzureKeyVault(
        new SecretClient(
            new Uri($"https://{keyValutName}.vault.azure.net/"),
            new DefaultAzureCredential()),
        new AzureKeyVaultConfigurationOptions()
    );

Configuration = builder.Build();

错误信息

Azure.Identity.CredentialUnavailableException: 'DefaultAzureCredential
failed to retrieve a token from the included credentials. See the
troubleshooting guide for more information.

  • EnvironmentCredential authentication unavailable.

Environment variables are not fully configured. See the
troubleshooting guide for more information.

  • ManagedIdentityCredential authentication unavailable. The requested identity has not been assigned to this resource.

Status: 400 (Bad Request)

可行的实现方案

1. 强制使用Visual Studio凭据(本地调试)

修改DefaultAzureCredential的配置,明确优先使用Visual Studio的身份上下文,解决本地调试时的身份隔离问题:

var credential = new DefaultAzureCredential(new DefaultAzureCredentialOptions
{
    // 可选:指定租户ID,避免多租户账户下的歧义
    VisualStudioTenantId = "你的Azure AD租户ID",
    CredentialProcessTimeout = TimeSpan.FromSeconds(30)
});

builder.AddAzureKeyVault(
    new SecretClient(
        new Uri($"https://{keyValutName}.vault.azure.net/"),
        credential),
    new AzureKeyVaultConfigurationOptions()
);

2. 应用托管身份(生产环境推荐)

部署到Azure集群时,给Service Fabric应用分配托管身份,并配置Key Vault访问权限:

  • 在Azure门户中为Service Fabric应用启用系统分配或用户分配的托管身份
  • 打开目标Key Vault的访问策略,添加该托管身份,授予机密读取权限
  • 代码无需修改,DefaultAzureCredential会自动识别并使用托管身份完成认证

3. 本地调试临时方案:环境变量认证

手动设置本地环境变量,指定身份信息(仅用于调试,不建议生产使用):

  • 若使用服务主体:设置AZURE_CLIENT_ID、AZURE_TENANT_ID、AZURE_CLIENT_SECRET
  • 若使用个人账户:设置AZURE_USERNAME和AZURE_PASSWORD

4. 借助Azure CLI凭据

确保本地已通过az login登录Azure CLI,然后配置DefaultAzureCredential优先使用CLI凭据:

var credential = new DefaultAzureCredential(new DefaultAzureCredentialOptions
{
    ExcludeVisualStudioCredential = false,
    ExcludeAzureCliCredential = false
});

内容的提问来源于stack exchange,提问作者Flea

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.09 16:05:31