50 lines
1.5 KiB
C#
50 lines
1.5 KiB
C#
using Microsoft.Identity.Client;
|
|
|
|
namespace IAChat.MSGraph
|
|
{
|
|
public class TokenManager
|
|
{
|
|
private readonly IConfiguration _configuration;
|
|
private readonly string _tenantId;
|
|
private readonly string _clientId;
|
|
|
|
public TokenManager(IConfigurationManager configuration)
|
|
{
|
|
_configuration = configuration;
|
|
_tenantId = _configuration.GetSection("AppTenantId").Value;
|
|
_clientId = _configuration.GetSection("AppClientID").Value;
|
|
}
|
|
|
|
|
|
public async Task<string> ObterToken(string userEmail)
|
|
{
|
|
// Configuração do contexto de autenticação
|
|
var app = PublicClientApplicationBuilder
|
|
.Create(_clientId)
|
|
.WithAuthority(AzureCloudInstance.AzurePublic, _tenantId)
|
|
.Build();
|
|
|
|
// Definir os escopos necessários
|
|
string[] scopes = new string[] {
|
|
"https://graph.microsoft.com/.default",
|
|
"User.Read"
|
|
};
|
|
|
|
try
|
|
{
|
|
var result = await app.AcquireTokenInteractive(scopes)
|
|
.WithLoginHint(userEmail)
|
|
.ExecuteAsync();
|
|
|
|
return result.AccessToken;
|
|
}
|
|
catch (Exception ex)
|
|
{
|
|
// Tratamento de erro
|
|
Console.WriteLine($"Erro ao obter token: {ex.Message}");
|
|
return null;
|
|
}
|
|
}
|
|
}
|
|
}
|