Quickstart: Inicialização da aplicação cliente - Policy SDK (C#)

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

Observação

Qualquer aplicação cliente que utilize o SDK de Política MIP .NET necessita dos passos descritos neste guia de início rápido. Conclua Instalar e configurar o MIP SDK antes de começar.

Pré-requisitos

Se ainda não o fez, certifique-se de:

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

  1. Abra o Visual Studio 2022 ou versão posterior, selecione o menu Ficheiro , Novo, Projeto.

    • Selecione Aplicação de Consola (direcionada para .NET 8 ou posterior).
    • Forneça um nome e localização para o projeto.
  2. Adicione os pacotes NuGet para o SDK de Política MIP e MSAL:

    • No Explorador de Soluções, clique com o botão direito no nó do projeto e selecione Gerir pacotes NuGet....
    • Selecione Navegar, introduza "Microsoft.InformationProtection" na caixa de pesquisa e instale o pacote Microsoft.InformationProtection.Policy .
    • Procure e instale o Microsoft.Identity.Client.

Implementar um delegado de autenticação

  1. Adicionar 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. Adicionar 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 motor de execução

  1. Atualizar Program.cs para criar o MipContext, carregar um PolicyProfile, e adicionar 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. Constrói e testa. A aplicação deve inicializar-se e ligar-se ao serviço de políticas.

Passos seguintes