【问题标题】:Trying to access Azure Keyvault from .Net Framework project is hanging尝试从 .Net Framework 项目访问 Azure Keyvault 已挂起
【发布时间】:2021-03-12 17:35:57
【问题描述】:

我目前正在为我的工作开发一个 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;
        }
    }

【问题讨论】:

  • .NET Core 没有同步上下文,但 .NET Framework 有,这就是您在这里遇到死锁的原因。您不能将代码重构为异步吗?
  • 仔细观察,您在未标记为异步的方法中使用await。这不可能是你实际运行的代码,它不会编译。

标签: c# aes azure-keyvault


【解决方案1】:

不太确定你的根本原因,但如果你想通过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();
            }
        }
    }
    
}

结果:

【讨论】:

  • 您是否在 .NET Framework 项目中使用 Azure.Security.KeyVault.Keys 和 Azure.Identity?如果是,您是如何做到这一点的?
猜你喜欢
  • 2022-12-09
  • 2020-08-01
  • 1970-01-01
  • 2019-09-01
  • 1970-01-01
  • 2018-04-18
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多