az keyvault certificate download --vault-name [key-vault-name] --name mycert --file mycert.pem --encoding PEM
openssl x509 -in mycert.pem -inform PEM -noout -sha1 -fingerprint
mmc.exe
现在尝试根据 Az KeyVault 对我的 .Net 6 Api 进行身份验证,以使用证书获取秘密。
public static async Task<string> GetKeyValultSecrets(string key, IConfiguration configuration)
{
var keyVaultUrl = configuration["KeyVault:Vault"].ValidateArgNotNull("KeyVault:Vault");
var thumbprint = configuration["KeyVault:CertThumbprint"].ValidateArgNotNull("KeyVault:CertThumbprint");
var appClientId = configuration["KeyVault:AppClientId"].ValidateArgNotNull("KeyVault:AppClientId");
var tenantId = configuration["KeyVault:TenantId"].ValidateArgNotNull("KeyVault:TenantId");
X509Certificate2 certificate = null;
using (X509Store store = new X509Store(StoreName.My, StoreLocation.LocalMachine))
{
store.Open(OpenFlags.ReadOnly);
X509Certificate2Collection certs = store.Certificates.Find(X509FindType.FindByThumbprint, thumbprint, validOnly: false);
if (certs.Count > 0)
{
certificate = certs[0];
}
}
if (certificate == null)
{
throw new Exception($"Certificate with thumbprint {thumbprint} not found in the local certificate store.");
}
string clientId = appClientId;
var credential = new ClientCertificateCredential(tenantId, clientId, certificate);
var client = new SecretClient(new Uri(keyVaultUrl), credential);
var secret = client.GetSecret(key).Value; // <----- Error!!!
if (secret == null)
{
throw new Exception("Invalid Key Vault Key");
}
return secret.Value;
}
错误是:
System.AggregateException: 'One or more errors occurred. (ClientCertificateCredential authentication failed: The certificate certificate does not have a private key.
See the troubleshooting guide for more information. https://aka.ms/azsdk/net/identity/clientcertificatecredential/troubleshoot)'
2. MsalClientException: The certificate certificate does not have a private key.
但是我已经验证了
Key Usage
是Digital Signature, Key Encipherment (a0)
但是上面有一个感叹号:
要使用证书进行身份验证您需要(匹配的)私钥(通常是一个,有时是多个链/中间证书——我不确定 Azure 是否需要这)。私钥实际上与证书是分开的,但 MS(和 MSians)通常将其视为证书的一部分——特别是作为
X509Certificate2
的一个组成部分。正如 the documentation for your command says
下载 Key Vault 证书的公共部分。
“公共部分”是指没有私钥。
虽然似乎有一些获取密钥的选项,但我认为唯一适用于 Windows 的选项是下载 PFX/PKCS12 格式的 secret;这包括证书 和 私钥,并且 can 包含链证书,两者/全部都可以由 Windows 上的 MMC 导入(并由其他东西使用,如 PS Get-PfxCertificate、openssl、NSS、gpgsm , Java,不胜枚举)。看 带有私钥的 Azure Key Vault 下载证书 和 Azure Key Vault - 从 Ket Vault 下载原始 PFX .
PS:要在 LocalMachine 上运行 MMC/证书,您可以将步骤 1-6 替换为
certlm.msc
——或者只是 certlm
,因为 .msc
在 PATHEXT 中。