简体   繁体   English

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

[英]Getting certificate from Azure KeyVault with Azure.Security.KeyVault.Secrets

I am fetching a certificate from Azure Key Vault using the code below我正在使用以下代码从 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;
        }

It uses the Microsoft.Azure.KeyVault library which is deprecated to be replaced by Azure.Security.KeyVault.它使用 Microsoft.Azure.KeyVault 库,该库已弃用,由 Azure.Security.KeyVault 代替。

How can I translate this code to make it work with the new library.如何翻译此代码以使其与新库一起使用。 (using connection string with appkey instead of password) (使用带有 appkey 的连接字符串而不是密码)

Many thanks非常感谢

This is the code I use to get a Certificate with its private key from Azure Key Vault, hope it can help you with your problem:这是我用来从 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}");
}

} }

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 Azure.Security.KeyVault.Secrets 与 Microsoft.Azure.KeyVault - Azure.Security.KeyVault.Secrets vs Microsoft.Azure.KeyVault Azure.Security.KeyVault.Secrets 中的 Azure.RequestFailedException - Azure.RequestFailedException in Azure.Security.KeyVault.Secrets Azure.Security.KeyVault.Secrets:az 未被识别为内部或外部命令 - Azure.Security.KeyVault.Secrets: az is not recognized as an internal or external command 使用 Azure.Security.KeyVault.Secrets 的网络核心密钥库配置 - Net core Key vault configuration using Azure.Security.KeyVault.Secrets 从 python 中的 azure keyvault 检索机密列表 - Retrieving list of secrets from azure keyvault in python 如何从Azure Keyvault获取证书链 - How to get the certificate chain from azure keyvault 如何将从Azure KeyVault下载的机密作为参数传递给Azure函数? - How to pass secrets downloaded from Azure KeyVault as parameters to an Azure Function? 从 keyvault 向 Azure APIM 添加证书 - Adding certificate to Azure APIM from keyvault Azure:: Terraform 在 azure keyvault 机密上失败 - Azure :: Terraform fails on azure keyvault secrets 使用 Azure.Security.KeyVault 通过 SecretId / SecretIdentifier 而不是 Microsoft.Azure.KeyVault 检索证书(PFXcontent) - Using Azure.Security.KeyVault to retrieve certificate (PFXcontent) via SecretId / SecretIdentifier instead of Microsoft.Azure.KeyVault
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM