快速入門:用戶端應用程式初始化 (C#)

本快速入門將示範如何在執行時間實作 MIP SDK .NET 包裝函式所使用的用戶端初始化模式。

注意

使用 MIP .NET 包裝函式檔案、原則或保護 SDK 的任何用戶端應用程式都需要本快速入門中所述的步驟。 雖然本快速入門示範檔案 SDK 的使用方式,但這個相同的模式適用于使用原則和保護 SDK 的用戶端。 未來快速入門應該以序列方式完成,因為每個快速入門都是以上一個為基礎而建置,而這是第一個。 此程式碼旨在示範如何開始使用 MIP SDK,不適用於 生產環境。

必要條件

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

  • 完成 Microsoft 資訊保護 (MIP) SDK 設定和 設定中的 步驟。 本「用戶端應用程式初始化」快速入門依賴適當的 SDK 安裝和設定。
  • 選擇:
    • 檢閱 設定檔和引擎物件 。 設定檔和引擎物件是通用概念,用戶端需要使用 MIP 檔案/原則/保護 SDK。
    • 檢閱 驗證概念 ,以瞭解 SDK 和用戶端應用程式如何實作驗證和同意。

建立 Visual Studio 方案和專案

首先,我們會建立並設定初始的 Visual Studio 方案和專案,而其他快速入門將會建置。

  1. 開啟 Visual Studio 2019,選取 [ 檔案 ] 功能表 [ 新增 ]、[ 專案 ]。 在 [ 新增專案] 對話方塊中:

    • 在左窗格中的 [已安裝] 底下 選取 [Visual C# ],選取 [Windows 桌面 ]。

    • 在中央窗格中,選取 [主控台應用程式] (.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. 為 Microsoft 驗證程式庫 (MSAL) 和 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.ApplicationId將在 類別中使用 AuthDelegateImplementation ,將用戶端識別碼提供給驗證程式庫。 ApplicationNameApplicationVersion 將會顯示在 Azure 資訊保護 Analytics 報表中。

  5. 加入 public string AcquireToken() 方法。 如果必要,此方法應該接受 Microsoft.InformationProtection.Identity 和三個字串:授權單位 URL、資源 URI 和宣告。 這些字串變數會由 API 傳入驗證程式庫,不應加以操作。 請輸入租使用者的租使用者 GUID,Azure 入口網站。 編輯租使用者 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 Managed 包裝函式

  1. 方案總管 ,在您的專案中開啟包含 方法實作的 Main() .cs 檔案。 它預設為與您在專案建立期間指定的專案相同名稱。

  2. 移除 產生的 實作 main()

  3. Managed 包裝函式包含靜態類別, Microsoft.InformationProtection.MIP 用於初始化、建立 MipContext 、載入設定檔,以及釋放資源。 若要初始化檔案 SDK 作業的包裝函式,請呼叫 MIP.Initialize() ,傳入 MipComponent.File 以載入檔案作業所需的程式庫。

  4. Main() Program.cs 新增下列內容,將 < application-id > 取代為先前建立的 Microsoft Entra 應用程式註冊識別碼。

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 設定和設定」中註冊之應用程式的 Microsoft Entra 應用程式識別碼(2 個實例)。 0edbblll-8773-44de-b87c-b8c6276d41eb
    <friendly-name> 應用程式的使用者定義易記名稱。 AppInitialization
    <Tenant-GUID> Microsoft Entra 租使用者的租使用者識別碼 TenantID
  2. 現在請執行應用程式的最終組建,並解決任何錯誤。 您的程式碼應該會成功建置。

後續步驟

現在您的初始化程式碼已完成,您已準備好進行下一個快速入門,您將開始體驗 MIP 檔案 SDK。