簡體   English   中英

在Azure網站上安裝和使用證書

[英]Installing and using certificate on Azure website

我正在嘗試在我的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();
        }
    }

為了解決此問題,我必須授予我的站點訪問證書的權限。
這是通過轉到Azure門戶->設置->應用程序設置中的應用程序來實現的
我添加了以下應用程序設置:
密鑰:WEBSITE_LOAD_CERTIFICATES,值:My_Certificate_Thumbprint
(感謝您將我指向正確的方向,Crypt32)

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM