【问题标题】:Installing and using certificate on Azure website在 Azure 网站上安装和使用证书
【发布时间】:2017-05-23 16:51:50
【问题描述】:

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

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

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

【问题讨论】:

  • 问题是您的 Web 应用程序在 Azure 上的非特权帐户下运行,并且只能完全控制 CurrentUser 存储,而您对 LocalMachine 存储只有只读权限。此外,您无权访问LocalMachine 存储中存储的密钥。这意味着您必须将您的个人证书安装到CurrentUser 商店。 SSL 转到LocalMachine
  • 通过应用程序设置授予访问权限后,它可以工作。谢谢!

标签: c# .net certificate x509certificate


【解决方案1】:

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

【讨论】:

    猜你喜欢
    • 2018-12-23
    • 1970-01-01
    • 2016-01-13
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-07-12
    • 1970-01-01
    • 2018-01-21
    相关资源
    最近更新 更多