using Microsoft.Extensions.Configuration; using Microsoft.Identity.Client; using System.Net.Http.Headers; namespace Shogi.AcceptanceTests.TestSetup { /// /// Acceptance Test fixture for tests which assert features for Microsoft accounts. /// public class MsalTestFixture : IAsyncLifetime, IDisposable { private bool disposedValue; private readonly IConfidentialClientApplication app; public MsalTestFixture() { Configuration = new ConfigurationBuilder() .AddJsonFile("appsettings.json") .AddEnvironmentVariables() .AddUserSecrets() .Build(); var azure = Configuration.GetSection("Auth"); app = ConfidentialClientApplicationBuilder .Create(azure["ClientId"]) .WithTenantId(azure["TenantId"]) .WithClientSecret(azure["SecretValue"]) .Build(); Service = new HttpClient { BaseAddress = new Uri(Configuration["ServiceUrl"], UriKind.Absolute) }; publicApp = PublicClientApplicationBuilder .Create(azure["ClientId"]) .WithTenantId("common") .Build(); } public IConfiguration Configuration { get; private set; } public HttpClient Service { get; } private IPublicClientApplication publicApp; public async Task InitializeAsync() { var scopes = Configuration.GetSection("Auth:Scopes").Get(); var authResult = await app .AcquireTokenForClient(scopes) .ExecuteAsync(); authResult.Should().NotBeNull(); authResult.AccessToken.Should().NotBeNullOrEmpty(); Service.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", authResult.AccessToken); var accounts = await publicApp.GetAccountsAsync(); var password = new System.Security.SecureString(); foreach (var c in "some password") { password.AppendChar(c); } var th = await publicApp .AcquireTokenByIntegratedWindowsAuth(scopes) .ExecuteAsync(); //var thing = await publicApp.AcquireTokenByUsernamePassword(scopes, "Need to create a test email.", password) //.ExecuteAsync(); } protected virtual void Dispose(bool disposing) { if (!disposedValue) { if (disposing) { Service.Dispose(); } disposedValue = true; } } public Task DisposeAsync() { Dispose(true); return Task.CompletedTask; } public void Dispose() { Dispose(disposing: true); GC.SuppressFinalize(this); } } }