1. 程式人生 > 其它 >【Azure 應用服務】在App Service中呼叫外部服務API時需要攜帶客戶端證書,而多次呼叫的情況下會出現WindowsCryptographicException Keyset does not exist異常

【Azure 應用服務】在App Service中呼叫外部服務API時需要攜帶客戶端證書,而多次呼叫的情況下會出現WindowsCryptographicException Keyset does not exist異常

問題描述

在App Service中呼叫外部服務API時需要攜帶客戶端證書,而多次呼叫的情況下會出現WindowsCryptographicException Keyset does not exist異常。

錯誤Tarce:

Exception: 
Internal.Cryptography.CryptoThrowHelper+WindowsCryptographicException: Keyset does not exist
   at Internal.NativeCrypto.CapiHelper.CreateProvHandle(CspParameters parameters, Boolean randomKeyContainer)
   at System.Security.Cryptography.RSACryptoServiceProvider.get_SafeProvHandle()
   at System.Security.Cryptography.RSACryptoServiceProvider.get_SafeKeyHandle()
   at System.Security.Cryptography.RSACryptoServiceProvider..ctor(Int32 keySize, CspParameters parameters, Boolean useDefaultKeySize)
   at System.Security.Cryptography.RSACryptoServiceProvider..ctor(CspParameters parameters)
   at Internal.Cryptography.Pal.CertificatePal.<>c.<GetRSAPrivateKey>b__66_0(CspParameters csp)
   at Internal.Cryptography.Pal.CertificatePal.GetPrivateKey[T](Func`2 createCsp, Func`2 createCng)
   at Internal.Cryptography.Pal.CertificatePal.GetRSAPrivateKey()
   at Internal.Cryptography.Pal.CertificateExtensionsCommon.GetPrivateKey[T](X509Certificate2 certificate, Predicate`1 matchesConstraints)
   at xxxxxxxx.Paylink.WeChatPay.WeChatPayOptions.GetCertificateInfo()

 

問題分析

當在App Service中上傳證書後,可以通過Kudu站點來檢視證書是否存在。在Currentuser\My目錄下則使用以下PowerShell指令:

Get-ChildItem Cert:\currentuser\My\

 

通過PowerShell命令檢視證書是否存在,並沒有能解決App Service中的 “WindowsCryptographicException Keyset does not exist” 問題,只是說從側面證明當前例項中是否有證書。如果沒有,那麼錯誤非常明顯,就需要在例項中安裝證書。

 

但是如果證書還是存在,而錯誤情況依舊,通過多次驗證發現於啟用了App Service多例項有關。 雖然沒有證明為什麼在多例項的情況下出現證書獲取不到的情況,但是當使用App Service單例項後,問題不在發生。

個人猜想:是否時在程式碼中載入證書時候的程式碼在多例項的情況下,某一個例項出現沒有載入到證書的情況而導致。 

PS: 記錄App Service上出現的證書問題,以待未來再次遇見而參考。有新的發現在更新博文。

 

For more details, you could refer to the links below.

  1. X509Certificate Constructor Exception

  2. What exactly happens when I set LoadUserProfile of IIS pool

  3. Can I set application pool in webconfig