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

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

메모

MIP .NET 정책 SDK를 사용하는 모든 클라이언트 애플리케이션에는 이 빠른 시작의 단계가 필요합니다. 시작하기 전에 MIP SDK 설정을 완료하고 구성 합니다.

사전 요구 사항

이미 하지 않았다면, 반드시 다음을 수행하세요:

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

  1. Visual Studio 2022 이상을 열고 파일 메뉴, 새로 만들기, 프로젝트를 선택합니다.

    • 콘솔 앱(.NET 8 이상 대상)을 선택합니다.
    • 프로젝트의 이름과위치를 제공합니다.
  2. MIP 정책 SDK 및 MSAL에 대한 NuGet 패키지를 추가합니다.

    • 솔루션 탐색기 프로젝트 노드를 마우스 오른쪽 단추로 클릭하고 NuGet 패키지 관리를 선택합니다.
    • 찾아보기를 선택하고, 검색 상자에 "Microsoft.InformationProtection"을 입력하고, Microsoft.InformationProtection.Policy 패키지를 설치합니다.
    • Microsoft.Identity.Client를 검색하여 설치합니다.

인증 대리자 구현

  1. 다음과 같은 새 AuthDelegateImplementation클래스를 추가합니다.

    using Microsoft.InformationProtection;
    using Microsoft.Identity.Client;
    
    public class AuthDelegateImplementation : IAuthDelegate
    {
        private ApplicationInfo _appInfo;
        private IPublicClientApplication _app;
    
        public AuthDelegateImplementation(ApplicationInfo appInfo)
        {
            _appInfo = appInfo;
        }
    
        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();
    
            string[] scopes = new string[]
            {
                resource.EndsWith('/') ? $"{resource}.default" : $"{resource}/.default"
            };
    
            var result = _app.AcquireTokenInteractive(scopes)
                .WithAccount(accounts.FirstOrDefault())
                .WithPrompt(Prompt.SelectAccount)
                .ExecuteAsync()
                .ConfigureAwait(false)
                .GetAwaiter()
                .GetResult();
    
            return result.AccessToken;
        }
    }
    
  1. 다음과 같은 새 ConsentDelegateImplementation클래스를 추가합니다.

    using Microsoft.InformationProtection;
    
    public class ConsentDelegateImplementation : IConsentDelegate
    {
        public Consent GetUserConsent(string url)
        {
            return Consent.Accept;
        }
    }
    

정책 프로필 및 엔진 초기화

  1. Program.cs를 업데이트하여 MipContext을(를) 만들고, PolicyProfile을(를) 로드한 다음, PolicyEngine을(를) 추가합니다.

    using Microsoft.InformationProtection;
    using Microsoft.InformationProtection.Policy;
    
    // Application info for Microsoft Entra app registration
    ApplicationInfo appInfo = new ApplicationInfo()
    {
        ApplicationId = "<application-id>",
        ApplicationName = "MIP SDK Policy Quickstart",
        ApplicationVersion = "1.0"
    };
    
    // Create MipConfiguration and MipContext
    var mipConfiguration = new MipConfiguration(appInfo, "mip_data", LogLevel.Trace, false, CacheStorageType.OnDiskEncrypted);
    var mipContext = MIP.CreateMipContext(mipConfiguration);
    
    // Create auth and consent delegates
    var authDelegate = new AuthDelegateImplementation(appInfo);
    var consentDelegate = new ConsentDelegateImplementation();
    
    // Create PolicyProfile
    var profileSettings = new PolicyProfileSettings(mipContext, CacheStorageType.OnDiskEncrypted);
    var profile = MIP.LoadPolicyProfileAsync(profileSettings).GetAwaiter().GetResult();
    
    // Create PolicyEngine
    var engineSettings = new PolicyEngineSettings(
        id: "<user@contoso.com>",
        authDelegate: authDelegate,
        clientData: "",
        locale: "en-US")
    {
        Identity = new Identity("<user@contoso.com>")
    };
    
    var engine = profile.AddEngineAsync(engineSettings).GetAwaiter().GetResult();
    
    Console.WriteLine("Policy engine loaded successfully.");
    
  2. 빌드 및 테스트. 애플리케이션은 정책 서비스를 초기화하고 연결해야 합니다.

다음 단계