我試圖在Azure網站中安裝自簽名證書,然後使用它訪問Azure密鑰保管庫。
當我在本地運行代碼並從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.點擊「上傳」
這是我使用的是閱讀和使用證書代碼:在Azure網站上安裝和使用證書
// 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應用下unpriveleged帳戶運行在Azure和只有在'CurrentUser'店完全控制你只有只讀的'LocalMachine'存儲權限。此外,您無法訪問存儲在「LocalMachine」商店中的密鑰。這意味着您必須將您的個人證書安裝到'CurrentUser'商店。 SSL轉到'LocalMachine'。 – Crypt32
通過應用程序設置授予訪問權後,它就可以工作。 謝謝! –