共用方式為


做法:使用 ACS 管理服務來設定服務身分識別

更新日期:2015 年 6 月 19 日

適用對象:Azure

套用至

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

概觀

您可以使用 ACS 管理入口網站 (來設定 ACS 服務識別,如需詳細資訊,請參閱 服務 識別) 或 ACS 管理服務。 如果您要建置用於管理 ACS 的自訂使用者介面,或想要將多租使用者軟體即服務的新租使用者上線自動化,則使用 ACS 管理服務可以更有效率 (SaaS) 解決方案。

使用 ACS 管理服務設定服務身分識別的步驟

重要

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

若要使用 ACS 管理服務來設定服務識別,請完成下列步驟:

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

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

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

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

  • 步驟 5 – 新增服務身分識別

步驟 1 – 收集 ACS 設定資訊

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

收集 ACS 設定資訊

  1. 啟動 ACS 管理入口網站。 如需如何啟動 ACS 管理入口網站的詳細資訊,請參閱 ACS 管理入口網站

  2. 取得 ACS 管理服務帳戶的值。 您可以使用預設的ManagementClient 帳戶。 若要檢視此值,請在 ACS 管理入口網站中,按一下頁面左側樹狀結構中 [系統管理] 區段下的 [管理服務]。

  3. 取得 ACS 管理服務帳戶密碼的值。 若要檢視此值,請執行下列動作:

    1. 在 ACS 管理入口網站中,按一下頁面左側樹狀目錄中 [管理] 區段下的 [管理服務]。

    2. 在 [管理服務] 頁面上,按一下 [管理服務帳戶] 下方的 ManagementClient

    3. 在 [編輯管理服務帳戶] 頁面的 [認證] 下方,按一下 [密碼]

    4. 在 [編輯管理認證] 頁面上,複製 [密碼] 欄位中的值。

  4. 取得 Azure 命名空間的值。 您可以從Azure 入口網站或 ACS 管理入口網站的 URL 取得此值。 例如,在 中 http://contoso.accesscontrol.windows.net ,Azure 命名空間的值是 contoso

  5. 取得 ACS 主機名稱的值。 此值通常為accesscontrol.windows.net

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

在此步驟中,您會建立範例主控台應用程式,以執行程式碼來新增 ACS 服務身分識別。

建立範例主控台應用程式

  1. 開啟 Visual Studio 2012,並建立新的主控台應用程式專案。

  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.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. 將下列程式碼新增至 Program 類別,以建立 GetTokenWithWritePermission 方法及其協助程式方法。 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 – 新增服務身分識別

在此步驟中,您會使用在上個步驟中建立的管理服務用戶端來新增服務身分識別。 ACS 服務身分識別可以使用密碼、對稱金鑰或 X.509 憑證作為認證類型。

新增服務身分識別

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

    ManagementService svc = CreateManagementServiceClient();
    
  2. 執行下列其中一個動作:

    • 若要新增與密碼相關聯的服務身分識別並儲存變更,請將下列程式碼新增至 Program 類別中的 Main 方法:

      注意

      您可以將此服務身分識別稱為 “SampleServiceIdentity” 並將其密碼設為 “SampleServiceIdentityPassword”,如以下程式碼所示。

                  string name = "SampleServiceIdentity";
                  string password = "SampleServiceIdentityPassword";
                  ServiceIdentity sid = new ServiceIdentity()
                  {
                      Name = name
                  };
      
                  DateTime startDate, endDate;
                  startDate = DateTime.UtcNow;
                  endDate = DateTime.MaxValue;
      
                  ServiceIdentityKey key = new ServiceIdentityKey()
                  {
                      EndDate = endDate.ToUniversalTime(),
                      StartDate = startDate.ToUniversalTime(),
                      Type = "Password",
                      Usage = "Password",
                      Value = Encoding.UTF8.GetBytes(password),
                      DisplayName = String.Format(CultureInfo.InvariantCulture, "{0} key for {1}", "Password", name)
                  };
      
                  svc.AddToServiceIdentities(sid);
                  svc.AddRelatedObject(
                      sid,
                      "ServiceIdentityKeys",
                      key);
      
      
                  svc.SaveChanges(SaveChangesOptions.Batch);
      
    • 若要新增與對稱金鑰相關聯的服務身分識別並儲存變更,請將下列程式碼新增至 Program 類別中的 Main 方法:

      注意

      您可以將此服務身分識別稱為 “SampleServiceIdentity” 並將其對稱金鑰值設為 “SampleServiceIdentityPassword”,如以下程式碼所示。

                  string name = "SampleServiceIdentity";
                  string symKey = "SampleServiceIdentitySymmetricKey";
                  ServiceIdentity sid = new ServiceIdentity()
                  {
                      Name = name
                  };
      
                  DateTime startDate, endDate;
                  startDate = DateTime.UtcNow;
                  endDate = DateTime.MaxValue;
      
                  ServiceIdentityKey key = new ServiceIdentityKey()
                  {
                      EndDate = endDate.ToUniversalTime(),
                      StartDate = startDate.ToUniversalTime(),
                      Type = "Symmetric",
                      Usage = "Signing",
                      Value = Convert.FromBase64String(symKey),
                      DisplayName = String.Format(CultureInfo.InvariantCulture, "{0} key for {1}", "Sym Key", name)
                  };
      
                  svc.AddToServiceIdentities(sid);
                  svc.AddRelatedObject(
                      sid,
                      "ServiceIdentityKeys",
                      key);
      
      
                  svc.SaveChanges(SaveChangesOptions.Batch);
      
    • 若要新增與 X.509 憑證相關聯的服務身分識別並儲存變更,請將下列程式碼新增至 Program 類別中的 Main 方法:

      注意

      您可以將此服務身分識別稱為 “SampleServiceIdentity”,如以下程式碼所示

      在下列程式碼中,使用您的 X.509 憑證的完整路徑取代 "Full path to your .CER file"。 例如,若名為 ACS2ClientCertificate.cer 的憑證儲存在 C:\ 中,則正確的值為 "C:\ ACS2ClientCertificate.cer"。

                  string name = "SampleServiceIdentity";
                  X509Certificate2 cert = new X509Certificate2(@"Full path to your .CER file");
      
                  ServiceIdentity sid = new ServiceIdentity()
                  {
                      Name = name
                  };
      
                  DateTime startDate, endDate;
      
                  startDate = cert.NotBefore.ToUniversalTime();
                  endDate = cert.NotAfter.ToUniversalTime();
      
                  ServiceIdentityKey key = new ServiceIdentityKey()
                  {
                      EndDate = endDate.ToUniversalTime(),
                      StartDate = startDate.ToUniversalTime(),
                      Type = "X509Certificate",
                      Usage = "Signing",
                      Value = cert.GetRawCertData(),
                      DisplayName = String.Format(CultureInfo.InvariantCulture, "{0} key for {1}", "Cert", name)
                  };
      
                  svc.AddToServiceIdentities(sid);
                  svc.AddRelatedObject(
                      sid,
                      "ServiceIdentityKeys",
                      key);
      
      
                  svc.SaveChanges(SaveChangesOptions.Batch);
      

另請參閱

概念

ACS 的作法