本快速入门介绍如何在运行时实现 MIP SDK .NET 包装器使用的客户端初始化模式。
注释
使用 MIP .NET 包装器的文件、策略或保护 SDK 的任何客户端应用程序都需要本快速入门中所述的步骤。 尽管本快速入门演示了文件 SDK 的使用,但此模式同样适用于使用策略和保护 SDK 的客户端。 后续的快速入门应依次进行,因为每个快速入门都基于前一个,而当前这一项是首项。 此代码旨在演示如何开始使用 MIP SDK, 不适用于生产用途。
先决条件
如果尚未这样做,请确保:
- 完成 Microsoft信息保护 (MIP) SDK 设置和配置中的步骤。 本“客户端应用程序初始化”快速入门依赖于正确的 SDK 设置和配置。
- 可选:
创建 Visual Studio 解决方案和项目
首先,我们会创建并配置初始的 Visual Studio 解决方案和项目,后续的快速入门将基于此构建。
打开 Visual Studio 2019,选择 “文件 ”菜单“ 新建”和 “项目”。 在 “新建项目 ”对话框中:
将 MIP 文件 SDK 的 NuGet 包添加到项目:
- 在 解决方案资源管理器中,右键单击项目节点(直接在顶部/解决方案节点下),然后选择“ 管理 NuGet 包...”:
- 当你在编辑器组选项卡区域中打开NuGet 包管理器选项卡时:
- 选择“浏览”。
- 在搜索框中输入“Microsoft.InformationProtection”。
- 选择“Microsoft.InformationProtection.File”包。
- 单击“安装”,然后在 “预览”更改 确认对话框显示时单击“确定”。
重复上述步骤以添加 MIP 文件 SDK 包,并将“Microsoft.Identity.Client”添加到您的应用程序中。
实现身份验证委托
MIP SDK 使用类扩展性实现身份验证,该扩展提供一种机制来与客户端应用程序共享身份验证工作。 客户端必须获取合适的 OAuth2 访问令牌,并在运行时提供给 MIP SDK。
现在,通过扩展 SDK 的 Microsoft.InformationProtection.IAuthDelegate 接口并重写/实现 IAuthDelegate.AcquireToken() 虚拟函数,为身份验证委托创建实现。 身份验证委托稍后被实例化并供FileProfileFileEngine对象使用。
在 Visual Studio 中右键单击项目名称,选择“ 添加 ”,然后选择 “类”。
在 “名称 ”字段中输入“AuthDelegateImplementation”。 单击 添加。
为 Microsoft 身份验证库 (MSAL) 和 MIP 库添加 using 语句:
using Microsoft.InformationProtection; using Microsoft.Identity.Client;将
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类中,以向身份验证库提供客户端 ID。ApplicationName和ApplicationVersion将显示在 Microsoft Purview 审核报告中。添加
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。
使用以前使用的同一 Visual Studio“添加类”功能,将另一个类添加到项目中。 这次在“类名”字段中输入“ConsentDelegateImplementation”。
现在 更新ConsentDelegateImpl.cs 来实现新的许可委托类。 为
Microsoft.InformationProtection添加 using 语句,并将类设置为继承IConsentDelegate。class ConsentDelegateImplementation : IConsentDelegate { public Consent GetUserConsent(string url) { return Consent.Accept; } }(可选)尝试生成解决方案,以确保它编译时不会出错。
初始化 MIP SDK 托管包装器
在 解决方案资源管理器中,打开项目中包含方法实现
Main()的.cs文件。 它默认与其所在项目同名,这是您在创建项目时指定的。删除
main()的生成实现。托管包装器包括一个静态类,
Microsoft.InformationProtection.MIP用于初始化、创建MipContext、加载配置文件和释放资源。 若要初始化文件 SDK 操作的包装器,请调用MIP.Initialize()并传入MipComponent.File以加载文件操作所需的库。在
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;
}
}
}
使用以下值替换粘贴的源代码中的占位符值:
占位符 价值 示例: <application-id> 分配给在“MIP SDK 安装和配置”中注册的应用程序的 Microsoft Entra 应用程序 ID(2 个实例)。 0edbblll-8773-44de-b87c-b8c6276d41eb <friendly-name> 应用程序的用户定义的易记名称。 AppInitialization <租户-GUID> Microsoft Entra 租户的租户 ID TenantID 现在,执行应用程序的最终构建并解决所有错误。 代码应成功生成。
后续步骤
完成初始化代码后,接下来可以开始学习下一个快速入门,你将开始了解 MIP 文件 SDK。