快速啟動:用戶端應用程式初始化 - Policy SDK (C#)

這個快速啟動說明如何在執行時實作 MIP SDK .NET 包裝器用於 Policy SDK 的用戶端初始化模式。

備註

本快速入門中所述的步驟是任何使用 MIP .NET Policy SDK 的客戶端應用程式所必需的。 這個快速入門應該在 設定 MIP SDK 後完成。

先決條件

如果您尚未這麼做,請務必:

建立 Visual Studio 方案和專案

  1. 開啟 Visual Studio 2022 或更新版本,選擇 檔案 選單, 新增專案

    • 選擇 主控台應用程式 (目標為 .NET 8 或更新版本)。
    • 請提供專案 名稱地點
  2. 新增 MIP Policy 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);
    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, consentDelegate);
    var profile = MIP.LoadPolicyProfileAsync(profileSettings).GetAwaiter().GetResult();
    
    // Create PolicyEngine
    var engineSettings = new PolicyEngineSettings(
        identity: new Identity("<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. 組裝並測試。 應用程式應該初始化並連接到政策服務。

下一步