首页 > 解决方案 > 尝试从 .Net Framework 项目访问 Azure Keyvault 已挂起

问题描述

我目前正在为我的工作开发一个 256 位 AES 加密 API 项目。这些加密 API 的一个方面是它们需要访问我们的 Azure Keyvault 以检索密钥(我们对不同的项目有不同的密钥)。

由于某种原因,.Net Framework 项目在第一次成功执行尝试访问密钥保管库时挂起。它将挂在这条线上:var key = client.GetKeyAsync($"https://automationkeys.vault.azure.net/keys/{product}").GetAwaiter().GetResult();

我有使用 .Net Core 制作的相同加密 API,并且我能够连续多次执行调用而不会出现问题。

在做了一些阅读之后,我觉得它与async/await有关,但我对这一切的了解还不够,无法看出问题出在哪里。

这是我的完整KeyVaultAccessor类:

public static class KeyVaultAccessor
    {
        public static string GetKey(string product)
        {
            var keyValue = string.Empty;

            try
            {
                var client = GetKeyVaultClient(<my_app_id>, <keyvault_cert_thumbprint>);
                var key = client.GetKeyAsync($"https://automationkeys.vault.azure.net/keys/{product}").GetAwaiter().GetResult();

                keyValue = key?.KeyIdentifier.Version;

                if (string.IsNullOrEmpty(keyValue))
                {
                    Assert.Fail($"Key was null or empty for product: {product}");
                }
            }
            catch (Exception e)
            {
                Assert.Fail($"Error occurred while attempting to retrieve key for product: {product}. {e.Message}");
            }

            return keyValue;
        }

        private static KeyVaultClient GetKeyVaultClient(string appId, string thumbprint)
        {
            var keyVault = new KeyVaultClient(async (authority, resource, scope) =>
            {
                var authenticationContext = new AuthenticationContext(authority, null);
                X509Certificate2 certificate;
                var store = new X509Store(StoreName.My, StoreLocation.LocalMachine);

                try
                {
                    store.Open(OpenFlags.ReadOnly);
                    var certificateCollection = store.Certificates.Find(X509FindType.FindByThumbprint, thumbprint, false);
                    if (certificateCollection.Count == 0)
                    {
                        throw new Exception("<certificate name> not installed in the store");
                    }

                    certificate = certificateCollection[0];
                }
                finally
                {
                    store.Close();
                }

                var clientAssertionCertificate = new ClientAssertionCertificate(appId, certificate);
                var result = await authenticationContext.AcquireTokenAsync(resource, clientAssertionCertificate);
                return result.AccessToken;

            });

            return keyVault;
        }
    }

标签: c#aesazure-keyvault

解决方案


不太确定您的根本原因,但如果您想通过ClientCertificateCredential本地证书获取 Azure keyVault 中的密钥,请尝试以下代码,该代码对我来说非常有效:

using System;
using System.Security.Cryptography.X509Certificates;
using System.Threading.Tasks;
using Azure.Identity;
using Azure.Security.KeyVault.Keys;


namespace key_vault_console_app
{
    class Program
    {
        static void Main(string[] args)
        {
            var keyVaultName = "";
            var tenantID = "";
            var appID = "";
            var certThumbprint = "";

            var kvUri = $"https://{keyVaultName}.vault.azure.net";

            var certCred = new ClientCertificateCredential(tenantID, appID, GetLocalCert(certThumbprint));
            var client = new KeyClient(new Uri(kvUri), certCred);
            
            Console.Write(client.GetKey("<your key name>").Value.Key.Id);

        }
        public static X509Certificate2 GetLocalCert(string thumbprint)
        {
            var store = new X509Store(StoreName.My, StoreLocation.LocalMachine);
            try
            {
                store.Open(OpenFlags.ReadOnly);
                var certificateCollection = store.Certificates.Find(X509FindType.FindByThumbprint, thumbprint, false);
                if (certificateCollection.Count == 0)
                {
                    throw new Exception("cert not installed in the store");

                }

                return certificateCollection[0];
            }
            finally
            {
                store.Close();
            }
        }
    }
    
}

结果: 在此处输入图像描述


推荐阅读