快速入门:客户端应用程序初始化 (C#)

本快速入门介绍如何实现 MIP SDK .NET包装器在运行时使用的客户端初始化模式。

注释

使用 MIP .NET包装器的文件、策略或保护 SDK 的任何客户端应用程序都需要本快速入门中所述的步骤。 尽管本快速入门演示了文件 SDK 的使用,但此模式同样适用于使用策略和保护 SDK 的客户端。 请按顺序完成后续的快速入门,因为每一个都是在前一个的基础上进行的,而本篇是第一个。 此代码旨在演示如何开始使用 MIP SDK, 不适用于生产用途。

先决条件

如果尚未这样做,请确保:

创建 Visual Studio 解决方案和项目

首先,创建并配置初始 Visual Studio 解决方案和项目,其他快速入门都将在此基础上展开。

  1. 打开 Visual Studio 2022 或更高版本,选择 “文件 ”菜单“ 新建”和 “项目”。 在 “新建项目 ”对话框中:

    • 在左窗格中的 “已安装”下,选择“ Visual C#”,选择 “Windows 桌面”。

    • 在中心窗格中,选择“控制台应用”(面向.NET 8 或更高版本)。

    • 在底部窗格中,相应地更新项目 名称、 位置和包含 的解决方案名称 。

    • 完成后,单击右下角的 “确定 ”按钮。

      创建 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() 虚拟函数,为身份验证委托创建实现。 FileProfile 和 FileEngine 对象随后会实例化并使用身份验证委托。

  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 包含三个属性。 该 AuthDelegateImplementation 类使用 _appInfo.ApplicationId 向身份验证库提供客户端 ID。 ApplicationName和ApplicationVersion显示在 Microsoft Purview 审计报告中。

  5. 添加 public string AcquireToken() 方法。 此方法应接受 Microsoft.InformationProtection.Identity 和三个字符串:授权 URL、资源 URI 和声明(如果需要)。 API 将这些字符串变量传递到身份验证库,不应对其进行操作。 从租户的Azure门户中输入租户 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. 托管包装器包括一个静态类, 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. 使用以下值替换粘贴的源代码中的占位符值:

    占位符 价值 示例:
    <application-id> 分配给在“MIP SDK 设置和配置”中注册的应用程序的 Microsoft Entra 应用程序 ID(2 个实例)。 00001111-aaaa-2222-bbbb-3333cccc4444
    <友好名称> 应用程序的用户定义的易记名称。 AppInitialization
    <租户-GUID> 你的 Microsoft Entra 租户的租户 ID。 TenantID
  2. 现在,执行应用程序的最终构建并解决所有错误。 代码应成功生成。

后续步骤

完成初始化代码后,即可开始体验 MIP 文件 SDK 的下一个快速入门。