Compartilhar via


SDK da Proteção de Informações da Microsoft – guia de início rápido de republicação do SDK de arquivo (C#)

Visão geral

Para obter uma visão geral desse cenário e saber quando usá-lo, confira Republicação no SDK do MIP.

Pré-requisitos

Conclua os seguintes pré-requisitos antes de continuar, caso ainda não tenha feito isso:

Adicionar lógica para editar e republicar um arquivo protegido

  1. Abra a solução do Visual Studio criada no artigo anterior "Guia de início rápido: definir/obter rótulos de confidencialidade (C#)".

  2. Usando o Gerenciador de Soluções, abra o arquivo .cs no projeto que contém a implementação do método Main(). Ele usa como padrão o mesmo nome que o projeto em que está contido, que você especificou durante a criação do projeto.

  3. No final do corpo de Main(), abaixo de Console.ReadKey() e acima do bloco de desligamento do aplicativo (onde você parou no Início Rápido), insira o código a seguir.

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. No final de Main() encontre o bloco de desligamento do aplicativo criado no início rápido anterior e adicione as linhas de manipuladores abaixo para liberar recursos.

        protectedFileHandler = null;
        protectionHandler = null;
    
  2. Substitua os valores de espaço reservado no código-fonte usando os seguintes valores:

    Espaço reservado Valor
    <protected-file-path> Arquivo protegido do início rápido anterior.
    <reprotected-file-path> O caminho do arquivo de saída para o arquivo modificado a ser republicado.

Criar e testar o aplicativo

Crie e teste o aplicativo cliente.

  1. Use CTRL-SHIFT-B (Compilar solução) para compilar o aplicativo cliente. Se não houver erros de build, use F5 (Iniciar depuração) para executar o aplicativo.

  2. Se seu projeto for compilado e executado com êxito, o aplicativo poderá solicitar autenticação usando a MSAL (Biblioteca de Autenticação da Microsoft) sempre que o SDK chamar seu método AcquireToken(). Se já houver credenciais armazenadas em cache, não será solicitado que você entre e veja a lista de rótulos, seguida pelas informações sobre o rótulo aplicado e o arquivo modificado.

  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.