在 Azure 网站上安装和使用证书

Installing and using certificate on Azure website

我正在尝试在我的 Azure 网站上安装一个自签名证书,然后用它来访问 Azure Key Vault。
当我在本地 运行 代码并从 StoreLocation.CurrentUser & StoreName.My 读取证书时,一切都按预期工作。
尝试 运行在我部署的 Azure 站点中使用相同的代码,但失败了。
当我将读取更改为使用 StoreLocation.LocalMachine 时,证书在没有私钥的情况下加载,稍后会导致异常:
"System.NotSupportedException: The private key is not present in the X.509 certificate".
我需要以不同方式加载证书吗?或者我一开始没有在 Azure 中正确安装它?
这些是我采取的安装步骤:
1. 前往 https://ms.portal.azure.com
2. select 我的资源(我网站的应用服务)
3.点击"SSL Certificates"
4.点击"Upload Certificate"
5.点击浏览,select我的pfx文件并提供密码
6.点击"Upload"

这是我用来读取和使用证书的代码:

    // C-tor
    public SecretRetriever(string thumbprint, string clientId)
    {
        var clientAssertionCertPfx = FindCertificateByThumbprint(thumbprint);
        this.AssertionCert = new ClientAssertionCertificate(clientId, clientAssertionCertPfx);
    }

    /// <summary>
    /// Get the certificate associated with the given secretId
    /// </summary>
    /// <param name="secretId"></param>
    /// <returns></returns>
    public async Task<string> GetSecretAsync(string secretId)
    {
        var kv = new KeyVaultClient(new KeyVaultClient.AuthenticationCallback(GetAccessTokenAsync));
        return (await kv.GetSecretAsync(secretId)).Value;
    }

    private async Task<string> GetAccessTokenAsync(string authority, string resource, string scope)
    {
        var context = new AuthenticationContext(authority, TokenCache.DefaultShared);
        var result = await context.AcquireTokenAsync(resource, AssertionCert);
        return result.AccessToken;
    }

    //when changing to "CurrentUser" the private key is in the certificate. why it is not there when reading from LocalMachine?
    private static X509Certificate2 FindCertificateByThumbprint(string findValue)
    {
        X509Store store = new X509Store(StoreName.My, StoreLocation.LocalMachine);
        try
        {
            store.Open(OpenFlags.ReadOnly);
            X509Certificate2Collection col = store.Certificates.Find(X509FindType.FindByThumbprint, findValue, false);
            if (col.Count == 0)
            {
                return null;
            }
            return col[0];
        }
        finally
        {
            store.Close();
        }
    }

为了解决这个问题,我必须授予我的网站访问证书的权限。
这是通过转到 Azure 门户中的应用程序 --> 设置--> 应用程序设置
来实现的 我添加了以下应用设置:
键:WEBSITE_LOAD_CERTIFICATES,值:My_Certificate_Thumbprint
(感谢 Crypt32 为我指明了正确的方向)