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

仅通过设备安装的证书访问Azure KeyVault密钥的相关问题咨询

证书认证访问Azure Key Vault实现方案

报错原因

你遇到的unknown_user_type: Unknown User Type报错是因为默认AzureServiceTokenProvider会优先尝试Active Directory集成认证,你的服务账号不支持该认证模式。

前置准备

  • 在Azure Active Directory中注册应用,记录该应用的客户端ID、所属租户的租户ID
  • 为该注册应用上传带私钥的PFX格式证书,也可以直接在Azure门户生成证书后下载PFX文件
  • 进入目标Key Vault的访问策略配置页,为该注册应用授予机密读取权限,保存生效
  • 将证书部署到代码运行环境,可选择存入系统证书存储,或直接保存PFX文件到本地路径(需妥善保管PFX的访问密码)

依赖安装

需要先安装以下两个官方NuGet包:

  • Azure.Identity:Azure官方认证类库
  • Azure.Security.KeyVault.Secrets:Key Vault机密操作专用类库

代码实现

直接加载PFX文件的示例

using Azure.Identity;
using Azure.Security.KeyVault.Secrets;
using System.Security.Cryptography.X509Certificates;

public static string GetKeyVaultSecret(string keyVaultName, string secretName, string tenantId, string clientId, string pfxFilePath, string pfxPassword)
{
    // 加载PFX证书
    X509Certificate2 certificate = new X509Certificate2(
        pfxFilePath, 
        pfxPassword, 
        X509KeyStorageFlags.MachineKeySet | X509KeyStorageFlags.PersistKeySet
    );

    // 构造证书认证凭据
    ClientCertificateCredential credential = new ClientCertificateCredential(tenantId, clientId, certificate);

    // 初始化Key Vault机密客户端
    SecretClient secretClient = new SecretClient(
        new Uri($"https://{keyVaultName}.vault.azure.net/"),
        credential
    );

    // 读取机密
    KeyVaultSecret secret = secretClient.GetSecret(secretName);
    return secret.Value;
}

从系统证书存储读取证书的示例

如果证书已经存入运行环境的系统证书存储,可替换证书加载逻辑:

// 从当前用户的个人证书存储读取指定指纹的证书
X509Certificate2 GetCertificateFromStore(string certThumbprint)
{
    using X509Store store = new X509Store(StoreName.My, StoreLocation.CurrentUser);
    store.Open(OpenFlags.ReadOnly);
    var certCollection = store.Certificates.Find(
        X509FindType.FindByThumbprint, 
        certThumbprint, 
        validOnly: false
    );
    if (certCollection.Count == 0)
    {
        throw new Exception("未找到指定指纹的证书");
    }
    return certCollection[0];
}

注意事项

  • 运行代码的账号需要有证书私钥的读取权限,否则会出现证书加载或认证失败问题
  • 生产环境禁止硬编码PFX密码、证书指纹等敏感信息,可通过本地加密配置文件存储
  • 整个认证流程不需要任何AD账号登录操作,只要证书有效、对应注册应用有Key Vault的访问权限,即可正常读取机密

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.27 22:24:01