Azure Web Apps 讀取憑證

一般當我們在本機能正常運作的東西

常常放到雲端就不Work了

很多問題其實就在於雲端環境的差異與限制

例如這次研究的問題->讀取憑證資訊

以下就介紹Azure Web Apps環境下

憑證如何放置與讀取的差異

一般我們系統要讀取的憑證會放在

StoreLocation.LocalMachine

Azure Web Apps上傳後的憑證是放在

StoreLocation.CurrentUser

要讓程式能讀取到要讀取的憑證還要設定憑證的設定檔

否則就算你上傳憑證之後還是找不到

APP Setting中新增憑證讀取參數

WEBSITE_LOAD_CERTIFICATES 和憑證指紋(thumbprint)

或者也可以設定"*"(不需要引號)就會讀取全部憑證

這樣就能順利讀取

以下是憑證讀取範例

using System;
using System.Security.Cryptography.X509Certificates;namespace UseCertificateInAzureWebsiteApp
{
  class Program
  {
    static void Main(string[] args)
    {
      X509Store certStore = new X509Store(StoreName.My, StoreLocation.CurrentUser);
      certStore.Open(OpenFlags.ReadOnly);
      X509Certificate2Collection certCollection = certStore.Certificates.Find(
                                 X509FindType.FindByThumbprint,
                                 // 憑證指紋
                                 “E661583E8FABEF4C0BEF694CBC41C28FB81CD870”,
                                 false);
      // Get the first cert with the thumbprint
      if (certCollection.Count > 0)
      {
        X509Certificate2 cert = certCollection[0];
        // Use certificate
        Console.WriteLine(cert.FriendlyName);
      }
      certStore.Close();
    }
  }
}

 

留言

這個網誌中的熱門文章

IIS 啟用HTTP Strict Transport Security (HSTS)

解決WCF(REST)在https出現檔案找不到錯誤