azure - 使用 Azure.Security.KeyVault.Secrets 从 Azure KeyVault 获取证书

标签 azure azure-keyvault

我使用下面的代码从 Azure Key Vault 获取证书

 private X509Certificate2 GetClientCertificate(string thumbprint)
        {
            var _keyVaultName = _configuration["CPC:KeyVaultUrl"];
            var connectionString = _configuration["CPC:KeyVaultCN"];
            var azureServiceTokenProvider = new AzureServiceTokenProvider(connectionString);
            var _client = new KeyVaultClient(new KeyVaultClient.AuthenticationCallback(azureServiceTokenProvider.KeyVaultTokenCallback));
            var secretName = _configuration["CPC:ECCCertName"];
            var secret = _client.GetSecretAsync(_keyVaultName, secretName).Result;
            var privateKeyBytes = Convert.FromBase64String(secret.Value);
            var certificate = new X509Certificate2(privateKeyBytes, string.Empty, X509KeyStorageFlags.MachineKeySet | X509KeyStorageFlags.PersistKeySet | X509KeyStorageFlags.Exportable);
            return certificate;
        }

它使用 Microsoft.Azure.KeyVault 库,该库已弃用并由 Azure.Security.KeyVault 取代。

如何翻译此代码以使其与新库一起使用。 (使用带有 appkey 的连接字符串而不是密码)

非常感谢

最佳答案

这是我用来从 Azure Key Vault 获取带有私钥的证书的代码,希望它可以帮助您解决问题:

/// <summary>
/// Load a certificate (with private key) from Azure Key Vault
///
/// Getting a certificate with private key is a bit of a pain, but the code below solves it.
/// 
/// Get the private key for Key Vault certificate
/// https://github.com/heaths/azsdk-sample-getcert
/// 
/// See also these GitHub issues: 
/// https://github.com/Azure/azure-sdk-for-net/issues/12742
/// https://github.com/Azure/azure-sdk-for-net/issues/12083
/// </summary>
/// <param name="config"></param>
/// <param name="certificateName"></param>
/// <returns></returns>
public static X509Certificate2 LoadCertificate(IConfiguration config, string certificateName)
{
    string vaultUrl = config["Vault:Url"] ?? "";
    string clientId = config["Vault:ClientId"] ?? "";
    string tenantId = config["Vault:TenantId"] ?? "";
    string secret = config["Vault:Secret"] ?? "";

    Console.WriteLine($"Loading certificate '{certificateName}' from Azure Key Vault");

    var credentials = new ClientSecretCredential(tenantId: tenantId, clientId: clientId, clientSecret: secret);
    var certClient = new CertificateClient(new Uri(vaultUrl), credentials);
    var secretClient = new SecretClient(new Uri(vaultUrl), credentials);

    var cert = GetCertificateAsync(certClient, secretClient, certificateName);

    Console.WriteLine("Certificate loaded");
    return cert;
}


/// <summary>
/// Helper method to get a certificate
/// 
/// Source https://github.com/heaths/azsdk-sample-getcert/blob/master/Program.cs
/// </summary>
/// <param name="certificateClient"></param>
/// <param name="secretClient"></param>
/// <param name="certificateName"></param>
/// <returns></returns>
private static X509Certificate2 GetCertificateAsync(CertificateClient certificateClient,
                                                        SecretClient secretClient,
                                                        string certificateName)
{

    KeyVaultCertificateWithPolicy certificate = certificateClient.GetCertificate(certificateName);

    // Return a certificate with only the public key if the private key is not exportable.
    if (certificate.Policy?.Exportable != true)
    {
        return new X509Certificate2(certificate.Cer);
    }

    // Parse the secret ID and version to retrieve the private key.
    string[] segments = certificate.SecretId.AbsolutePath.Split('/', StringSplitOptions.RemoveEmptyEntries);
    if (segments.Length != 3)
    {
        throw new InvalidOperationException($"Number of segments is incorrect: {segments.Length}, URI: {certificate.SecretId}");
    }

    string secretName = segments[1];
    string secretVersion = segments[2];

    KeyVaultSecret secret = secretClient.GetSecret(secretName, secretVersion);

    // For PEM, you'll need to extract the base64-encoded message body.
    // .NET 5.0 preview introduces the System.Security.Cryptography.PemEncoding class to make this easier.
    if ("application/x-pkcs12".Equals(secret.Properties.ContentType, StringComparison.InvariantCultureIgnoreCase))
    {
        byte[] pfx = Convert.FromBase64String(secret.Value);
        return new X509Certificate2(pfx);
    }

    throw new NotSupportedException($"Only PKCS#12 is supported. Found Content-Type: {secret.Properties.ContentType}");
}

}

关于azure - 使用 Azure.Security.KeyVault.Secrets 从 Azure KeyVault 获取证书,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/65858283/

相关文章:

azure - 无法使用应用服务上的 Azure MSI 访问 Key Vault

.net - Azure Functions 在 bin 内创建另一个 bin 文件夹

java - 使用 REST API 将 block Blob 列表放在 Azure 存储上时,指定的 XML 在语法上无效错误

c# - 使用 C# 从存储在 azure blob 存储上的 200gb 文本文件中读取一行

Azure KeyVault 迭代保管库中的所有 secret

azure - 从 yaml 管道中的变量组参数化 azureSubscription

azure - 无法将 Azure Key Vault 与 Azure Kubernetes 服务集成

azure - 为什么我们需要在创建 Azure Key Vault 之前在 Azure Active Directory 中创建应用程序?

azure - 使用访问策略从多个不同的主体/用户获取对 Azure Key Vault 的访问权限

azure - 如何在部署作业期间设置 XML 转换的环境名称?