仅通过设备安装的证书访问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
相关产品推荐
相关产品推荐

