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

2024-04-21

我有一个 asp.net core web api (app1) 应用程序,它正在调用另一个 asp.net core web 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 https://github.com/Azure-Samples/active-directory-dotnetcore-daemon-v2/tree/master/2-Call-OwnApi#variation-daemon-application-using-client-credentials-with-certificates

一切正常,直到我俩app1 and app2在本地计算机上运行,​​我正在读取如下所示的证书,

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 应用程序服务托管 app1 和 2,现在的问题是如何读取证书?

Thanks!


在 Azure 计算(例如应用程序服务)上部署时,不存在诸如local磁盘或证书存储本身可用。

所以,随着建议的更改 https://github.com/Azure-Samples/active-directory-aspnetcore-webapp-openidconnect-v2/tree/master/6-Deploy-to-Azure对于您的应用程序的配置,您还需要执行以下操作

  1. 将您的证书存储在KeyVault https://azure.microsoft.com/en-ca/services/key-vault/(或同等内容)并从您的代码中获取它
  2. 更好,考虑使用托管身份 https://github.com/Azure-Samples/app-service-msi-keyvault-dotnet/blob/master/README.md.
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

如果 Web 应用程序通过 Azure 应用程序服务托管,如何读取证书 的相关文章

随机推荐