Quickstart: Client application initialization - Policy SDK (C#)

This quickstart shows you how to implement the client initialization pattern used by the MIP SDK .NET wrapper for the Policy SDK at runtime.

Note

Any client application that uses the MIP .NET Policy SDK needs the steps in this quickstart. Complete Set up and configure MIP SDK before you start.

Prerequisites

If you haven't already, be sure to:

Create a Visual Studio solution and project

  1. Open Visual Studio 2022 or later, select the File menu, New, Project.

    • Select Console App (targeting .NET 8 or later).
    • Provide a Name and Location for the project.
  2. Add the NuGet packages for the MIP Policy SDK and MSAL:

    • In Solution Explorer, right-click the project node and select Manage NuGet packages....
    • Select Browse, enter "Microsoft.InformationProtection" in the search box, and install the Microsoft.InformationProtection.Policy package.
    • Search for and install Microsoft.Identity.Client.

Implement an authentication delegate

  1. Add a new class named AuthDelegateImplementation:

    using Microsoft.InformationProtection;
    using Microsoft.Identity.Client;
    
    public class AuthDelegateImplementation : IAuthDelegate
    {
        private ApplicationInfo _appInfo;
        private IPublicClientApplication _app;
    
        public AuthDelegateImplementation(ApplicationInfo appInfo)
        {
            _appInfo = appInfo;
        }
    
        public string AcquireToken(Identity identity, string authority, string resource, string claims)
        {
            var authorityUri = new Uri(authority);
            authority = string.Format("https://{0}/{1}", authorityUri.Host, "<Tenant-GUID>");
    
            _app = PublicClientApplicationBuilder
                .Create(_appInfo.ApplicationId)
                .WithAuthority(authority)
                .WithDefaultRedirectUri()
                .Build();
    
            var accounts = _app.GetAccountsAsync().GetAwaiter().GetResult();
    
            string[] scopes = new string[]
            {
                resource.EndsWith('/') ? $"{resource}.default" : $"{resource}/.default"
            };
    
            var result = _app.AcquireTokenInteractive(scopes)
                .WithAccount(accounts.FirstOrDefault())
                .WithPrompt(Prompt.SelectAccount)
                .ExecuteAsync()
                .ConfigureAwait(false)
                .GetAwaiter()
                .GetResult();
    
            return result.AccessToken;
        }
    }
    
  1. Add a new class named ConsentDelegateImplementation:

    using Microsoft.InformationProtection;
    
    public class ConsentDelegateImplementation : IConsentDelegate
    {
        public Consent GetUserConsent(string url)
        {
            return Consent.Accept;
        }
    }
    

Initialize the Policy profile and engine

  1. Update Program.cs to create the MipContext, load a PolicyProfile, and add a PolicyEngine:

    using Microsoft.InformationProtection;
    using Microsoft.InformationProtection.Policy;
    
    // Application info for Microsoft Entra app registration
    ApplicationInfo appInfo = new ApplicationInfo()
    {
        ApplicationId = "<application-id>",
        ApplicationName = "MIP SDK Policy Quickstart",
        ApplicationVersion = "1.0"
    };
    
    // Create MipConfiguration and MipContext
    var mipConfiguration = new MipConfiguration(appInfo, "mip_data", LogLevel.Trace, false, CacheStorageType.OnDiskEncrypted);
    var mipContext = MIP.CreateMipContext(mipConfiguration);
    
    // Create auth and consent delegates
    var authDelegate = new AuthDelegateImplementation(appInfo);
    var consentDelegate = new ConsentDelegateImplementation();
    
    // Create PolicyProfile
    var profileSettings = new PolicyProfileSettings(mipContext, CacheStorageType.OnDiskEncrypted);
    var profile = MIP.LoadPolicyProfileAsync(profileSettings).GetAwaiter().GetResult();
    
    // Create PolicyEngine
    var engineSettings = new PolicyEngineSettings(
        id: "<user@contoso.com>",
        authDelegate: authDelegate,
        clientData: "",
        locale: "en-US")
    {
        Identity = new Identity("<user@contoso.com>")
    };
    
    var engine = profile.AddEngineAsync(engineSettings).GetAwaiter().GetResult();
    
    Console.WriteLine("Policy engine loaded successfully.");
    
  2. Build and test. The application should initialize and connect to the Policy service.

Next steps