Inicio rápido: Inicialización de aplicaciones cliente: SDK de directivas (C#)

En este inicio rápido se muestra cómo implementar el patrón de inicialización de cliente usado por el contenedor .NET del SDK de MIP para el SDK de directiva en tiempo de ejecución.

Nota:

Los pasos descritos en este inicio rápido son necesarios para cualquier aplicación cliente que use el SDK de directivas de .NET de MIP. Este inicio rápido debe completarse después de configurar y configurar el SDK de MIP.

Prerrequisitos

Si aún no lo ha hecho, asegúrese de:

Creación de una solución y un proyecto de Visual Studio

  1. Abra Visual Studio 2022 o posterior, seleccione el menú Archivo , Nuevo, Proyecto.

    • Seleccione Aplicación de consola (destinada a .NET 8 o posterior).
    • Proporcione un nombre y una ubicación para el proyecto.
  2. Agregue los paquetes NuGet para el SDK de políticas de MIP y MSAL:

    • En el Explorador de soluciones, haga clic con el botón derecho en el nodo del proyecto y seleccione Administrar paquetes NuGet....
    • Seleccione Examinar, escriba "Microsoft.InformationProtection" en el cuadro de búsqueda e instale el paquete Microsoft.InformationProtection.Policy .
    • Busque e instale Microsoft.Identity.Client.

Implementación de un delegado de autenticación

  1. Agregue una nueva clase denominada 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. Agregue una nueva clase denominada ConsentDelegateImplementation:

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

Inicialización del perfil de directiva y el motor

  1. Actualice Program.cs para crear el MipContext, cargar un PolicyProfile, y agregar un 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);
    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, consentDelegate);
    var profile = MIP.LoadPolicyProfileAsync(profileSettings).GetAwaiter().GetResult();
    
    // Create PolicyEngine
    var engineSettings = new PolicyEngineSettings(
        identity: new Identity("<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. Compilar y probar. La aplicación debe inicializar y conectarse al servicio Policy.

Pasos siguientes