다음을 통해 공유


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

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

비고

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

필수 조건

아직 없는 경우 다음을 수행해야 합니다.

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

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

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

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

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

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

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

      Visual Studio 솔루션 만들기

  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() 만듭니다. 인증 대리자는 인스턴스화되고 나중에 및 FileEngine 개체에서 FileProfile 사용됩니다.

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

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

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

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

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

    개체에는 ApplicationInfo 세 가지 속성이 포함됩니다. 클래스 _appInfo.ApplicationId 에서 클라이언트 ID를 AuthDelegateImplementation 인증 라이브러리에 제공하는 데 사용됩니다. ApplicationName Microsoft ApplicationVersion Purview 감사 보고서에 표시됩니다.

  5. 메서드를 추가합니다 public string AcquireToken() . 이 메서드는 필요한 경우 권한 URL, 리소스 URI 및 클레임의 세 가지 문자열을 수락 Microsoft.InformationProtection.Identity 해야 합니다. 이러한 문자열 변수는 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 업데이트하여 새 동의 대리자 클래스를 구현합니다. using 문을 Microsoft.InformationProtection 추가하고 상속 IConsentDelegate할 클래스를 설정합니다.

    class ConsentDelegateImplementation : IConsentDelegate
    {
         public Consent GetUserConsent(string url)
         {
              return Consent.Accept;
         }
    }
    
  3. 필요에 따라 솔루션을 빌드하여 오류 없이 컴파일되도록 합니다.

MIP SDK 관리 래퍼 초기화

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

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

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

  4. Main() Program.cs 애플리케이션 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. 다음 값을 사용하여 붙여넣은 소스 코드의 자리 표시자 값을 바꿉합니다.

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

다음 단계

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