共用方式為


如何:使用 ACS 管理服務來設定憑證和金鑰

更新日期:2015 年 6 月 19 日

適用對象:Azure

套用至

  • Microsoft Azure Active Directory 存取控制服務 (也稱為「存取控制服務」或 ACS)

概觀

您可以使用 ACS 管理入口網站或 ACS 管理服務來設定 ACS 憑證和金鑰。 如果您要建置自訂使用者介面來管理 ACS,或想要將多租使用者軟體即服務 (SaaS) 解決方案的新租使用者上線自動化,則使用 ACS 管理服務會更有效率。

如需使用 ACS 管理入口網站來設定憑證和金鑰的詳細資訊,請參閱 憑證和金鑰

使用 ACS 管理服務來設定憑證和金鑰的步驟

重要

執行下列步驟之前,請確定您的系統符合 ACS 必要條件中摘要的所有 .NET Framework 和平臺需求。

若要使用 ACS 管理服務設定憑證和金鑰,請完成下列步驟:

  • 步驟 1 – 收集 ACS 設定資訊

  • 步驟 2 – 建立範例主控台應用程式

  • 步驟 3 – 新增必要服務與組件的參考

  • 步驟 4 – 實作管理服務用戶端

  • 步驟 5 - 安裝憑證和金鑰

    • 新增存取控制命名空間的權杖簽署憑證

    • 新增信賴憑證者應用程式的權杖簽署憑證

    • 新增存取控制命名空間的權杖簽署對稱金鑰

    • 新增信賴憑證者應用程式的權杖簽署對稱金鑰

    • 新增權杖加密憑證

    • 新增權杖解密憑證

步驟 1 – 收集 ACS 設定資訊

您可以使用 ACS 管理入口網站來收集必要的組態資訊。 如需詳細資訊,請參閱 ACS 管理入口網站

收集 ACS 設定資訊

  1. 移至Microsoft Azure管理入口網站 (https://manage.WindowsAzure.com) 登入,然後按一下[Active Directory]。 (疑難排解提示: 「Active Directory」 專案遺失或無法使用)

  2. 若要管理存取控制命名空間,請選取該命名空間,然後按一下 [管理]。 (或按一下 [存取控制命名空間]、選取 [命名空間],然後按一下 [管理])。

  3. 依序按一下 [管理服務]、[ManagementClient] 和 [密碼]

  4. 複製 [密碼] 欄位中的值。

  5. 按一下 [管理服務]。 取得服務命名空間和 ACS 主機名稱的值。 如果您的管理服務 URL 為 http://contoso.accesscontrol.windows.net ,則命名空間為 contoso ,且主機名稱 為 accesscontrol.windows.net

步驟 2 – 建立範例主控台應用程式

在此步驟中,您會建立範例主控台應用程式,以執行程式碼來新增 ACS 規則群組和規則。

建立範例主控台應用程式

  1. 開啟 Visual Studio 2012,然後在安裝Windows範本下建立新的主控台應用程式專案。

  2. 將下列程式碼新增至 Program 類別中,然後將 serviceIdentityPasswordForManagement、serviceNamespace 與 acsHostName 等變數指派給您在前一個步驟中收集到的適當設定資訊。

    public const string serviceIdentityUsernameForManagement = "ManagementClient";
    public const string serviceIdentityPasswordForManagement = "My Password/Key for ManagementClient";
    public const string serviceNamespace = "MyNameSpaceNoDots";
    public const string acsHostName = "accesscontrol.windows.net";
    public const string acsManagementServicesRelativeUrl = "v2/mgmt/service/";
    static string cachedSwtToken;
    

步驟 3 – 新增必要服務與組件的參考

在此步驟中,您會識別必要的相依性,並將其新增至服務與組件。

將必要的相依性新增到服務與組件

  1. 以滑鼠右鍵按一下 [參考],再按一下 [新增參考],然後新增參考至 System.Web.Extensions。

    注意

    您可能必須在 [方案總管] 中以滑鼠右鍵按一下您的範例主控台應用程式名稱,選取 [內容],然後將範例應用程式的目標架構從 [.NET Framework 4 用戶端設定檔] (在您建立新的主控台應用程式時依預設指派的) 變更為 [.NET Framework 4]

  2. 以滑鼠右鍵按一下 [服務參考],按一下 [新增服務參考],然後將服務參考新增至管理服務。 管理服務的 URL 對您的命名空間而言是唯一的,而且外觀應與下列內容類似:

    HTTPs:// YOURNAMESPACE.accesscontrol.windows.net/v2/mgmt/service

  3. 新增下列宣告,其中 MyConsoleApplication 是您主控台應用程式的名稱,MyServiceReference 是您服務參考的名稱:

    using System;
    using System.IO;
    using System.Collections.Generic;
    using System.Linq;
    using System.Text;
    using System.Web;
    using System.Net;
    using System.Data.Services.Client;
    using System.Collections.Specialized;
    using System.Web.Script.Serialization;
    using System.Globalization;
    using System.Security.Cryptography;
    using System.Security.Cryptography.X509Certificates; 
    using MyConsoleApplication.MyServiceReference;
    

步驟 4 – 實作管理服務用戶端

在此步驟中,您會實作管理服務用戶端。

實作管理服務用戶端

  1. 將下列方法加入至 Program 類別:

       public static ManagementService CreateManagementServiceClient()
            {
                string managementServiceEndpoint = String.Format(CultureInfo.InvariantCulture, "https://{0}.{1}/{2}",
                    serviceNamespace,
                    acsHostName,
                    acsManagementServicesRelativeUrl);
                ManagementService managementService = new ManagementService(new Uri(managementServiceEndpoint));
    
                managementService.SendingRequest += GetTokenWithWritePermission;
    
                return managementService;
            }
    
  2. GetTokenWithWritePermission 方法及其協助程式方法新增至 Program 類別。 GetTokenWithWritePermission 及其協助程式會將 SWT OAuth 權杖新增至 HTTP 要求的授權標頭。

    public static void GetTokenWithWritePermission(object sender, SendingRequestEventArgs args)
            {
                GetTokenWithWritePermission((HttpWebRequest)args.Request);
            }
    
            public static void GetTokenWithWritePermission(HttpWebRequest args)
            {
                if (cachedSwtToken == null)
                {
                    cachedSwtToken = GetTokenFromACS();
                }
    
                args.Headers.Add(HttpRequestHeader.Authorization, "Bearer " + cachedSwtToken);
            }
    
            private static string GetTokenFromACS()
            {
                //
                // Request a token from ACS
                //
                WebClient client = new WebClient();
                client.BaseAddress = string.Format(CultureInfo.CurrentCulture, 
                                                   "https://{0}.{1}", 
                                                   serviceNamespace, 
                                                   acsHostName);
    
                NameValueCollection values = new NameValueCollection();
                values.Add("grant_type", "client_credentials");
                values.Add("client_id", serviceIdentityUsernameForManagement);
                values.Add("client_secret", serviceIdentityPasswordForManagement);
                values.Add("scope", client.BaseAddress + acsManagementServicesRelativeUrl);
    
                byte[] responseBytes = client.UploadValues("/v2/OAuth2-13", "POST", values);
    
                string response = Encoding.UTF8.GetString(responseBytes);
    
                // Parse the JSON response and return the access token 
                JavaScriptSerializer serializer = new JavaScriptSerializer();
    
                Dictionary<string, object> decodedDictionary = serializer.DeserializeObject(response) as Dictionary<string, object>;
    
                return decodedDictionary["access_token"] as string;
    
            }
    

步驟 5 – 新增憑證和金鑰

為您的存取控制命名空間新增權杖簽署憑證

在此範例中,您會為存取控制命名空間建立 X.509 簽署憑證。

為存取控制命名空間中的所有信賴憑證者應用程式新增權杖簽署憑證

  1. 將下列程式碼新增至 Program 類別中的 Main 方法,以初始化管理服務用戶端。

    ManagementService svc = CreateManagementServiceClient();
    
  2. 將下列程式碼新增至Program類別,以建立ReadBytesFromPfxFile協助程式函式,以從 X.509 憑證讀取位元組:

    //Helper function to read bytes from your .pfx file
    
            public static byte[] ReadBytesFromPfxFile(string pfxFileName, string protectionPassword)
            {
                byte[] signingCertificate;
                using (FileStream stream = File.OpenRead(pfxFileName))
                {
                    using (BinaryReader br = new BinaryReader(stream))
                    {
                        signingCertificate = br.ReadBytes((int)stream.Length);
                    }
                }
                return signingCertificate;
            }
    
  3. 若要新增權杖簽署 X.509 憑證,請將下列程式碼新增至 Program 類別中的 Main 方法:

    注意

    使用 X.509 憑證的有效完整路徑來取代 "Full path to your .PFX file"。 例如,"C:\ACS2ClientCertificate.pfx"。

    使用 X.509 憑證的密碼來取代 “MyCertificatePassword”。

    X509Certificate2 cert = new X509Certificate2(@"Full path to your .PFX file", “MyCertificatePassword”);
    
                DateTime startDate, endDate;
                startDate = cert.NotBefore.ToUniversalTime();
                endDate = cert.NotAfter.ToUniversalTime();
               string pfxFileName = @"Full path to your .PFX file";
                string pfxPassword = @"MyCertificatePassword";
    
    byte[] signingCertificate = ReadBytesFromPfxFile(pfxFileName, pfxPassword);
    
    ServiceKey serviceKey = new ServiceKey()
                {
                    Type = "X509Certificate",
                    Usage = "Signing",
                    Value = signingCertificate,
                      Password = Encoding.UTF8.GetBytes("MyCertificatePassword"),
                      IsPrimary = false,
                    StartDate = startDate.ToUniversalTime(),
                    EndDate = endDate.ToUniversalTime()
                };
                svc.AddToServiceKeys(serviceKey);
                svc.SaveChanges(SaveChangesOptions.Batch);
    

新增信賴憑證者應用程式的權杖簽署憑證

在此範例中,您會建立指派給特定信賴憑證者應用程式的 X.509 簽署憑證。

如何新增信賴憑證者應用程式的權杖簽署憑證

  1. 將下列程式碼新增至 Program 類別中的 Main 方法,以初始化管理服務用戶端。

    ManagementService svc = CreateManagementServiceClient();
    
  2. 透過將下列程式碼新增至 Program 類別,您可以建立 ReadBytesFromPfxFile 協助程式功能,從 X.509 憑證中讀取位元組:

    //Helper function to read bytes from your .pfx file
    
            public static byte[] ReadBytesFromPfxFile(string pfxFileName, string protectionPassword)
            {
                byte[] signingCertificate;
                using (FileStream stream = File.OpenRead(pfxFileName))
                {
                    using (BinaryReader br = new BinaryReader(stream))
                    {
                        signingCertificate = br.ReadBytes((int)stream.Length);
                    }
                }
                return signingCertificate;
            }
    
  3. 若要新增權杖簽署 X.509 憑證,請將下列程式碼新增至 Program 類別中的 Main 方法:

    注意

    使用 X.509 憑證的完整路徑來取代 "Full path to your .PFX file"。 例如,"C:\ACS2ClientCertificate.pfx"。

    使用 X.509 憑證的密碼來取代 “MyCertificatePassword”。

    使用信賴憑證者應用程式的名稱來取代 “MyRelyingPartyApplication”。

    //Select an existing Relying Party Application by its name
    
                RelyingParty relyingParty = svc.RelyingParties.Where(m => m.Name == "MyRelyingPartyApplication").Single();
    
               // Add a signing certificate
    
               X509Certificate2 cert = new X509Certificate2(@"Full path to your .PFX file", "MyCertificatePassword");
               DateTime startDate, endDate;
               startDate = cert.NotBefore.ToUniversalTime();
               endDate = cert.NotAfter.ToUniversalTime();
    
               string pfxFileName = @"Full path to your .PFX file";
               string pfxPassword = "MyCertificatePassword";
    
                byte[] signingCertificate = ReadBytesFromPfxFile(pfxFileName, pfxPassword);
    
               RelyingPartyKey relyingPartyKey = new RelyingPartyKey()
                {
                    StartDate = startDate.ToUniversalTime(),
                   EndDate = endDate.ToUniversalTime(),
                    Type = "X509Certificate",
                    Usage = "Signing",
                    IsPrimary = true,
                    Value = signingCertificate,
                   Password = Encoding.UTF8.GetBytes("MyCertificatePassword")
                };
    
    // Add the new signing certificate to the selected Relying Party Application
    
                svc.AddRelatedObject(relyingParty, "RelyingPartyKeys", relyingPartyKey);
    
    
    
                //Save your relying party application
    
                svc.SaveChanges(SaveChangesOptions.Batch);
    

為您的存取控制命名空間新增權杖簽署對稱金鑰

在此範例中,您會將此簽署對稱金鑰指派給存取控制命名空間。

為存取控制命名空間新增權杖簽署對稱金鑰

  1. 將下列程式碼新增至 Program 類別中的 Main 方法,以初始化管理服務用戶端。

    ManagementService svc = CreateManagementServiceClient();
    
  2. 若要新增權杖簽署對稱金鑰,請將下列程式碼新增至 Program 類別中的 Main 方法:

           string symKey = "SampleTokenSigningSymmetricKey";
                DateTime startDate, endDate;
                startDate = DateTime.UtcNow;
                endDate = DateTime.MaxValue;
    
                ServiceKey serviceKey = new ServiceKey()
                {
                    
                    Type = "Symmetric",
                    Usage = "Signing",
                    Value = Encoding.UTF8.GetBytes(symKey),
                    StartDate = startDate.ToUniversalTime(),
                    EndDate = endDate.ToUniversalTime()
                };
                svc.AddToServiceKeys(serviceKey);
                svc.SaveChanges(SaveChangesOptions.Batch);
    

新增信賴憑證者應用程式的權杖簽署對稱金鑰

在此範例中,您會對特定信賴憑證者應用程式指派新的簽署對稱金鑰。

新增信賴憑證者應用程式的權杖簽署對稱金鑰

  1. 將下列程式碼新增至 Program 類別中的 Main 方法,以初始化管理服務用戶端。

    ManagementService svc = CreateManagementServiceClient();
    
  2. 若要新增權杖簽署對稱金鑰,請將下列程式碼新增至 Program 類別中的 Main 方法:

          //Select a relying party application
    
                RelyingParty relyingParty = svc.RelyingParties.Where(m => m.Name == "MyRelyingPartyApplication").Single();
    
               // Create a symmetric key
    
                string symKey = "SampleTokenSigningSymmetricKey";
                DateTime startDate, endDate;
                startDate = DateTime.UtcNow;
                endDate = DateTime.MaxValue;
    
                RelyingPartyKey relyingPartyKey = new RelyingPartyKey()
                {
    
                    Type = "Symmetric",
                    Usage = "Signing",
                    Value = Encoding.UTF8.GetBytes(symKey),
                    StartDate = startDate.ToUniversalTime(),
                    EndDate = endDate.ToUniversalTime()
                };
    
                //Assign this symmetric key to the selected relying party application 
    
                svc.AddRelatedObject(relyingParty, "RelyingPartyKeys", relyingPartyKey);
    
                   //Save your symmetric key
    
                svc.SaveChanges(SaveChangesOptions.Batch);        
    

新增權杖加密憑證

在此範例中,您會新增特定信賴憑證者應用程式的 X.509 權杖加密憑證。

新增信賴憑證者應用程式的權杖加密憑證

  1. 將下列程式碼新增至 Program 類別中的 Main 方法,以初始化管理服務用戶端。

    ManagementService svc = CreateManagementServiceClient();
    
  2. 若要新增權杖加密 X.509 憑證,請將下列程式碼新增至 Program 類別中的 Main 方法:

    注意

    使用 X.509 憑證的完整路徑來取代 "Full path to your .CER file"。 例如,"C:\ ACS2ClientCertificate.cer"。

    使用 X.509 憑證的密碼來取代 “MyCertificatePassword”。

    使用信賴憑證者應用程式的名稱來取代 “MyRelyingPartyApplication”。

    //Select a relying party application
    
                RelyingParty relyingParty = svc.RelyingParties.Where(m => m.Name == "MyRelyingPartyApplication").Single();
    
               // Add an encryption certificate
    
                X509Certificate2 cert = new X509Certificate2(@"Full path to your .CER file");
                DateTime startDate, endDate; 
                  startDate = cert.NotBefore;
                  endDate = cert.NotAfter;
    
                RelyingPartyKey relyingPartyKey = new RelyingPartyKey()
                {
                    Type = "X509Certificate",
                    Usage = "Encrypting",
                    Value = cert.GetRawCertData(),
                    StartDate = startDate.ToUniversalTime(),
                    EndDate = endDate.ToUniversalTime()
                };
    
                //Assign this encryption certificate to the selected relying party application 
    
                svc.AddRelatedObject(relyingParty, "RelyingPartyKeys", relyingPartyKey);
    
                   //Save your encryption certificate
    
                svc.SaveChanges(SaveChangesOptions.Batch);     
    

新增權杖解密憑證

在此範例中,您會新增指派給存取控制命名空間的 X.509 權杖解密憑證。

為存取控制命名空間中的所有信賴憑證者應用程式新增權杖簽署憑證

  1. 將下列程式碼新增至 Program 類別中的 Main 方法,以初始化管理服務用戶端。

    ManagementService svc = CreateManagementServiceClient();
    
  2. 透過將下列程式碼新增至 Program 類別,您可以建立 ReadBytesFromPfxFile 協助程式功能,從 X.509 憑證中讀取位元組:

    //Helper function to read bytes from your .pfx file
    
            public static byte[] ReadBytesFromPfxFile(string pfxFileName, string protectionPassword)
            {
                byte[] decryptionCertificate;
                using (FileStream stream = File.OpenRead(pfxFileName))
                {
                    using (BinaryReader br = new BinaryReader(stream))
                    {
                        decryptionCertificate = br.ReadBytes((int)stream.Length);
                    }
                }
                return decryptingCertificate;
            }
    
  3. 若要新增權杖簽署 X.509 憑證,請將下列程式碼新增至 Program 類別中的 Main 方法:

    注意

    使用您的 X.509 憑證的有效完整路徑,取代以下程式碼中的 "Full path to your .PFX file"。 例如,如果名為 ACS2ClientCertificate.pfx 的憑證儲存在 C:下,則正確的值為 「C:\ACS2ClientCertificate.pfx」。

    使用您的 X.509 憑證的正確密碼,取代以下程式碼中的 “MyCertificatePassword”。

    X509Certificate2 cert = new X509Certificate2(@"Full path to your .PFX file", “MyCertificatePassword”);
    
                DateTime startDate, endDate;
                startDate = cert.NotBefore.ToUniversalTime();
                endDate = cert.NotAfter.ToUniversalTime();
               string pfxFileName = @"Full path to your .PFX file";
                string pfxPassword = @"MyCertificatePassword";
    
    byte[] decryptionCertificate = ReadBytesFromPfxFile(pfxFileName, pfxPassword);
    
    ServiceKey serviceKey = new ServiceKey()
                {
                    Type = "X509Certificate",
                    Usage = "Encrypting",
                    Value = decryptionCertificate,
                      Password = Encoding.UTF8.GetBytes("MyCertificatePassword"),
                    StartDate = startDate.ToUniversalTime(),
                    EndDate = endDate.ToUniversalTime()
                };
                svc.AddToServiceKeys(serviceKey);
                svc.SaveChanges(SaveChangesOptions.Batch);
    

另請參閱

概念

ACS 的作法