开发应用程序Developing your application

本示例中将构建与 Azure信息保护服务 (AIP) 交互的简单控制台应用程序。In this example you are going to build a simple console application that interacts with the Azure Information Protection service (AIP). 它将要保护的文件的路径作为输入,然后使用临时策略或 Azure 模板对其进行保护。It will take as input the path of a document to protect, then protect it with an ad-hoc policy or an Azure template. 应用程序将根据输入应用正确的策略,创建信息受保护的文档。The application will then apply the correct policies according to the inputs, creating a information protected document. 你将使用的示例代码是 Azure IP 测试应用程序,位于 Github 上。The sample code you will be using is Azure IP test application and is on Github.

示例应用程序必备组件Sample app prerequisites

  • 操作系统:Windows 10、Windows 8、Windows 7、Windows Server 2008、Windows Server 2008 R2 或 Windows Server 2012Operating System: Windows 10, Windows 8, Windows 7, Windows Server 2008, Windows Server 2008 R2, or Windows Server 2012
  • 编程语言:C#(.NET Framework 3.0 及更高版本)Programming Language: C# (.NET Framework 3.0 and above)
  • 开发环境:Visual Studio 2015(以及更高版本)Development environment: Visual Studio 2015 (and later)

设置 Azure 配置Setting up your Azure Configuration

为此应用设置 Azure 需要创建租户 ID、对称密钥和应用程序主体 ID。Getting Azure set up for this app requires you to create a Tenant ID, a Symmetric Key, and an Application Principal ID.

Azure AD 租户配置Azure AD Tenant configuration

若要为 Azure 信息保护配置 Azure AD 环境,请按照 从 Azure 信息保护中激活保护服务中的指南进行操作。To configure the Azure AD environment for Azure Information Protection, follow the guidance in Activating the protection service from Azure Information Protection.

激活服务后,你需要 PowerShell 组件来执行后续步骤。Once the service is activated you will need PowerShell components for the next steps. 遵循 使用 PowerShell 管理 Azure 信息保护中的保护 来完成此操作。Follow Administering protection from Azure Information Protection by using PowerShell to accomplish this.

获取租户 IDGetting your Tenant ID

  • 以管理员身份运行 PowerShell。As an administrator, run PowerShell.
  • 导入 RMS 模块:Import-Module AIPServiceImport the RMS module: Import-Module AIPService
  • 使用分配的用户凭据连接到服务:Connect-AipService –VerboseConnect to the service with the assigned user credentials: Connect-AipService –Verbose
  • 确保已启用 RMS:enable-aipserviceEnsure RMS is enabled: enable-aipservice
  • 通过运行 Get-AipServiceConfiguration 获取租户 IDGet your tenant ID by running: Get-AipServiceConfiguration

记录 BPOSId(租户 ID)值。Record the BPOSId (tenant ID) value. 在后续步骤中需要用到。You will need it in future steps.

示例输出 cmdlet 输出Example output cmdlet output

  • 从服务断开连接:Disconnect-AipServiceServiceDisconnect from the service: Disconnect-AipServiceService

创建服务主体Create a service Principal

按照下列步骤来创建服务主体:Follow these steps to create a Service Principal:

服务主体是全局配置以用于访问控制的凭据,允许服务使用 Microsoft Azure AD 进行身份验证,并使用 Microsoft Azure AD Rights Management 保护信息A service principal is credentials configured globally for access control that allow a service to authenticate with Microsoft Azure AD and to protect information using Microsoft Azure AD Rights Management

  • 以管理员身份运行 PowerShellAs an administrator, run PowerShell
  • 使用 Import-Module MSOnline 导入 Microsoft Azure AD 模块Import the Microsoft Azure AD module using: Import-Module MSOnline
  • 使用分配的用户凭据 Connect-MsolService 连接到在线服务Connect to your online service with the assigned user credentials: Connect-MsolService
  • 通过运行 New-MsolServicePrincipal 创建新服务主体Create a new service principal by running: New-MsolServicePrincipal
  • 为服务主体提供名称Provide a name for your service principal

    记录对称密钥和应用程序主体 ID 以供将来使用。Record the symmetric key and application principal id for future use.

示例输出 cmdlet 输出Example output cmdlet output

  • 将应用程序主体 ID、对称密钥和租户 ID 添加到应用程序的 App.config 文件。Add your application principal id, symmetric key, and tenant ID to the application’s App.config file.

示例 App.config 文件 cmdlet 输出Example App.config file cmdlet output

  • 在 Azure 中注册应用程序后,你就可以使用 ClientIDRedirectUriThe ClientID and RedirectUri will be available to you from when you registered your application in Azure. 有关如何在 Azure 中注册应用程序以及获取 ClientIDRedirectUri 的详细信息,请参阅为 ADAL 身份验证配置 Azure RMSFor more information on how to register your application in Azure and to acquire a ClientID and RedirectUri see, Configure Azure RMS for ADAL authentication.

设计摘要Design summary

下图描述了你正在创建的应用的体系结构和流程,步骤如下。The following diagram depicts an architecture and process flow for the app you're creating, steps outlined below. 设计摘要design summary

  1. 用户输入:The user inputs:
    • 要保护的文件的路径The path of the file to be protected
    • 选择模板或创建临时策略Selects a template or creates an ad-hoc policy
  2. 应用程序请求使用 AIP 进行身份验证。The application requests authentication with AIP.
  3. AIP 确认身份验证AIP confirms authentication
  4. 应用程序从 AIP 请求模板。The application requests templates from the AIP.
  5. AIP 返回预定义的模板。AIP returns pre-defined templates.
  6. 应用程序通过给定位置定位指定的文件。The application locates the specified file with given location.
  7. 应用程序将 AIP 保护策略应用于文件。The application applies the AIP protection policy to the file.

代码的工作原理How the code works

在示例中,Azure IP 测试(即解决方案)以文件 Iprotect.cs 开头。In the sample, Azure IP Test, the solution begins up with the file Iprotect.cs. 这是一个 C# 控制台应用程序,与其他任何启用了 AIP 的应用程序相同,使用 main() 方法开始加载 MSIPC.dllThis is a C# console application and, like with any other AIP enabled application, you begin with loading the MSIPC.dll as shown in the main() method.

//Loads MSIPC.dll
SafeNativeMethods.IpcInitialize();
SafeNativeMethods.IpcSetAPIMode(APIMode.Server);

加载连接到 Azure 所需的参数Load the parameters needed to connect to Azure

//Loads credentials for the service principal from App.Config
SymmetricKeyCredential symmetricKeyCred = new SymmetricKeyCredential();
symmetricKeyCred.AppPrincipalId = ConfigurationManager.AppSettings["AppPrincipalId"];
symmetricKeyCred.Base64Key = ConfigurationManager.AppSettings["Base64Key"];
symmetricKeyCred.BposTenantId = ConfigurationManager.AppSettings["BposTenantId"];

在控制台应用程序中提供文件路径时,应用程序将检查文档是否已加密。When you provide the file path in the console application, the application checks if the document is already encrypted. 该方法属于 SafeFileApiNativeMethods 类。The method is of the SafeFileApiNativeMethods class.

var checkEncryptionStatus = SafeFileApiNativeMethods.IpcfIsFileEncrypted(filePath);

如果文档未加密,则继续使用提示符上提供的选择来加密文档。If the document is not encrypted, then it proceeds to encrypt the document with the selection provided on the prompt.

if (!checkEncryptionStatus.ToString().ToLower().Contains(alreadyEncrypted))
{
  if (method == EncryptionMethod1)
  {
    //Encrypt a file via AIP template
    ProtectWithTemplate(symmetricKeyCred, filePath);

  }
  else if (method == EncryptionMethod2)
  {
    //Encrypt a file using ad-hoc policy
    ProtectWithAdHocPolicy(symmetricKeyCred, filePath);
  }
}

“使用模板保护”选项继续从服务器获取模板列表,并为用户提供选项。The protect with template option proceeds to get the template list from the server and provides the user the option to select.

如果没有修改模板,则将从 AIP 获取默认模板If you did not Modify templates then you will get default templates from AIP

public static void ProtectWithTemplate(SymmetricKeyCredential symmetricKeyCredential, string filePath)
{
  // Gets the available templates for this tenant
  Collection<TemplateInfo> templates = SafeNativeMethods.IpcGetTemplateList(null, false, true,
      false, true, null, null, symmetricKeyCredential);

  //Requests tenant template to use for encryption
  Console.WriteLine("Please select the template you would like to use to encrypt the file.");

  //Outputs templates available for selection
  int counter = 0;
  for (int i = 0; i < templates.Count; i++)
  {
    counter++;
    Console.WriteLine(counter + ". " + templates.ElementAt(i).Name + "\n" +
        templates.ElementAt(i).Description);
  }

  //Parses template selection
  string input = Console.ReadLine();
  int templateSelection;
  bool parseResult = Int32.TryParse(input, out templateSelection);

  //Returns error if no template selection is entered
  if (parseResult)
  {
    //Ensures template value entered is valid
    if (0 < templateSelection && templateSelection <= counter)
    {
      templateSelection -= templateSelection;

      // Encrypts the file using the selected template
      TemplateInfo selectedTemplateInfo = templates.ElementAt(templateSelection);

      string encryptedFilePath = SafeFileApiNativeMethods.IpcfEncryptFile(filePath,
          selectedTemplateInfo.TemplateId,
          SafeFileApiNativeMethods.EncryptFlags.IPCF_EF_FLAG_KEY_NO_PERSIST, true, false, true, null,
          symmetricKeyCredential);
    }
  }
}

如果选择临时策略,应用程序的用户必须提供应具有权限的人员的电子邮件。If you select ad-hoc policy, the user of the application has to provide emails of the people that would have rights. 本节中使用 IpcCreateLicenseFromScratch() 方法创建许可证,并在模板上应用新策略。In this section the license is created using the IpcCreateLicenseFromScratch() method and applying the new policy on the template.

if (issuerDisplayName.Trim() != "")
{
  // Gets the available issuers of rights policy templates.
  // The available issuers is a list of RMS servers that this user has already contacted.
  try
  {
    Collection<TemplateIssuer> templateIssuers = SafeNativeMethods.IpcGetTemplateIssuerList(
                                                    null,
                                                    true,
                                                    false,
                                                    false, true, null, symmetricKeyCredential);

    // Creates the policy and associates the chosen user rights with it
    SafeInformationProtectionLicenseHandle handle = SafeNativeMethods.IpcCreateLicenseFromScratch(
                                                        templateIssuers.ElementAt(0));
    SafeNativeMethods.IpcSetLicenseOwner(handle, owner);
    SafeNativeMethods.IpcSetLicenseUserRightsList(handle, userRights);
    SafeNativeMethods.IpcSetLicenseDescriptor(handle, new TemplateInfo(null, CultureInfo.CurrentCulture,
                                                            policyName,
                                                            policyDescription,
                                                            issuerDisplayName,
                                                            false));

    //Encrypts the file using the ad hoc policy
    string encryptedFilePath = SafeFileApiNativeMethods.IpcfEncryptFile(
                                    filePath,
                                    handle,
                                    SafeFileApiNativeMethods.EncryptFlags.IPCF_EF_FLAG_KEY_NO_PERSIST,
                                    true,
                                    false,
                                    true,
                                    null,
                                    symmetricKeyCredential);
    }
}

用户交互示例User interaction example

创建和执行所有项后,应用程序的输出应如下所示:Once you get everything built and executing, the outputs of the application should look like the following:

  1. 系统将提示你选择加密方法。You are prompted to select an encryption method. 应用输出 - 步骤 1app output - step 1

  2. 你需要提供要保护的文件的路径。You are asked to provide the path to the file to be protected. 应用输出 - 步骤 2app output - step 2

  3. 系统将提示你输入许可证所有者的电子邮件(此所有者必须对 Azure AD 租户具有全局管理员权限)。You are prompted to enter a license owner’s email (this owner must have Global Administrator privileges on the Azure AD Tenant). 应用输出 - 步骤 3app output - step 3

  4. 输入有权访问该文件的用户的电子邮件地址(电子邮件必须以空格分隔)。You enter email addresses of users who will have rights to access the file (emails must be separated by spaces). 应用输出 - 步骤 4app output - step 4

  5. 从要向授权用户提供的权限列表中进行选择。You select from a list of rights to be given to the authorized users. 应用输出 - 步骤 5app output - step 5

  6. 最后,输入一些策略元数据:策略名称、描述和发布者(Azure AD 租户)显示名称应用输出 - 步骤6Finally, you enter some policy metadata: policy name, description, and issuer (Azure AD Tenant) display name app output - step 6