Поделиться через


Пакет SDK Microsoft Information Protection. Краткое руководство по повторной публикации пакета SDK файлов (C#)

Обзор

Общие сведения об этом сценарии и о том, когда его можно использовать, см. в статье Повторная публикация в пакете SDK для MIP.

Необходимые компоненты

Прежде чем продолжить, выполните следующие предварительные требования:

Добавление логики для изменения и повторной публикации защищенного файла

  1. Откройте решение Visual Studio, созданное при изучении предыдущей статьи "Краткое руководство: Установка и получение меток конфиденциальности (C#)".

  2. С помощью Обозревателя решений откройте в проекте CS-файл, содержащий реализацию метода Main(). По умолчанию он имеет то же имя, что и содержащий его проект, который вы указали при создании проекта.

  3. Вставьте указанный ниже код в конце тела метода Main(), после Console.ReadKey() и перед блоком завершения работы приложения (где вы закончили работу в предыдущем кратком руководстве).

string protectedFilePath = "<protected-file-path>" // Originally protected file's path from previous quickstart.

//Create a fileHandler for consumption for the Protected File.
var protectedFileHandler = Task.Run(async () => 
                            await fileEngine.CreateFileHandlerAsync(protectedFilePath,// inputFilePath
                                                                    protectedFilePath,// actualFilePath
                                                                    false, //isAuditDiscoveryEnabled
                                                                    null)).Result; // fileExecutionState

// Store protection handler from file
var protectionHandler = protectedFileHandler.Protection;

//Check if the user has the 'Edit' right to the file
if (protectionHandler.AccessCheck("Edit"))
{
    // Decrypt file to temp path
    var tempPath = Task.Run(async () => await protectedFileHandler.GetDecryptedTemporaryFileAsync()).Result;

    /*
        Your own application code to edit the decrypted file belongs here. 
    */

    /// Follow steps below for re-protecting the edited file. ///
    // Create a new file handler using the temporary file path.
    var republishHandler = Task.Run(async () => await fileEngine.CreateFileHandlerAsync(tempPath, tempPath, false)).Result;

    // Set protection using the ProtectionHandler from the original consumption operation.
    republishHandler.SetProtection(protectionHandler);

    // New file path to save the edited file
    string reprotectedFilePath = "<reprotected-file-path>" // New file path for saving reprotected file.

    // Write changes
    var reprotectedResult = Task.Run(async () => await republishHandler.CommitAsync(reprotectedFilePath)).Result;

    var protectedLabel = protectedFileHandler.Label;
    Console.WriteLine(string.Format("Originally protected file: {0}", protectedFilePath));
    Console.WriteLine(string.Format("File LabelID: {0} \r\nProtectionOwner: {1} \r\nIsProtected: {2}", 
                        protectedLabel.Label.Id, 
                        protectedFileHandler.Protection.Owner, 
                        protectedLabel.IsProtectionAppliedFromLabel.ToString()));
    var reprotectedLabel = republishHandler.Label;
    Console.WriteLine(string.Format("Reprotected file: {0}", reprotectedFilePath));
    Console.WriteLine(string.Format("File LabelID: {0} \r\nProtectionOwner: {1} \r\nIsProtected: {2}", 
                        reprotectedLabel.Label.Id, 
                        republishHandler.Protection.Owner, 
                        reprotectedLabel.IsProtectionAppliedFromLabel.ToString()));
    Console.WriteLine("Press a key to continue.");
    Console.ReadKey();
}
  1. В конце метода Main() найдите блок завершения работы приложения, созданный в предыдущем кратком руководстве, и добавьте указанные ниже строки, чтобы освободить ресурсы.

        protectedFileHandler = null;
        protectionHandler = null;
    
  2. Замените значения-заполнители в исходном коде следующими значениями:

    Заполнитель Значение
    <protected-file-path> Защищенный файл из предыдущего краткого руководства.
    <reprotected-file-path> Путь к выходному файлу для повторной публикации измененного файла.

Создание и тестирование приложения

Выполните сборку клиентского приложения и протестируйте его.

  1. Нажмите клавиши CTRL+SHIFT+B (Собрать решение), чтобы выполнить сборку клиентского приложения. Если ошибок сборки нет, нажмите клавишу F5 (Начать отладку), чтобы запустить приложение.

  2. Если проект успешно создан и запущен, приложение может запрашивать проверку подлинности через Библиотеку проверки подлинности Майкрософт (MSAL) каждый раз, когда пакет SDK вызывает метод AcquireToken(). Если кэшированные учетные данные уже имеются, вам не будет предлагаться выполнить вход и просмотреть список меток со сведениями о каждой из них и об измененных файлах.

  Personal : 73c47c6a-eb00-4a6a-8e19-efaada66dee6
  Public : 73254501-3d5b-4426-979a-657881dfcb1e
  General : da480625-e536-430a-9a9e-028d16a29c59
  Confidential : 569af77e-61ea-4deb-b7e6-79dc73653959
  Highly Confidential : 905845d6-b548-439c-9ce5-73b2e06be157
  Press a key to continue.

  Getting the label committed to file: C:\Test\Test_protected.docx
  File Label: Confidential
  IsProtected: True
  Press a key to continue.
  Originally protected file: C:\Test\Test_protected.docx
  File LabelID: 569af77e-61ea-4deb-b7e6-79dc73653959
  ProtectionOwner: User1@Contoso.OnMicrosoft.com
  IsProtected: True
  Reprotected file: C:\Test\Test_reprotected.docx
  File LabelID: 569af77e-61ea-4deb-b7e6-79dc73653959
  ProtectionOwner: User1@Contoso.OnMicrosoft.com
  IsProtected: True
  Press a key to continue.