方法: ACS 管理サービスを使用して証明書とキーを構成する

更新日: 2015 年 6 月 19 日

適用先:Azure

適用対象

  • Microsoft Azure Active Directory アクセス制御 (アクセス制御サービスまたは ACS)

概要

ACS 証明書とキーは、ACS 管理ポータルまたは ACS 管理サービスを使用して構成できます。 ACS 管理サービスの操作は、ACS を管理するためのカスタム ユーザー インターフェイスを構築する場合や、マルチテナント のサービスとしてのソフトウェア (SaaS) ソリューションの新しいテナントのオンボードを自動化する場合に、より効率的になります。

ACS 管理ポータルを使用して証明書とキーを構成する方法の詳細については、「 証明書とキー」を参照してください。

ACS 管理サービスを使用して証明書とキーを構成する手順

重要

次の手順を実行する前に、 システムが ACS の前提条件に要約されているすべての .NET フレームワークとプラットフォームの要件を満たしていることを確認します。

ACS 管理サービスを使用して証明書とキーを構成するには、次の手順を実行します。

  • 手順 1 – ACS 構成情報を収集する

  • 手順 2 – サンプル コンソール アプリケーションを作成する

  • 手順 3 – 必要なサービスとアセンブリへの参照を追加する

  • 手順 4 – 管理サービス クライアントを実装する

  • 手順 5 - 証明書とキーをインストールする

    • Access Control 名前空間のトークン署名証明書を追加する

    • 証明書利用者アプリケーションのトークン署名証明書を追加する

    • Access Control 名前空間のトークン署名対称キーを追加する

    • 証明書利用者アプリケーションのトークン署名対称キーを追加する

    • トークン暗号化証明書を追加する

    • トークン復号化証明書を追加する

手順 1 – ACS 構成情報を収集する

ACS 管理ポータルを使用して、必要な構成情報を収集できます。 詳細については、 ACS 管理ポータルを参照してください。

ACS 構成情報を収集するには

  1. Microsoft Azure管理ポータル (https://manage.WindowsAzure.com) に移動し、サインインし、[Active Directory] をクリックします。 (トラブルシューティングのヒント: "Active Directory" 項目が見つからないか、使用できません)

  2. アクセス制御名前空間を管理するには、名前空間をクリックしてしてから [管理] をクリックします。 または、[アクセス制御名前空間] をクリックして名前空間を選択し、[管理] をクリックします。

  3. [管理サービス] をクリックし、[ManagementClient] をクリックして、[パスワード] をクリックします。

  4. [パスワード] フィールドの値をコピーします。

  5. [管理サービス] をクリックします。 サービス名前空間と ACS ホスト名の値を取得します。 Management Service 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 Client Profile (新しいコンソール アプリケーションの作成時に既定で割り当てられる) から .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 とそのヘルパーにより、HTTP 要求の承認ヘッダーに SWT OAuth トークンが追加されます。

    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 – 証明書とキーを追加する

Access Control名前空間のトークン署名証明書を追加する

この例では、Access Control名前空間の X.509 署名証明書を作成します。

Access Control名前空間内のすべての証明書利用者アプリケーションのトークン署名証明書を追加するには

  1. 次のコードを Program クラスの Main メソッドに追加して、管理サービス クライアントを初期化します。

    ManagementService svc = CreateManagementServiceClient();
    
  2. 次のコードを Program クラスに追加して、X.509 証明書からバイトを読み取る ReadBytesFromPfxFile ヘルパー関数を作成します。

    //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] メソッドに追加します。

    注意

    "Full path to your .PFX file" を X.509 証明書への有効な完全パスに置き換えます。 たとえば、"C:\ ACS2ClientCertificate.pfx" のようになります。

    "MyCertificatePassword"を X.509 証明書のパスワードに置き換えます。

    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. ヘルパー関数 ReadBytesFromPfxFile を作成して、次のコードを [Program] クラスに追加することで 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] メソッドに追加します。

    注意

    "Full path to your .PFX file" を X.509 証明書への完全パスに置き換えます。 たとえば、"C:\ ACS2ClientCertificate.pfx" のようになります。

    "MyCertificatePassword"を X.509 証明書のパスワードに置き換えます。

    "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);
    

Access Control名前空間のトークン署名対称キーを追加する

この例では、この署名対称キーを Access Control 名前空間に割り当てます。

Access Control名前空間のトークン署名対称キーを追加するには

  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 メソッドに以下のコードを追加します。

    注意

    "Full path to your .CER file" を X.509 証明書への完全パスに置き換えます。 たとえば、"C:\ ACS2ClientCertificate.cer" です。

    "MyCertificatePassword"を X.509 証明書のパスワードに置き換えます。

    "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);     
    

トークン復号化証明書を追加する

この例では、Access Control名前空間に割り当てられた X.509 トークン暗号化解除証明書を追加します。

Access Control名前空間内のすべての証明書利用者アプリケーションにトークン署名証明書を追加するには

  1. 次のコードを Program クラスの Main メソッドに追加して、管理サービス クライアントを初期化します。

    ManagementService svc = CreateManagementServiceClient();
    
  2. ヘルパー関数 ReadBytesFromPfxFile を作成して、次のコードを [Program] クラスに追加することで 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] メソッドに追加します。

    注意

    以下のコードの "Full path to your .PFX file" を X.509 証明書への有効な完全パスに置き換えます。 たとえば、ACS2ClientCertificate.pfx という証明書が C: の下に保存されている場合、正しい値は "C:\ACS2ClientCertificate.pfx"。

    以下のコードの "MyCertificatePassword" を X.509 証明書の正しいパスワードに置き換えます。

    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 の利用方法