Nota
O acesso a esta página requer autorização. Pode tentar iniciar sessão ou alterar os diretórios.
O acesso a esta página requer autorização. Pode tentar alterar os diretórios.
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:
- Instalação e configuração do SDK do Microsoft Information Protection (MIP). Conclua os passos seguintes antes deste guia de iniciação rápida.
- Opcionalmente:
Criar uma solução e um projeto do Visual Studio
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.
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
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; } }
Implementar o delegado de consentimento
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
Atualizar
Program.cspara criar oMipContext, carregar umPolicyProfile, e adicionar umPolicyEngine: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.");Constrói e testa. A aplicação deve inicializar-se e ligar-se ao serviço de políticas.