如果 Web 应用程序托管在 Azure 应用程序服务上,如何读取证书

how to read certificate if web app is hosted over azure app service

我有一个 asp.net 核心网络 api (app1) 应用程序正在调用另一个 asp.net 核心网络 api (app2) 我正在考虑将 app1 作为守护进程应用程序,我想使用证书而不是应用程序机密来跟踪客户端凭据。

https://github.com/Azure-Samples/active-directory-dotnetcore-daemon-v2/tree/master/2-Call-OwnApi#variation-daemon-application-using-client-credentials-with-certificates

一切正常,直到我的 app1app2 运行 在我正在读取证书的本地机器上,如下所示,

private static X509Certificate2 ReadCertificate(string certificateName)
    {
        if (string.IsNullOrWhiteSpace(certificateName))
        {
            throw new ArgumentException("certificateName should not be empty. Please set the CertificateName setting in the appsettings.json", "certificateName");
        }
        X509Certificate2 cert = null;

        using (X509Store store = new X509Store(StoreName.My, StoreLocation.CurrentUser))
        {
            store.Open(OpenFlags.ReadOnly);
            X509Certificate2Collection certCollection = store.Certificates;

            // Find unexpired certificates.
            X509Certificate2Collection currentCerts = certCollection.Find(X509FindType.FindByTimeValid, DateTime.Now, false);

            // From the collection of unexpired certificates, find the ones with the correct name.
            X509Certificate2Collection signingCert = currentCerts.Find(X509FindType.FindBySubjectDistinguishedName, certificateName, false);

            // Return the first certificate in the collection, has the right name and is current.
            cert = signingCert.OfType<X509Certificate2>().OrderByDescending(c => c.NotBefore).FirstOrDefault();
        }
        return cert;
    }

证书在本地机器上,我正在从这里读取,

 using (X509Store store = new X509Store(StoreName.My, StoreLocation.CurrentUser))

现在我想用 Azure 应用程序服务同时托管应用程序 1 和应用程序 2,现在的问题是如何读取证书?

谢谢!

在 Azure 计算(例如应用程序服务)上部署时,没有 local 磁盘或证书存储这样的东西可用。

因此,除了 the suggested changes 应用程序配置外,您还需要执行以下操作

  1. 将您的证书存储在 KeyVault(或等效文件)中并从您的代码中获取它
  2. 更好,考虑使用 Managed Identities