Início Rápido: Computar ações de política - SDK da Política (C#)

Este início rápido mostra como usar o SDK de Política de .NET MIP para calcular as ações que devem ser executadas ao aplicar ou alterar rótulos de confidencialidade.

Prerequisites

Caso ainda não tenha feito isso, certifique-se de concluir os seguintes pré-requisitos antes de continuar:

Implementar ExecutionState

Antes de chamar ComputeActions(), você precisa de uma implementação da classe abstrata ExecutionState que forneça o estado de rótulo atual e desejado.

  1. Abra a solução do Visual Studio que você criou no início rápido anterior.

  2. Adicione uma nova classe ao projeto que deriva de ExecutionState:

    using Microsoft.InformationProtection;
    using Microsoft.InformationProtection.Policy;
    using Microsoft.InformationProtection.Policy.Actions;
    using System;
    using System.Collections.Generic;
    using System.Linq;
    
    public class PolicyExecutionState : ExecutionState
    {
        private Label _newLabel;
        private AssignmentMethod _assignmentMethod;
        private List<MetadataEntry> _metadata;
        private bool _isDowngradeJustified;
        private string _downgradeJustification;
        private string _contentIdentifier;
    
        public PolicyExecutionState(
            Label newLabel,
            string contentIdentifier,
            AssignmentMethod assignmentMethod = AssignmentMethod.Standard,
            List<MetadataEntry> existingMetadata = null,
            bool isDowngradeJustified = false,
            string downgradeJustification = "")
        {
            _newLabel = newLabel;
            _contentIdentifier = contentIdentifier;
            _assignmentMethod = assignmentMethod;
            _metadata = existingMetadata ?? new List<MetadataEntry>();
            _isDowngradeJustified = isDowngradeJustified;
            _downgradeJustification = downgradeJustification;
        }
    
        public override Label GetNewLabel()
        {
            return _newLabel;
        }
    
        public override AssignmentMethod GetNewLabelAssignmentMethod()
        {
            return _assignmentMethod;
        }
    
        public override ProtectionDescriptor GetProtectionDescriptor()
        {
            return null;
        }
    
        public override string GetContentFormat()
        {
            return ContentFormat.File;
        }
    
        public override string GetContentIdentifier()
        {
            return _contentIdentifier;
        }
    
        public override ActionType GetSupportedActions()
        {
            return ActionType.Metadata
                | ActionType.ProtectByTemplate
                | ActionType.Justify
                | ActionType.AddContentFooter
                | ActionType.AddContentHeader
                | ActionType.AddWatermark;
        }
    
        public override bool IsDowngradeJustified(out string justification)
        {
            justification = _downgradeJustification;
            return _isDowngradeJustified;
        }
    
        public override List<MetadataEntry> GetContentMetadata(
            List<string> names, List<string> namePrefixes)
        {
            return _metadata.Where(entry =>
                (names.Count == 0 && namePrefixes.Count == 0)
                || names.Contains(entry.Key)
                || namePrefixes.Any(prefix => entry.Key.StartsWith(prefix, StringComparison.Ordinal)))
                .ToList();
        }
    }
    

Calcular ações para um novo rótulo

Adicione lógica para calcular as ações necessárias ao aplicar um novo rótulo ao conteúdo sem rótulo.

Depois que o mecanismo for carregado e os rótulos estiverem listados, adicione o código a seguir. Importe Microsoft.InformationProtection.Policy.Actions no arquivo que contém este código:

// Replace with a valid label ID from your tenant.
string newLabelId = "<label-id>";

// Resolve the label by ID.
var label = engine.GetLabelById(newLabelId);

// Create the ExecutionState for applying a new label.
var state = new PolicyExecutionState(
    newLabel: label,
    contentIdentifier: "MyDocument.docx");

// Create a policy handler and compute actions.
var handler = engine.CreatePolicyHandler(false);
var actions = handler.ComputeActions(state);

Console.WriteLine("\nActions for applying label:");

foreach (var action in actions)
{
    if (action is MetadataAction metadataAction)
    {
        Console.WriteLine("MetadataAction:");
        foreach (var name in metadataAction.MetadataToRemove)
        {
            Console.WriteLine($"  Remove: {name}");
        }
        foreach (var prop in metadataAction.MetadataToAdd)
        {
            Console.WriteLine($"  Add: {prop.Key} : {prop.Value}");
        }
    }
    else if (action is ProtectByTemplateAction protectAction)
    {
        Console.WriteLine($"ProtectByTemplateAction: TemplateId = {protectAction.TemplateId}");
    }
    else if (action is AddContentFooterAction)
    {
        Console.WriteLine("AddContentFooterAction");
    }
    else if (action is AddContentHeaderAction)
    {
        Console.WriteLine("AddContentHeaderAction");
    }
    else if (action is AddWatermarkAction)
    {
        Console.WriteLine("AddWatermarkAction");
    }
    else if (action is JustifyAction)
    {
        Console.WriteLine("JustifyAction");
    }
    else
    {
        Console.WriteLine($"Other action: {action.GetType().Name}");
    }
}

Manipular um cenário de downgrade de rótulo

Ao alterar de um rótulo de confidencialidade mais alto para um menor, a política pode exigir justificativa. Substitua ambos os espaços reservados de ID de rótulo por rótulos distintos do seu locatário. Na produção, leia os metadados existentes completos do conteúdo e obtenha justificativa do usuário; o código a seguir usa metadados simplificados e uma justificativa fixa para demonstração.

// Resolve the lower sensitivity label.
var lowerLabel = engine.GetLabelById("<lower-sensitivity-label-id>");

// Build existing metadata from the previously applied label.
var existingMetadata = new List<MetadataEntry>
{
    new MetadataEntry("MSIP_Label_<previous-label-id>_Enabled", "true",
        new MetadataVersion(0, MetadataVersionFormat.DEFAULT)),
    new MetadataEntry("MSIP_Label_<previous-label-id>_Method", "Standard",
        new MetadataVersion(0, MetadataVersionFormat.DEFAULT))
};

// Create the ExecutionState with downgrade justification.
var downgradeState = new PolicyExecutionState(
    newLabel: lowerLabel,
    contentIdentifier: "MyDocument.docx",
    existingMetadata: existingMetadata,
    isDowngradeJustified: true,
    downgradeJustification: "Manager approved declassification");

var downgradeHandler = engine.CreatePolicyHandler(false);
var downgradeActions = downgradeHandler.ComputeActions(downgradeState);

Console.WriteLine("\nActions for label downgrade:");
foreach (var action in downgradeActions)
{
    Console.WriteLine($"  Action: {action.GetType().Name}");
}

Criar e testar o aplicativo

Crie e teste seu aplicativo cliente.

  1. Use Ctrl+Shift+B (Build Solution) para criar o aplicativo. Se você não tiver erros de build, use F5 (Iniciar depuração) para executar.

  2. Na primeira execução, o aplicativo solicita autenticação. Forneça credenciais para uma conta de usuário em seu locatário.

  3. A saída deve exibir as ações computadas para o rótulo especificado, semelhante a:

    Actions for applying label:
    MetadataAction:
      Add: MSIP_Label_<label-id>_Enabled : true
      Add: MSIP_Label_<label-id>_SetDate : 2026-03-11T10:00:00-0800
      Add: MSIP_Label_<label-id>_Method : Standard
      Add: MSIP_Label_<label-id>_Name : Confidential
      Add: MSIP_Label_<label-id>_SiteId : <site-id>
      Add: MSIP_Label_<label-id>_ActionId : <action-id>
      Add: MSIP_Label_<label-id>_ContentBits : 3
    AddContentFooterAction
    AddContentHeaderAction
    

Próximas Etapas 

Este início rápido exibe apenas ações; ele não rotula, marca ou protege o documento. Um aplicativo completo deve implementar todas as ações que ele anuncia por meio de GetSupportedActions(). Manipule a justificativa antes de confirmar alterações e chame NotifyCommittedActions(state) somente depois que as ações tiverem sido aplicadas e o conteúdo confirmado com êxito.