Share via


방법: ACS 관리 서비스를 사용하여 인증서 및 키 구성

업데이트: 2015년 6월 19일

Azure에 적용합니다.

적용 대상

  • Microsoft Azure Active Directory 액세스 제어(액세스 제어 서비스 또는 ACS라고도 함)

개요

ACS 관리 포털 또는 ACS 관리 서비스를 사용하여 ACS 인증서 및 키를 구성할 수 있습니다. ACS를 관리하기 위한 사용자 지정 사용자 인터페이스를 빌드하거나 다중 테넌트 SaaS(Software as a Service) 솔루션에 대한 새 테넌트의 온보딩을 자동화하려는 경우 ACS 관리 서비스로 작업하는 것이 더 효율적일 수 있습니다.

ACS 관리 포털을 사용하여 인증서 및 키를 구성하는 방법에 대한 자세한 내용은 인증서 및 키를 참조하세요.

ACS 관리 서비스를 사용하여 인증서 및 키를 구성하는 단계

중요

다음 단계를 수행하기 전에 시스템이 ACS 필수 구성 요소에 요약된 모든 .NET 프레임워크 및 플랫폼 요구 사항을 충족하는지 확인합니다.

ACS 관리 서비스를 사용하여 인증서 및 키를 구성하려면 다음 단계를 완료합니다.

  • 1단계 – ACS 구성 정보 수집

  • 2단계 - 샘플 콘솔 응용 프로그램 만들기

  • 3단계 - 필수 서비스 및 어셈블리에 대한 참조 추가

  • 4단계 - 관리 서비스 클라이언트 구현

  • 5단계 - 인증서 및 키 설치

    • 액세스 제어 네임스페이스에 사용되는 토큰 서명 인증서 추가

    • 신뢰 당사자 응용 프로그램에 사용되는 토큰 서명 인증서 추가

    • 액세스 제어 네임스페이스에 사용되는 토큰 서명 대칭 키 추가

    • 신뢰 당사자 응용 프로그램에 사용되는 토큰 서명 대칭 키 추가

    • 토큰 암호화 인증서 추가

    • 토큰 암호 해독 인증서 추가

1단계 – ACS 구성 정보 수집

ACS 관리 포털을 사용하여 필요한 구성 정보를 수집할 수 있습니다. 자세한 내용은 ACS 관리 포털을 참조하세요.

ACS 구성 정보를 수집하려면

  1. Microsoft Azure 관리 포털(https://manage.WindowsAzure.com)로 이동하여 로그인한 다음 Active Directory를 클릭합니다. (문제 해결 팁: "Active Directory" 항목이 없거나 사용할 수 없음)

  2. Access Control 네임스페이스를 관리하려면 네임스페이스를 선택한 다음 관리를 클릭합니다. 또는 Access Control 네임스페이스를 클릭하고 네임스페이스를 선택한 다음 관리를 클릭합니다.

  3. 관리 서비스에서 ManagementClient를 클릭한 다음 암호를 클릭합니다.

  4. 암호 필드의 값을 복사합니다.

  5. 관리 서비스를 클릭합니다. 서비스 네임스페이스 및 ACS 호스트 이름의 값을 가져옵니다. 관리 서비스 URL인 경우 네임스페이 http://contoso.accesscontrol.windows.net스는 contoso 이고 호스트 이름은 accesscontrol.windows.net.

2단계 - 샘플 콘솔 응용 프로그램 만들기

이 단계에서는 ACS 규칙 그룹 및 규칙을 추가하기 위한 코드를 실행할 수 있는 샘플 콘솔 애플리케이션을 만듭니다.

샘플 콘솔 응용 프로그램을 만들려면

  1. Visual Studio 열고 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 요청의 Authorization 헤더에 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. 다음 코드를 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 인증서의 암호로 바꿉니다.

    "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. 다음 코드를 Program 클래스에 추가하여 X.509 인증서의 바이트를 읽는 ReadBytesFromPfxFile 도우미 함수를 만듭니다.

    //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 사용 방법