简体   繁体   中英

Trying to access Azure Keyvault from .Net Framework project is hanging

I'm currently working on a 256 bit AES encryption API project for my job. One of the aspects of these encryption APIs is they need to access our Azure Keyvault to retrieve a key (we have different keys for different projects).

For some reason the.Net Framework project hangs when trying to access the key vault after the first successful execution. It will hang on this line: var key = client.GetKeyAsync($"https://automationkeys.vault.azure.net/keys/{product}").GetAwaiter().GetResult();

I have the same encryption API made using.Net Core and I'm able to execute calls multiple times in a row without issue.

After doing some reading I have a feeling it has to do with async / await but I don't know enough about all that to see where the problem is.

Here is my full KeyVaultAccessor class:

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;
        }
    }

Not quite sure your root reason, but if you want to get a key in Azure keyVault by ClientCertificateCredential and local cert, try the code below which works perfectly for me:

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();
            }
        }
    }
    
}

Result: 在此处输入图像描述

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM