Início Rápido: Inicialização do aplicativo cliente – SDK de Políticas (C#)

Este guia de início rápido mostra como implementar o padrão de inicialização do cliente usado pelo wrapper .NET do MIP SDK para o Policy SDK em tempo de execução.

Observação

Qualquer aplicativo cliente que usa o SDK de Política de .NET MIP precisa das etapas neste início rápido. Conclua a configuração e configure o SDK do MIP antes de começar.

Pré-requisitos

Caso ainda não tenha feito isso, certifique-se de:

Criar uma solução e um projeto do Visual Studio

  1. Abra o Visual Studio 2022 ou posterior, selecione o menu Arquivo , Novo, Projeto.

    • Selecione Console App (direcionado ao .NET 8 ou posterior).
    • Forneça um nome e um local para o projeto.
  2. Adicione os pacotes NuGet para o SDK de Política de MIP e o MSAL:

    • Em Gerenciador de Soluções, clique com o botão direito do mouse no nó do projeto e selecione Gerenciar pacotes NuGet....
    • Selecione Procurar, insira "Microsoft.InformationProtection" na caixa de pesquisa e instale o pacote Microsoft.InformationProtection.Policy .
    • Pesquise e instale o Microsoft.Identity.Client.

Implementar um delegado de autenticação

  1. Adicione uma nova classe chamada 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. Adicione uma nova classe chamada ConsentDelegateImplementation:

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

Inicializar o perfil de política e o mecanismo

  1. Atualize Program.cs para criar o MipContext, carregue um PolicyProfilee adicione um 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. Compilar e testar. O aplicativo deve inicializar e conectar-se ao serviço de política.

Próximas Etapas