Showing posts with label Sensitivity Label. Show all posts
Showing posts with label Sensitivity Label. Show all posts

Friday, August 29, 2025

Building a Read-Only Microsoft Information Protection Sensitivity Label Reader in C#

Building a Read-Only Microsoft Information Protection Sensitivity Label Reader in C#
https://learn.microsoft.com/en-us/information-protection/develop/quick-app-initialization-csharp

Introduction

In today's data-driven world, protecting sensitive information is paramount. Microsoft Information Protection (MIP) provides robust capabilities for classifying, labeling, and protecting documents across your organization. While many solutions focus on applying and modifying sensitivity labels, there's often a need for read-only operations—such as auditing, compliance checking, or simply understanding what labels are applied to existing documents.

In this article, we'll explore how to build a simple yet powerful C# console application that reads Microsoft Information Protection sensitivity labels from files without modifying them. This solution is perfect for compliance officers, IT administrators, or developers who need to audit document classifications safely.

What We'll Build

Our application will:

  • Connect to Microsoft Information Protection services
  • List all available sensitivity labels in your organization
  • Read existing sensitivity labels from specific files
  • Display detailed label information including protection status
  • Operate in read-only mode, ensuring no modifications to files

Prerequisites

Before we start, ensure you have:

  1. Azure AD App Registration with appropriate MIP permissions
  2. Visual Studio or .NET Framework 4.8 development environment
  3. Microsoft Information Protection SDK (via NuGet)
  4. Microsoft Authentication Library (MSAL) for authentication
  5. Files with sensitivity labels applied for testing

Azure AD App Registration Setup

First, you'll need to register an application in Azure Active Directory:

  1. Navigate to the Azure Portal → Azure Active Directory → App registrations
  2. Click "New registration"
  3. Provide a name (e.g., "Sensitivity Label Reader")
  4. Set redirect URI to http://localhost (for desktop app)
  5. Under API permissions, add:
    • UnifiedPolicy.User.Read (for reading label policies)
    • InformationProtectionPolicy.Read (for accessing protection policies)

Project Setup and Dependencies

Create a new console application and install the required NuGet packages:

<PackageReference Include="Microsoft.InformationProtection.File" Version="1.17.158" />
<PackageReference Include="Microsoft.Identity.Client" Version="4.76.0" />

The Complete Implementation

Here's our streamlined, single-file implementation:

using Microsoft.InformationProtection;
using Microsoft.InformationProtection.File;
using Microsoft.Identity.Client;
using System;
using System.Linq;
using System.Threading.Tasks;

namespace ConsoleApp5
{
    internal class Program
    {
        private const string clientId = "clientId";
        private const string tenantId = "tenantId";
        private const string appName = "SensitivityLabelReader";
        private const string userEmail = "user1@demain.com";
        private const string filePath = "C:\\Users\\TestdDoc.docx";

        static void Main(string[] args)
        {
            try
            {
                // Initialize MIP SDK
                MIP.Initialize(MipComponent.File);

                // Create application info
                var appInfo = new ApplicationInfo()
                {
                    ApplicationId = clientId,
                    ApplicationName = appName,
                    ApplicationVersion = "1.0.0"
                };

                // Create delegates
                var authDelegate = new AuthDelegateImplementation(appInfo, tenantId);
                var consentDelegate = new ConsentDelegateImplementation();

                // Setup MIP context and profile
                var mipConfiguration = new MipConfiguration(appInfo, "mip_data", Microsoft.InformationProtection.LogLevel.Error, false, CacheStorageType.OnDiskEncrypted);
                var mipContext = MIP.CreateMipContext(mipConfiguration);
                var profileSettings = new FileProfileSettings(mipContext, CacheStorageType.OnDiskEncrypted, consentDelegate);
                var fileProfile = Task.Run(async () => await MIP.LoadFileProfileAsync(profileSettings)).Result;

                // Setup engine
                var engineSettings = new FileEngineSettings(userEmail, authDelegate, "", "en-US")
                {
                    Identity = new Identity(userEmail)
                };
                var fileEngine = Task.Run(async () => await fileProfile.AddEngineAsync(engineSettings)).Result;

                // Display available labels
                Console.WriteLine("Available Sensitivity Labels:");
                Console.WriteLine("==============================");
                foreach (var label in fileEngine.SensitivityLabels)
                {
                    Console.WriteLine($"{label.Name} : {label.Id}");
                    foreach (var child in label.Children)
                    {
                        Console.WriteLine($"\t{child.Name} : {child.Id}");
                    }
                }
                Console.WriteLine();

                // Read label from file
               
                Console.WriteLine($"Reading sensitivity label from: {filePath}");
                Console.WriteLine("===============================================");

                var handler = Task.Run(async () => await fileEngine.CreateFileHandlerAsync(filePath, filePath, true)).Result;
                var contentLabel = handler.Label;

                if (contentLabel?.Label != null)
                {
                    Console.WriteLine($"Label Name: {contentLabel.Label.Name}");
                    Console.WriteLine($"Label ID: {contentLabel.Label.Id}");
                    Console.WriteLine($"Is Protected: {contentLabel.IsProtectionAppliedFromLabel}");
                    if (!string.IsNullOrEmpty(contentLabel.Label.Description))
                        Console.WriteLine($"Description: {contentLabel.Label.Description}");
                    if (contentLabel.Label.Parent != null)
                        Console.WriteLine($"Parent Label: {contentLabel.Label.Parent.Name}");
                }
                else
                {
                    Console.WriteLine("No sensitivity label found on this file.");
                }
            }
            catch (Exception ex)
            {
                Console.WriteLine($"Error: {ex.Message}");
            }

            Console.WriteLine("\nPress any key to exit...");
            Console.ReadKey();
        }
    }

    // Authentication delegate for MIP SDK
    public class AuthDelegateImplementation : IAuthDelegate
    {
        private readonly ApplicationInfo _appInfo;
        private readonly string _tenantId;

        public AuthDelegateImplementation(ApplicationInfo appInfo, string tenantId)
        {
            _appInfo = appInfo;
            _tenantId = tenantId;
        }

        public string AcquireToken(Identity identity, string authority, string resource, string claims)
        {
            var authorityUri = new Uri(authority);
            authority = $"https://{authorityUri.Host}/{_tenantId}";

            var app = PublicClientApplicationBuilder
                .Create(_appInfo.ApplicationId)
                .WithAuthority(authority)
                .WithDefaultRedirectUri()
                .Build();

            var accounts = app.GetAccountsAsync().GetAwaiter().GetResult();
            var scopes = new[] { resource.TrimEnd('/') + "/.default" };

            var result = app.AcquireTokenInteractive(scopes)
                .WithAccount(accounts.FirstOrDefault())
                .WithPrompt(Prompt.SelectAccount)
                .ExecuteAsync()
                .GetAwaiter()
                .GetResult();

            return result.AccessToken;
        }
    }

    // Consent delegate for MIP SDK
    public class ConsentDelegateImplementation : IConsentDelegate
    {
        public Consent GetUserConsent(string url) => Consent.Accept;
    }
}


Featured Post

Building a Read-Only Microsoft Information Protection Sensitivity Label Reader in C#

Building a Read-Only Microsoft Information Protection Sensitivity Label Reader in C# https://learn.microsoft.com/en-us/information-protectio...

Popular posts