빠른 시작: 클라이언트 애플리케이션 초기화(C#)

이 빠른 시작에서는 런타임 시 MIP SDK .NET 래퍼에서 사용하는 클라이언트 초기화 패턴을 구현하는 방법을 보여줍니다.

참고 항목

이 빠른 시작에 설명된 단계는 MIP .NET 래퍼의 파일, 정책 또는 보호 SDK를 사용하는 모든 클라이언트 애플리케이션에 필요합니다. 이 빠른 시작에서는 파일 SDK의 사용을 보여 주지만, 이 동일한 패턴은 정책 및 보호 SDK를 사용하는 클라이언트에 적용할 수 있습니다. 향후의 빠른 시작은 각 작업이 이전 작업을 기반으로 빌드되며. 이 작업이 첫 번째 작업이므로 순차적으로 수행해야 합니다. 이 코드는 MIP SDK를 시작하는 방법을 보여주기 위한 것이며 프로덕션용이 아닙니다.

필수 조건

아직 없는 경우 다음을 확인해야 합니다.

  • MIP(Microsoft Information Protection) SDK 설정 및 구성의 단계를 완료합니다. 이 “클라이언트 애플리케이션 초기화” 빠른 시작은 적절한 SDK 설정 및 구성에 의존합니다.
  • 필요:
    • 프로필 및 엔진 개체를 검토합니다. 프로필 및 엔진 개체는 MIP 파일/정책/보호 SDK를 사용하는 클라이언트에서 요구하는 범용 개념입니다.
    • 인증 개념을 검토하여 SDK 및 클라이언트 애플리케이션에서 인증 및 동의를 구현하는 방법을 알아봅니다.

Visual Studio 솔루션 및 프로젝트 만들기

먼저, 다른 빠른 시작이 빌드되는 Visual Studio 초기 솔루션 및 프로젝트를 만들고 구성합니다.

  1. Visual Studio 2019를 열고 파일 메뉴, 새로 만들기, 프로젝트를 선택합니다. 새 프로젝트 대화 상자에서 다음을 수행합니다.

    • 왼쪽 창의 설치됨, Visual C#에서 Windows Desktop을 선택합니다.

    • 가운데 창에서 콘솔 앱(.NET Framework)을 선택합니다.

    • 아래쪽 창에서 프로젝트 이름, 위치, 포함된 솔루션 이름을 적절하게 업데이트합니다.

    • 완료되면 오른쪽 아래에서 확인 단추를 클릭합니다.

      Visual Studio solution creation

  2. 프로젝트에 MIP 파일 SDK에 대한 Nuget 패키지를 추가합니다.

    • 솔루션 탐색기에서 프로젝트 노드(상단/솔루션 노드 바로 아래)를 마우스 오른쪽 단추로 클릭하고 NuGet 패키지 관리...를 선택합니다.
    • 편집기 그룹 탭 영역에서 NuGet 패키지 관리자 탭이 열리는 경우:
      • 찾아보기를 선택합니다.
      • 검색 상자에 “Microsoft.InformationProtection”을 입력합니다.
      • “Microsoft.InformationProtection.File” 패키지를 선택합니다.
      • “설치”를 클릭한 다음, 미리 보기 변경 확인 대화 상자가 표시되어 있는 경우 “확인”을 클릭합니다.
  3. MIP 파일 SDK 패키지를 추가하기 위해 위의 단계를 반복하되 대신 애플리케이션에 “Microsoft.Identity.Client”를 추가합니다.

인증 대리자 구현

MIP SDK는 클래스 확장성을 사용하여 인증을 구현합니다. 이는 클라이언트 애플리케이션과 인증 작업을 공유하는 메커니즘을 제공합니다. 클라이언트는 적절한 OAuth2 액세스 토큰을 획득하고 런타임 시 이를 MIP SDK에 제공해야 합니다.

이제 SDK의 Microsoft.InformationProtection.IAuthDelegate 인터페이스를 확장하고 IAuthDelegate.AcquireToken() 가상 함수를 재정의/구현하여 인증 대리자에 대한 구현을 만들 수 있습니다. 인증 대리자는 FileProfileFileEngine 개체에서 인스턴스화되고 나중에 사용됩니다.

  1. Visual Studio에서 프로젝트 이름을 마우스 오른쪽 단추로 클릭하고 추가를 선택한 다음, 클래스를 선택합니다.

  2. 이름 필드에 “AuthDelegateImplementation”을 입력합니다. 추가를 클릭합니다.

  3. MSAL(Microsoft 인증 라이브러리) 및 MIP 라이브러리에 대한 using 문을 추가합니다.

    using Microsoft.InformationProtection;
    using Microsoft.Identity.Client;
    
  4. AuthDelegateImplementation을 설정하여 Microsoft.InformationProtection.IAuthDelegate를 상속하고 Microsoft.InformationProtection.ApplicationInfo의 프라이빗 변수와 동일한 유형을 허용하는 생성자를 구현합니다.

    public class AuthDelegateImplementation : IAuthDelegate
    {
       private ApplicationInfo _appInfo;
       // Microsoft Authentication Library IPublicClientApplication
       private IPublicClientApplication _app;
       public AuthDelegateImplementation(ApplicationInfo appInfo)
       {
           _appInfo = appInfo;
       }
    
    }
    

    ApplicationInfo 개체는 세 가지 속성을 포함합니다. _appInfo.ApplicationIdAuthDelegateImplementation 클래스에서 클라이언트 ID를 인증 라이브러리에 제공하는 데 사용됩니다. ApplicationNameApplicationVersion은 Azure Information Protection Analytics 보고서에 표시됩니다.

  5. public string AcquireToken() 메서드를 추가합니다. 이 메서드는 필요한 경우 Microsoft.InformationProtection.Identity 및 세 개의 문자열(권한 URL, 리소스 URI 및 클레임)을 수락해야 합니다. 이러한 문자열 변수는 API에 의해 인증 라이브러리에 전달되며 조작해서는 안 됩니다. 테넌트에 대한 Azure Portal에서 테넌트 GUID를 입력하세요. 테넌트 GUID 이외의 문자열을 편집하면 인증에 실패할 수 있습니다.

    public string AcquireToken(Identity identity, string authority, string resource, string claims)
    {
       var authorityUri = new Uri(authority);
       authority = String.Format("https://{0}/{1}", authorityUri.Host, "<Tenant-GUID>");
    
       _app = PublicClientApplicationBuilder.Create(_appInfo.ApplicationId).WithAuthority(authority).WithDefaultRedirectUri().Build();
       var accounts = (_app.GetAccountsAsync()).GetAwaiter().GetResult();
    
       // Append .default to the resource passed in to AcquireToken().
       string[] scopes = new string[] { resource[resource.Length - 1].Equals('/') ? $"{resource}.default" : $"{resource}/.default" };
       var result = _app.AcquireTokenInteractive(scopes).WithAccount(accounts.FirstOrDefault()).WithPrompt(Prompt.SelectAccount)
                  .ExecuteAsync().ConfigureAwait(false).GetAwaiter().GetResult();
    
       return result.AccessToken;
    }
    
    

이제 SDK의 Microsoft.InformationProtection.IConsentDelegate 인터페이스를 확장하고 GetUserConsent()를 재정의/구현하여 동의 대리자에 대한 구현을 만들 수 있습니다. 동의 대리자는 나중에 파일 프로필 및 파일 엔진 개체에 의해 인스턴스화되어 사용됩니다. 동의 대리자는 사용자가 url 매개 변수에서 사용하는 데 동의해야 하는 서비스의 주소와 함께 제공됩니다. 대리자는 일반적으로 사용자가 서비스에 액세스하는 데 동의하거나 거부할 수 있는 몇 가지 흐름을 제공해야 합니다. 이 빠른 시작 하드 코드 Consent.Accept의 경우

  1. 이전에 사용한 동일한 Visual Studio “클래스 추가” 기능을 사용하여 프로젝트에 다른 클래스를 추가합니다. 이번에는 클래스 이름 필드에 “ConsentDelegateImplementation”을 입력합니다.

  2. 이제 ConsentDelegateImpl.cs를 업데이트하여 새 동의 대리자 클래스를 구현합니다. Microsoft.InformationProtection에 대한 using 문을 추가하고 IConsentDelegate를 상속하도록 클래스를 설정합니다.

    class ConsentDelegateImplementation : IConsentDelegate
    {
         public Consent GetUserConsent(string url)
         {
              return Consent.Accept;
         }
    }
    
  3. 선택적으로 오류가 없는 컴파일되도록 솔루션을 빌드하려고 합니다.

MIP SDK 관리형 래퍼 초기화

  1. 솔루션 탐색기에서 Main() 메서드 구현을 포함하는 프로젝트에서 .cs 파일을 엽니다. 기본값은 프로젝트 생성 중에 지정한 이름이 포함된 프로젝트와 동일한 이름입니다.

  2. main()의 생성된 구현을 제거합니다.

  3. 관리되는 래퍼에는 초기화, MipContext 생성, 프로필 로드 및 리소스 공개에 사용되는 정적 클래스인 Microsoft.InformationProtection.MIP가 포함됩니다. 파일 SDK 작업에 대한 래퍼를 초기화하려면 MIP.Initialize()를 호출하고 MipComponent.File에 전달하여 파일 작업에 필요한 라이브러리를 로드합니다.

  4. Program.cs에서 Main() 애플리케이션 ID>를 이전에 만든 Microsoft Entra 애플리케이션 등록의 ID로 바꾸는< 다음을 추가합니다.

using System;
using System.Threading.Tasks;
using Microsoft.InformationProtection;
using Microsoft.InformationProtection.Exceptions;
using Microsoft.InformationProtection.File;
using Microsoft.InformationProtection.Protection;

namespace mip_sdk_dotnet_quickstart
{
    class Program
    {
        private const string clientId = "<application-id>";
        private const string appName = "<friendly-name>";

        static void Main(string[] args)
        {
            //Initialize Wrapper for File SDK operations
            MIP.Initialize(MipComponent.File);
            
        }
    }
}

파일 프로필 및 엔진 구성

위에서 언급한 것처럼 MIP API를 사용하는 SDK 클라이언트에 프로필 및 엔진 개체가 필요합니다. 네이티브 DLL을 로드한 다음, 프로필 및 엔진 개체를 인스턴스화하는 코드를 추가하여 이 빠른 시작의 코딩 부분을 완료합니다.

using System;
using System.Threading.Tasks;
using Microsoft.InformationProtection;
using Microsoft.InformationProtection.File;

namespace mip_sdk_dotnet_quickstart
{
  class Program
  {
       private const string clientId = "<application-id>";
       private const string appName = "<friendly-name>";

       static void Main(string[] args)
       {
            // Initialize Wrapper for File SDK operations.
            MIP.Initialize(MipComponent.File);

            // Create ApplicationInfo, setting the clientID from Microsoft Entra App Registration as the ApplicationId.
            ApplicationInfo appInfo = new ApplicationInfo()
            {
                 ApplicationId = clientId,
                 ApplicationName = appName,
                 ApplicationVersion = "1.0.0"
            };

            // Instantiate the AuthDelegateImpl object, passing in AppInfo.
            AuthDelegateImplementation authDelegate = new AuthDelegateImplementation(appInfo);

            // Create MipConfiguration Object
            MipConfiguration mipConfiguration = new MipConfiguration(appInfo, "mip_data", LogLevel.Trace, false);

            // Create MipContext using Configuration
            MipContext mipContext = MIP.CreateMipContext(mipConfiguration);

            // Initialize and instantiate the File Profile.
            // Create the FileProfileSettings object.
            // Initialize file profile settings to create/use local state.
            var profileSettings = new FileProfileSettings(mipContext,
                                     CacheStorageType.OnDiskEncrypted,
                                     new ConsentDelegateImplementation());

            // Load the Profile async and wait for the result.
            var fileProfile = Task.Run(async () => await MIP.LoadFileProfileAsync(profileSettings)).Result;

            // Create a FileEngineSettings object, then use that to add an engine to the profile.
            // This pattern sets the engine ID to user1@tenant.com, then sets the identity used to create the engine.
            var engineSettings = new FileEngineSettings("user1@tenant.com", authDelegate, "", "en-US");
            engineSettings.Identity = new Identity("user1@tenant.com");

            var fileEngine = Task.Run(async () => await fileProfile.AddEngineAsync(engineSettings)).Result;

            // Application Shutdown
            // handler = null; // This will be used in later quick starts.
            fileEngine = null;
            fileProfile = null;
            mipContext.ShutDown();
            mipContext = null;
       }
  }
}
  1. 다음 값을 사용하여 붙여넣은 소스 코드의 자리 표시자 값을 바꿉니다.

    자리 표시자 예시
    <application-id> "MIP SDK 설정 및 구성"(2개 인스턴스)에 등록된 애플리케이션에 할당된 Microsoft Entra 애플리케이션 ID입니다. 0edbblll-8773-44de-b87c-b8c6276d41eb
    <friendly-name> 애플리케이션에 대한 사용자 정의 식별 이름입니다. AppInitialization
    <테넌트-GUID> Microsoft Entra 테넌트에 대한 테넌트 ID TenantID
  2. 이제 애플리케이션의 최종 빌드를 실행하고 오류를 해결합니다. 코드가 성공적으로 빌드됩니다.

다음 단계

이제 초기화 코드가 완료되었으므로 다음 빠른 시작에 대한 준비가 완료되어 MIP 파일 SDK를 경험하기 시작할 수 있습니다.