방법: ACS 관리 서비스를 사용하여 신뢰 당사자 애플리케이션 구성

업데이트: 2015년 6월 19일

Azure에 적용합니다.

적용 대상

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

개요

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

ACS 관리 서비스를 사용하여 신뢰 당사자 응용 프로그램을 구성하는 단계

중요

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

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 Portal 또는 ACS 관리 포털의 URL에서 가져올 수 있습니다. 예를 들어 네 http://contoso.accesscontrol.windows.net임스페이스 이름은 contoso입니다.

  5. ACS 호스트 이름을 가져옵니다. 일반적으로 이 값은 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은 콘솔 응용 프로그램의 이름입니다.

    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단계 - 신뢰 당사자 애플리케이션 추가

이 단계에서는 SAML 2.0 토큰 형식(기본 옵션), 토큰 암호화 정책 없음(기본 옵션), Windows Live ID(Microsoft 계정) ID 공급자(기본 옵션), 600초의 토큰 수명(기본 옵션) 및 신뢰 당사자 애플리케이션에 대한 사용자 지정 X.509 토큰 서명 인증서 또는 토큰 서명 인증서를 사용하여 샘플 신뢰 당사자 애플리케이션을 만듭니다. 네임스페이스를 Access Control.

Access Control 네임스페이스 토큰 서명 인증서를 사용하여 신뢰 당사자 애플리케이션을 추가하려면

  1. Program 클래스의 Main 메서드에 다음 코드를 추가하여 관리 서비스 클라이언트를 초기화합니다.

    ManagementService svc = CreateManagementServiceClient();
    
  2. Program 클래스의 Main 메서드에 다음 코드를 추가하여 새 신뢰 당사자 응용 프로그램을 추가하고(이름은 아래 코드와 같이 "MyRelyingPartyApplication"으로 지정할 수 있음) 변경 내용을 저장합니다.

    참고

    아래 코드에서 "Full path to your .PFX file"을 X.509 인증서의 유효한 전체 경로로 바꿉니다. 예를 들어 ACS2ClientCertificate.cer이라는 인증서가 C:에 저장되면 올바른 값은 "C:\ ACS2ClientCertificate.cer".

    아래 코드에서 "MyCertificatePassword"를 X.509 인증서의 올바른 암호로 바꿉니다.

                //Create Relying Party Application
    
                RelyingParty relyingParty = new RelyingParty()
                {
                    Name = "MyRelyingPartyApplication",
                    AsymmetricTokenEncryptionRequired = false,
                    TokenType = "SAML_2_0",
                    TokenLifetime = 3600
                };
    
                svc.AddToRelyingParties(relyingParty);
    
    
                //Create the Realm Address
    
                RelyingPartyAddress realmAddress = new RelyingPartyAddress()
                {
                    Address = "http://TestRelyingParty.com/Realm",
                    EndpointType = "Realm"
                };
    
                svc.AddRelatedObject(relyingParty, "RelyingPartyAddresses", realmAddress);
    
                //Create the Return URL Address
    
                RelyingPartyAddress replyAddress = new RelyingPartyAddress()
                {
                    Address = "http://TestRelyingParty.com/Reply",
                    EndpointType = "Reply"
                };
    
                svc.AddRelatedObject(relyingParty, "RelyingPartyAddresses", replyAddress);
    
              // Create a Rule Group for This Relying Party Application
    
                RuleGroup rg = new RuleGroup();
                rg.Name = "SampleRuleGroup For " + relyingParty.Name;
                svc.AddToRuleGroups(rg);
    
                // Assign This New Rule Group to Your New Relying Party Application
    
                RelyingPartyRuleGroup relyingPartyRuleGroup = new RelyingPartyRuleGroup();
    
                svc.AddToRelyingPartyRuleGroups(relyingPartyRuleGroup);
                svc.AddLink(relyingParty, "RelyingPartyRuleGroups", relyingPartyRuleGroup);
                svc.AddLink(rg, "RelyingPartyRuleGroups", relyingPartyRuleGroup);
    
    
                //Save Your New Relying Party Application
    
                svc.SaveChanges(SaveChangesOptions.Batch);
    

전용 토큰 서명 인증서가 포함된 신뢰 당사자 응용 프로그램을 추가하려면

  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. Program 클래스의 Main 메서드에 다음 코드를 추가하여 새 신뢰 당사자 응용 프로그램을 추가하고(이름은 아래 코드와 같이 "MyRelyingPartyApplication"으로 지정할 수 있음) 변경 내용을 저장합니다.

    참고

    아래 코드에서 "Full path to your .PFX file"을 X.509 인증서의 유효한 전체 경로로 바꿉니다. 예를 들어 ACS2ClientCertificate.cer이라는 인증서가 C:에 저장되면 올바른 값은 "C:\ ACS2ClientCertificate.cer".

    아래 코드에서 "MyCertificatePassword"를 X.509 인증서의 올바른 암호로 바꿉니다.

                //Create Relying Party Application
    
                RelyingParty relyingParty = new RelyingParty()
                {
                    Name = "MyRelyingPartyApplication",
                    AsymmetricTokenEncryptionRequired = false,
                    TokenType = "SAML_2_0",
                    TokenLifetime = 3600
                };
    
                svc.AddToRelyingParties(relyingParty);
    
    
                //Create the Realm Address
    
                RelyingPartyAddress realmAddress = new RelyingPartyAddress()
                {
                    Address = "http://TestRelyingParty.com/Realm",
                    EndpointType = "Realm"
                };
    
                svc.AddRelatedObject(relyingParty, "RelyingPartyAddresses", realmAddress);
    
                //Create the Return URL Address
    
                RelyingPartyAddress replyAddress = new RelyingPartyAddress()
                {
                    Address = "http://TestRelyingParty.com/Reply",
                    EndpointType = "Reply"
                };
    
                svc.AddRelatedObject(relyingParty, "RelyingPartyAddresses", replyAddress);
    
                //Create 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")
                };
                svc.AddRelatedObject(relyingParty, "RelyingPartyKeys", relyingPartyKey);
    
    
              // Create a Rule Group for This Relying Party Application
    
                RuleGroup rg = new RuleGroup();
                rg.Name = "SampleRuleGroup For " + relyingParty.Name;
                svc.AddToRuleGroups(rg);
    
                // Assign This New Rule Group to Your New Relying Party Application
    
                RelyingPartyRuleGroup relyingPartyRuleGroup = new RelyingPartyRuleGroup();
    
                svc.AddToRelyingPartyRuleGroups(relyingPartyRuleGroup);
                svc.AddLink(relyingParty, "RelyingPartyRuleGroups", relyingPartyRuleGroup);
                svc.AddLink(rg, "RelyingPartyRuleGroups", relyingPartyRuleGroup);
    
    
                //Save Your New Relying Party Application
    
                svc.SaveChanges(SaveChangesOptions.Batch);
    

참고 항목

개념

ACS 사용 방법