有没有更好的使用证书和获取Azure密钥库秘密的方法?

时间:2019-06-18 20:19:59

标签: c# azure azure-keyvault

我有以下代码,这些代码传递了证书指纹,以从Azure密钥库中检索机密。我想知道是否有更好的方法可以做到这一点而不必传递指纹来完全消除这种风险?下面是我的代码

        public static async Task<string> GetAccessToken(string authority, string resource, string scope)
        {
            var certificate = GetCertificateFromStore(ConfigurationManager.AppSettings["Thumbprint"]);
            var clientAssertionCertificate = new ClientAssertionCertificate(ConfigurationManager.AppSettings["ClientId"], certificate);
            var context = new AuthenticationContext(authority, TokenCache.DefaultShared);
            var result = await context.AcquireTokenAsync(resource, clientAssertionCertificate);

            return result.AccessToken;
        }

        public static X509Certificate2 GetCertificateFromStore(string thumbprint)
        {
            X509Certificate2 certificate;
            // Get the certificate store for the current user.
            thumbprint = Regex.Replace(thumbprint, @"[^\da-fA-F]", string.Empty).ToUpper();
            X509Store store = new X509Store(StoreName.My, StoreLocation.LocalMachine);
            try
            {
                store.Open(OpenFlags.ReadOnly);
                X509Certificate2Collection certCollection = store
                    .Certificates
                    .Find(X509FindType.FindByThumbprint, thumbprint, false);

                if (certCollection == null || certCollection.Count == 0)
                {
                    throw new Exception("Certificate not installed in the store");
                }
                return certificate = certCollection[0];
            }
            finally
            {
                store.Close();
            }
        } 

0 个答案:

没有答案