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

在调用Microsoft Graph的.NET Worker服务中从Key Vault加载Azure AD客户端密钥

.NET 8 Worker服务从Azure Key Vault加载客户端密钥配置Microsoft Graph

前提准备

  1. 在Azure Key Vault中创建存储客户端密钥的机密,假设机密名称为AzureAd-ClientSecret(可自定义,后续需对应),将原appsettings中的secretvalue存入该机密。
  2. 确保Worker服务的身份(本地开发用Azure CLI/Visual Studio身份,生产用托管标识)拥有Key Vault的机密读取权限。

步骤1:安装必要NuGet包

在项目中安装以下包:

dotnet add package Azure.Extensions.AspNetCore.Configuration.Secrets
dotnet add package Azure.Identity

步骤2:集成Key Vault到配置系统

修改Program.cs中的配置加载逻辑,添加Key Vault配置源:

var builder = Host.CreateDefaultBuilder(args);

// 集成Azure Key Vault
builder.ConfigureAppConfiguration((context, config) =>
{
    var builtConfig = config.Build();
    var keyVaultUri = new Uri(builtConfig["KeyVault:Uri"]); // 从appsettings读取Key Vault地址

    // 使用DefaultAzureCredential自动适配本地/生产环境身份
    config.AddAzureKeyVault(keyVaultUri, new DefaultAzureCredential());
})
.ConfigureServices((hostContext, services) =>
{
    // 原有的Microsoft Graph配置代码
    services
        .AddTokenAcquisition(isTokenAcquisitionSingleton: true)
        .Configure<MicrosoftIdentityApplicationOptions>(hostContext.Configuration.GetSection("AzureAd"))
        .AddInMemoryTokenCaches()
        .AddHttpClient();

    services.AddMicrosoftGraph(hostContext.Configuration.GetSection("MicrosoftGraph"));

    services.AddHostedService<Worker>();
});

var host = builder.Build();
host.Run();

步骤3:调整appsettings.json配置

方式A:配置系统自动匹配覆盖

保留原AzureAd结构,配置系统会自动通过Key Vault中对应路径的机密覆盖配置值。比如Key Vault机密名称设为AzureAd-ClientCredentials-0-ClientSecret,会自动匹配AzureAd:ClientCredentials:0:ClientSecret的配置项:

{
  "KeyVault": {
    "Uri": "https://your-keyvault-name.vault.azure.net/"
  },
  "AzureAd": {
    "Instance": "https://login.microsoftonline.com/",
    "TenantId": "xxx",
    "ClientId": "xxx",
    "ClientCredentials": [
      {
        "SourceType": "ClientSecret",
        "ClientSecret": "" // 由Key Vault机密自动覆盖
      }
    ],
    "Domain": "xxx.onmicrosoft.com"
  },
  "MicrosoftGraph": {
    "BaseUrl": "https://graph.microsoft.com/v1.0"
  }
}

方式B:手动读取机密赋值

如果需要更灵活的控制,可手动从配置中读取Key Vault机密,再赋值给MicrosoftIdentityApplicationOptions:

.ConfigureServices((hostContext, services) =>
{
    services
        .AddTokenAcquisition(isTokenAcquisitionSingleton: true)
        .Configure<MicrosoftIdentityApplicationOptions>(options =>
        {
            // 绑定基础AzureAd配置
            hostContext.Configuration.GetSection("AzureAd").Bind(options);
            // 替换为Key Vault中的客户端密钥
            options.ClientCredentials[0].ClientSecret = hostContext.Configuration["AzureAd-ClientSecret"];
        })
        .AddInMemoryTokenCaches()
        .AddHttpClient();

    services.AddMicrosoftGraph(hostContext.Configuration.GetSection("MicrosoftGraph"));

    services.AddHostedService<Worker>();
});

验证运行

本地开发时,确保已通过Azure CLI登录(az login)或Visual Studio已关联Azure账户;生产环境部署到Azure时,给Worker服务分配托管标识,并授予该标识Key Vault的机密读取权限,即可自动加载密钥运行。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.26 22:42:45