From e233e60e6f2886dc41b10307c1b670e0aaabf499 Mon Sep 17 00:00:00 2001 From: John Luo Date: Wed, 14 Mar 2018 18:24:00 -0700 Subject: [PATCH] Add logging for functional tests --- Identity.sln | 2 +- .../AuthorizationTests.cs | 75 +++-- .../Infrastructure/ServerFactory.cs | 13 +- test/Identity.FunctionalTests/LoginTests.cs | 277 ++++++++++-------- .../ManagementTests.cs | 262 +++++++++-------- .../RegistrationTests.cs | 42 +-- .../CredentialsServerBuilder.cs | 5 +- .../TraditionalWebApplicationTests.cs | 241 +++++++-------- 8 files changed, 505 insertions(+), 412 deletions(-) diff --git a/Identity.sln b/Identity.sln index 4bfe34fd..aa69c507 100644 --- a/Identity.sln +++ b/Identity.sln @@ -965,4 +965,4 @@ Global GlobalSection(ExtensibilityGlobals) = postSolution SolutionGuid = {B3F2A592-CCE0-40C2-8CA4-7B1293DED874} EndGlobalSection -EndGlobal \ No newline at end of file +EndGlobal diff --git a/test/Identity.FunctionalTests/AuthorizationTests.cs b/test/Identity.FunctionalTests/AuthorizationTests.cs index 12be3ec9..9d6875f3 100644 --- a/test/Identity.FunctionalTests/AuthorizationTests.cs +++ b/test/Identity.FunctionalTests/AuthorizationTests.cs @@ -1,14 +1,17 @@ // Copyright (c) .NET Foundation. All rights reserved. // Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. +using System.Net; using System.Threading.Tasks; +using Microsoft.Extensions.Logging.Testing; using Xunit; +using Xunit.Abstractions; namespace Microsoft.AspNetCore.Identity.FunctionalTests { - public class AuthorizationTests : IClassFixture + public class AuthorizationTests : LoggedTest, IClassFixture { - public AuthorizationTests(ServerFactory serverFactory) + public AuthorizationTests(ServerFactory serverFactory, ITestOutputHelper output) : base(output) { ServerFactory = serverFactory; } @@ -37,15 +40,18 @@ namespace Microsoft.AspNetCore.Identity.FunctionalTests [MemberData(nameof(AuthorizedPages))] public async Task AnonymousUserCantAccessAuthorizedPages(string url) { - // Arrange - var client = ServerFactory.CreateDefaultClient(); + using (StartLog(out var loggerFactory, $"{nameof(AnonymousUserCantAccessAuthorizedPages)}_{WebUtility.UrlEncode(url)}")) + { + // Arrange + var client = ServerFactory.CreateDefaultClient(loggerFactory); - // Act - var response = await client.GetAsync(url); + // Act + var response = await client.GetAsync(url); - // Assert - var location = ResponseAssert.IsRedirect(response); - Assert.StartsWith("/Identity/Account/Login?", location.PathAndQuery); + // Assert + var location = ResponseAssert.IsRedirect(response); + Assert.StartsWith("/Identity/Account/Login?", location.PathAndQuery); + } } // The routes commented below are not directly accessible by @@ -74,15 +80,18 @@ namespace Microsoft.AspNetCore.Identity.FunctionalTests [MemberData(nameof(RouteableAuthorizedPages))] public async Task AuthenticatedUserCanAccessAuthorizedPages(string url) { - // Arrange - var client = ServerFactory.CreateDefaultClient(); - await UserStories.RegisterNewUserAsync(client); + using (StartLog(out var loggerFactory, $"{nameof(AuthenticatedUserCanAccessAuthorizedPages)}_{WebUtility.UrlEncode(url)}")) + { + // Arrange + var client = ServerFactory.CreateDefaultClient(loggerFactory); + await UserStories.RegisterNewUserAsync(client); - // Act - var response = await client.GetAsync(url); + // Act + var response = await client.GetAsync(url); - // Assert - await ResponseAssert.IsHtmlDocumentAsync(response); + // Assert + await ResponseAssert.IsHtmlDocumentAsync(response); + } } // The routes commented below are not directly accessible by @@ -107,14 +116,17 @@ namespace Microsoft.AspNetCore.Identity.FunctionalTests [MemberData(nameof(UnauthorizedPages))] public async Task AnonymousUserCanAccessNotAuthorizedPages(string url) { - // Arrange - var client = ServerFactory.CreateDefaultClient(); + using (StartLog(out var loggerFactory, $"{nameof(AnonymousUserCanAccessNotAuthorizedPages)}_{WebUtility.UrlEncode(url)}")) + { + // Arrange + var client = ServerFactory.CreateDefaultClient(loggerFactory); - // Act - var response = await client.GetAsync(url); + // Act + var response = await client.GetAsync(url); - // Assert - await ResponseAssert.IsHtmlDocumentAsync(response); + // Assert + await ResponseAssert.IsHtmlDocumentAsync(response); + } } public static TheoryData UnauthorizedPagesAllowAnonymous => @@ -131,16 +143,19 @@ namespace Microsoft.AspNetCore.Identity.FunctionalTests [MemberData(nameof(UnauthorizedPagesAllowAnonymous))] public async Task AnonymousUserAllowedAccessToPages_WithGlobalAuthorizationFilter(string url) { - // Arrange - var server = ServerFactory.CreateServer(builder => - builder.ConfigureServices(services => services.SetupGlobalAuthorizeFilter())); - var client = ServerFactory.CreateDefaultClient(server); + using (StartLog(out var loggerFactory, $"{nameof(AnonymousUserAllowedAccessToPages_WithGlobalAuthorizationFilter)}_{WebUtility.UrlEncode(url)}")) + { + // Arrange + var server = ServerFactory.CreateServer(loggerFactory, builder => + builder.ConfigureServices(services => services.SetupGlobalAuthorizeFilter())); + var client = ServerFactory.CreateDefaultClient(server); - // Act - var response = await client.GetAsync(url); + // Act + var response = await client.GetAsync(url); - // Assert - await ResponseAssert.IsHtmlDocumentAsync(response); + // Assert + await ResponseAssert.IsHtmlDocumentAsync(response); + } } } } diff --git a/test/Identity.FunctionalTests/Infrastructure/ServerFactory.cs b/test/Identity.FunctionalTests/Infrastructure/ServerFactory.cs index 19f46df6..0991a688 100644 --- a/test/Identity.FunctionalTests/Infrastructure/ServerFactory.cs +++ b/test/Identity.FunctionalTests/Infrastructure/ServerFactory.cs @@ -10,6 +10,7 @@ using Identity.DefaultUI.WebSite; using Microsoft.AspNetCore.Hosting; using Microsoft.AspNetCore.TestHost; using Microsoft.Extensions.DependencyInjection; +using Microsoft.Extensions.Logging; namespace Microsoft.AspNetCore.Identity.FunctionalTests { @@ -19,12 +20,14 @@ namespace Microsoft.AspNetCore.Identity.FunctionalTests private IList _disposableServers = new List(); public TestServer CreateServer( - Action configureBuilder, + ILoggerFactory loggerFactory, + Action configureBuilder, [CallerMemberName] string isolationKey = "") { var builder = WebHostBuilderFactory .CreateFromTypesAssemblyEntryPoint(new string[] { }) .UseSolutionRelativeContentRoot(Path.Combine("test", "WebSites", "Identity.DefaultUI.WebSite")) + .ConfigureServices(collection => collection.AddSingleton(loggerFactory)) .ConfigureServices(sc => sc.SetupTestDatabase(isolationKey) .AddMvc() // Mark the cookie as essential for right now, as Identity uses it on @@ -38,8 +41,8 @@ namespace Microsoft.AspNetCore.Identity.FunctionalTests return server; } - public TestServer CreateDefaultServer([CallerMemberName] string isolationKey = "") => - CreateServer(b => { }, isolationKey); + public TestServer CreateDefaultServer(ILoggerFactory loggerFactory, [CallerMemberName] string isolationKey = "") => + CreateServer(loggerFactory, b => { }, isolationKey); public HttpClient CreateDefaultClient(TestServer server) { @@ -51,8 +54,8 @@ namespace Microsoft.AspNetCore.Identity.FunctionalTests return client; } - public HttpClient CreateDefaultClient() => - CreateDefaultClient(CreateDefaultServer()); + public HttpClient CreateDefaultClient(ILoggerFactory loggerFactory) => + CreateDefaultClient(CreateDefaultServer(loggerFactory)); protected virtual void Dispose(bool disposing) { diff --git a/test/Identity.FunctionalTests/LoginTests.cs b/test/Identity.FunctionalTests/LoginTests.cs index 17cf9495..6bf75b76 100644 --- a/test/Identity.FunctionalTests/LoginTests.cs +++ b/test/Identity.FunctionalTests/LoginTests.cs @@ -5,14 +5,16 @@ using System; using System.Linq; using System.Threading.Tasks; using Identity.DefaultUI.WebSite; +using Microsoft.Extensions.Logging.Testing; using Xunit; +using Xunit.Abstractions; using Xunit.Sdk; namespace Microsoft.AspNetCore.Identity.FunctionalTests { - public class LoginTests : IClassFixture + public class LoginTests : LoggedTest, IClassFixture { - public LoginTests(ServerFactory serverFactory) + public LoginTests(ServerFactory serverFactory, ITestOutputHelper output) : base(output) { ServerFactory = serverFactory; } @@ -22,203 +24,230 @@ namespace Microsoft.AspNetCore.Identity.FunctionalTests [Fact] public async Task CanLogInWithAPreviouslyRegisteredUser() { - // Arrange - var server = ServerFactory.CreateDefaultServer(); - var client = ServerFactory.CreateDefaultClient(server); - var newClient = ServerFactory.CreateDefaultClient(server); + using (StartLog(out var loggerFactory)) + { + // Arrange + var server = ServerFactory.CreateDefaultServer(loggerFactory); + var client = ServerFactory.CreateDefaultClient(server); + var newClient = ServerFactory.CreateDefaultClient(server); - var userName = $"{Guid.NewGuid()}@example.com"; - var password = $"!Test.Password1$"; + var userName = $"{Guid.NewGuid()}@example.com"; + var password = $"!Test.Password1$"; - // Act & Assert - await UserStories.RegisterNewUserAsync(client, userName, password); + // Act & Assert + await UserStories.RegisterNewUserAsync(client, userName, password); - // Use a new client to simulate a new browser session. - await UserStories.LoginExistingUserAsync(newClient, userName, password); + // Use a new client to simulate a new browser session. + await UserStories.LoginExistingUserAsync(newClient, userName, password); + } } [Fact] public async Task CanLogInWithTwoFactorAuthentication() { - // Arrange - var server = ServerFactory.CreateDefaultServer(); - var client = ServerFactory.CreateDefaultClient(server); - var newClient = ServerFactory.CreateDefaultClient(server); + using (StartLog(out var loggerFactory)) + { + // Arrange + var server = ServerFactory.CreateDefaultServer(loggerFactory); + var client = ServerFactory.CreateDefaultClient(server); + var newClient = ServerFactory.CreateDefaultClient(server); - var userName = $"{Guid.NewGuid()}@example.com"; - var password = $"!Test.Password1$"; + var userName = $"{Guid.NewGuid()}@example.com"; + var password = $"!Test.Password1$"; - var loggedIn = await UserStories.RegisterNewUserAsync(client, userName, password); - var showRecoveryCodes = await UserStories.EnableTwoFactorAuthentication(loggedIn); + var loggedIn = await UserStories.RegisterNewUserAsync(client, userName, password); + var showRecoveryCodes = await UserStories.EnableTwoFactorAuthentication(loggedIn); - var twoFactorKey = showRecoveryCodes.Context.AuthenticatorKey; + var twoFactorKey = showRecoveryCodes.Context.AuthenticatorKey; - // Act & Assert - // Use a new client to simulate a new browser session. - await UserStories.LoginExistingUser2FaAsync(newClient, userName, password, twoFactorKey); + // Act & Assert + // Use a new client to simulate a new browser session. + await UserStories.LoginExistingUser2FaAsync(newClient, userName, password, twoFactorKey); + } } [Fact] public async Task CanLogInWithTwoFactorAuthentication_WithGlobalAuthorizeFilter() { - // Arrange - var server = ServerFactory.CreateServer(builder => - builder.ConfigureServices(services => services.SetupGlobalAuthorizeFilter())); - var client = ServerFactory.CreateDefaultClient(server); - var newClient = ServerFactory.CreateDefaultClient(server); + using (StartLog(out var loggerFactory)) + { + // Arrange + var server = ServerFactory.CreateServer(loggerFactory, builder => + builder.ConfigureServices(services => services.SetupGlobalAuthorizeFilter())); + var client = ServerFactory.CreateDefaultClient(server); + var newClient = ServerFactory.CreateDefaultClient(server); - var userName = $"{Guid.NewGuid()}@example.com"; - var password = $"!Test.Password1$"; + var userName = $"{Guid.NewGuid()}@example.com"; + var password = $"!Test.Password1$"; - var loggedIn = await UserStories.RegisterNewUserAsync(client, userName, password); - var showRecoveryCodes = await UserStories.EnableTwoFactorAuthentication(loggedIn); + var loggedIn = await UserStories.RegisterNewUserAsync(client, userName, password); + var showRecoveryCodes = await UserStories.EnableTwoFactorAuthentication(loggedIn); - var twoFactorKey = showRecoveryCodes.Context.AuthenticatorKey; + var twoFactorKey = showRecoveryCodes.Context.AuthenticatorKey; - // Act & Assert - // Use a new client to simulate a new browser session. - await UserStories.LoginExistingUser2FaAsync(newClient, userName, password, twoFactorKey); + // Act & Assert + // Use a new client to simulate a new browser session. + await UserStories.LoginExistingUser2FaAsync(newClient, userName, password, twoFactorKey); + } } [Fact] public async Task CanLogInWithRecoveryCode() { - // Arrange - var server = ServerFactory.CreateDefaultServer(); - var client = ServerFactory.CreateDefaultClient(server); - var newClient = ServerFactory.CreateDefaultClient(server); + using (StartLog(out var loggerFactory)) + { + // Arrange + var server = ServerFactory.CreateDefaultServer(loggerFactory); + var client = ServerFactory.CreateDefaultClient(server); + var newClient = ServerFactory.CreateDefaultClient(server); - var userName = $"{Guid.NewGuid()}@example.com"; - var password = $"!Test.Password1$"; + var userName = $"{Guid.NewGuid()}@example.com"; + var password = $"!Test.Password1$"; - var loggedIn = await UserStories.RegisterNewUserAsync(client, userName, password); - var showRecoveryCodes = await UserStories.EnableTwoFactorAuthentication(loggedIn); + var loggedIn = await UserStories.RegisterNewUserAsync(client, userName, password); + var showRecoveryCodes = await UserStories.EnableTwoFactorAuthentication(loggedIn); - var recoveryCode = showRecoveryCodes.Context.RecoveryCodes.First(); + var recoveryCode = showRecoveryCodes.Context.RecoveryCodes.First(); - // Act & Assert - // Use a new client to simulate a new browser session. - await UserStories.LoginExistingUserRecoveryCodeAsync(newClient, userName, password, recoveryCode); + // Act & Assert + // Use a new client to simulate a new browser session. + await UserStories.LoginExistingUserRecoveryCodeAsync(newClient, userName, password, recoveryCode); + } } [Fact] public async Task CanLogInWithRecoveryCode_WithGlobalAuthorizeFilter() { - // Arrange - var server = ServerFactory.CreateServer(builder => - builder.ConfigureServices(services => services.SetupGlobalAuthorizeFilter())); - var client = ServerFactory.CreateDefaultClient(server); - var newClient = ServerFactory.CreateDefaultClient(server); + using (StartLog(out var loggerFactory)) + { + // Arrange + var server = ServerFactory.CreateServer(loggerFactory, builder => + builder.ConfigureServices(services => services.SetupGlobalAuthorizeFilter())); + var client = ServerFactory.CreateDefaultClient(server); + var newClient = ServerFactory.CreateDefaultClient(server); - var userName = $"{Guid.NewGuid()}@example.com"; - var password = $"!Test.Password1$"; + var userName = $"{Guid.NewGuid()}@example.com"; + var password = $"!Test.Password1$"; - var loggedIn = await UserStories.RegisterNewUserAsync(client, userName, password); - var showRecoveryCodes = await UserStories.EnableTwoFactorAuthentication(loggedIn); + var loggedIn = await UserStories.RegisterNewUserAsync(client, userName, password); + var showRecoveryCodes = await UserStories.EnableTwoFactorAuthentication(loggedIn); - var recoveryCode = showRecoveryCodes.Context.RecoveryCodes.First(); + var recoveryCode = showRecoveryCodes.Context.RecoveryCodes.First(); - // Act & Assert - // Use a new client to simulate a new browser session. - await UserStories.LoginExistingUserRecoveryCodeAsync(newClient, userName, password, recoveryCode); + // Act & Assert + // Use a new client to simulate a new browser session. + await UserStories.LoginExistingUserRecoveryCodeAsync(newClient, userName, password, recoveryCode); + } } [Fact] public async Task CannotLogInWithoutRequiredEmailConfirmation() { - // Arrange - var emailSender = new ContosoEmailSender(); - var server = ServerFactory.CreateServer(builder => + using (StartLog(out var loggerFactory)) { - builder.ConfigureServices(services => services - .SetupTestEmailSender(emailSender) - .SetupEmailRequired()); - }); + // Arrange + var emailSender = new ContosoEmailSender(); + var server = ServerFactory.CreateServer(loggerFactory, builder => + { + builder.ConfigureServices(services => services + .SetupTestEmailSender(emailSender) + .SetupEmailRequired()); + }); - var client = ServerFactory.CreateDefaultClient(server); - var newClient = ServerFactory.CreateDefaultClient(server); + var client = ServerFactory.CreateDefaultClient(server); + var newClient = ServerFactory.CreateDefaultClient(server); - var userName = $"{Guid.NewGuid()}@example.com"; - var password = $"!Test.Password1$"; + var userName = $"{Guid.NewGuid()}@example.com"; + var password = $"!Test.Password1$"; - var loggedIn = await UserStories.RegisterNewUserAsync(client, userName, password); + var loggedIn = await UserStories.RegisterNewUserAsync(client, userName, password); - // Act & Assert - // Use a new client to simulate a new browser session. - await Assert.ThrowsAnyAsync(() => UserStories.LoginExistingUserAsync(newClient, userName, password)); + // Act & Assert + // Use a new client to simulate a new browser session. + await Assert.ThrowsAnyAsync(() => UserStories.LoginExistingUserAsync(newClient, userName, password)); + } } [Fact] public async Task CanLogInAfterConfirmingEmail() { - // Arrange - var emailSender = new ContosoEmailSender(); - var server = ServerFactory.CreateServer(builder => + using (StartLog(out var loggerFactory)) { - builder.ConfigureServices(services => services - .SetupTestEmailSender(emailSender) - .SetupEmailRequired()); - }); + // Arrange + var emailSender = new ContosoEmailSender(); + var server = ServerFactory.CreateServer(loggerFactory, builder => + { + builder.ConfigureServices(services => services + .SetupTestEmailSender(emailSender) + .SetupEmailRequired()); + }); - var client = ServerFactory.CreateDefaultClient(server); - var newClient = ServerFactory.CreateDefaultClient(server); + var client = ServerFactory.CreateDefaultClient(server); + var newClient = ServerFactory.CreateDefaultClient(server); - var userName = $"{Guid.NewGuid()}@example.com"; - var password = $"!Test.Password1$"; + var userName = $"{Guid.NewGuid()}@example.com"; + var password = $"!Test.Password1$"; - var loggedIn = await UserStories.RegisterNewUserAsync(client, userName, password); + var loggedIn = await UserStories.RegisterNewUserAsync(client, userName, password); - // Act & Assert - // Use a new client to simulate a new browser session. - var email = Assert.Single(emailSender.SentEmails); - await UserStories.ConfirmEmailAsync(email, newClient); + // Act & Assert + // Use a new client to simulate a new browser session. + var email = Assert.Single(emailSender.SentEmails); + await UserStories.ConfirmEmailAsync(email, newClient); - await UserStories.LoginExistingUserAsync(newClient, userName, password); + await UserStories.LoginExistingUserAsync(newClient, userName, password); + } } [Fact] public async Task CanLoginWithASocialLoginProvider() { - // Arrange - var server = ServerFactory.CreateServer(builder => - builder.ConfigureServices(services => services.SetupTestThirdPartyLogin())); - var client = ServerFactory.CreateDefaultClient(server); - var newClient = ServerFactory.CreateDefaultClient(server); + using (StartLog(out var loggerFactory)) + { + // Arrange + var server = ServerFactory.CreateServer(loggerFactory, builder => + builder.ConfigureServices(services => services.SetupTestThirdPartyLogin())); + var client = ServerFactory.CreateDefaultClient(server); + var newClient = ServerFactory.CreateDefaultClient(server); - var guid = Guid.NewGuid(); - var userName = $"{guid}"; - var email = $"{guid}@example.com"; + var guid = Guid.NewGuid(); + var userName = $"{guid}"; + var email = $"{guid}@example.com"; - // Act & Assert - await UserStories.RegisterNewUserWithSocialLoginAsync(client, userName, email); - await UserStories.LoginWithSocialLoginAsync(newClient, userName); + // Act & Assert + await UserStories.RegisterNewUserWithSocialLoginAsync(client, userName, email); + await UserStories.LoginWithSocialLoginAsync(newClient, userName); + } } [Fact] public async Task CanLogInAfterResettingThePassword() { - // Arrange - var emailSender = new ContosoEmailSender(); - var server = ServerFactory.CreateServer(b => b.ConfigureServices(s => - s.SetupTestEmailSender(emailSender))); - var client = ServerFactory.CreateDefaultClient(server); - var resetPasswordClient = ServerFactory.CreateDefaultClient(server); - var newClient = ServerFactory.CreateDefaultClient(server); + using (StartLog(out var loggerFactory)) + { + // Arrange + var emailSender = new ContosoEmailSender(); + var server = ServerFactory.CreateServer(loggerFactory, b => b.ConfigureServices(s => + s.SetupTestEmailSender(emailSender))); + var client = ServerFactory.CreateDefaultClient(server); + var resetPasswordClient = ServerFactory.CreateDefaultClient(server); + var newClient = ServerFactory.CreateDefaultClient(server); - var userName = $"{Guid.NewGuid()}@example.com"; - var password = $"!Test.Password1$"; - var newPassword = $"!New.Password1$"; + var userName = $"{Guid.NewGuid()}@example.com"; + var password = $"!Test.Password1$"; + var newPassword = $"!New.Password1$"; - await UserStories.RegisterNewUserAsync(client, userName, password); - var registrationEmail = Assert.Single(emailSender.SentEmails); - await UserStories.ConfirmEmailAsync(registrationEmail, client); + await UserStories.RegisterNewUserAsync(client, userName, password); + var registrationEmail = Assert.Single(emailSender.SentEmails); + await UserStories.ConfirmEmailAsync(registrationEmail, client); - // Act & Assert - await UserStories.ForgotPasswordAsync(resetPasswordClient, userName); - Assert.Equal(2, emailSender.SentEmails.Count); - var email = emailSender.SentEmails[1]; - await UserStories.ResetPasswordAsync(resetPasswordClient, email, userName, newPassword); - await UserStories.LoginExistingUserAsync(newClient, userName, newPassword); + // Act & Assert + await UserStories.ForgotPasswordAsync(resetPasswordClient, userName); + Assert.Equal(2, emailSender.SentEmails.Count); + var email = emailSender.SentEmails[1]; + await UserStories.ResetPasswordAsync(resetPasswordClient, email, userName, newPassword); + await UserStories.LoginExistingUserAsync(newClient, userName, newPassword); + } } } } diff --git a/test/Identity.FunctionalTests/ManagementTests.cs b/test/Identity.FunctionalTests/ManagementTests.cs index 2089048a..10224e56 100644 --- a/test/Identity.FunctionalTests/ManagementTests.cs +++ b/test/Identity.FunctionalTests/ManagementTests.cs @@ -8,13 +8,15 @@ using System.Security.Claims; using System.Threading.Tasks; using Identity.DefaultUI.WebSite; using Microsoft.AspNetCore.TestHost; +using Microsoft.Extensions.Logging.Testing; using Xunit; +using Xunit.Abstractions; namespace Microsoft.AspNetCore.Identity.FunctionalTests { - public class ManagementTests : IClassFixture + public class ManagementTests : LoggedTest, IClassFixture { - public ManagementTests(ServerFactory serverFactory) + public ManagementTests(ServerFactory serverFactory, ITestOutputHelper output) : base(output) { ServerFactory = serverFactory; } @@ -24,192 +26,216 @@ namespace Microsoft.AspNetCore.Identity.FunctionalTests [Fact] public async Task CanEnableTwoFactorAuthentication() { - // Arrange - var client = ServerFactory.CreateDefaultClient(); + using (StartLog(out var loggerFactory)) + { + // Arrange + var client = ServerFactory.CreateDefaultClient(loggerFactory); - var userName = $"{Guid.NewGuid()}@example.com"; - var password = $"!Test.Password1$"; + var userName = $"{Guid.NewGuid()}@example.com"; + var password = $"!Test.Password1$"; - var index = await UserStories.RegisterNewUserAsync(client, userName, password); + var index = await UserStories.RegisterNewUserAsync(client, userName, password); - // Act & Assert - await UserStories.EnableTwoFactorAuthentication(index); + // Act & Assert + await UserStories.EnableTwoFactorAuthentication(index); + } } [Fact] public async Task CanConfirmEmail() { - // Arrange - var emails = new ContosoEmailSender(); - var server = ServerFactory.CreateServer(builder => - builder.ConfigureServices(s => s.SetupTestEmailSender(emails))); - var client = ServerFactory.CreateDefaultClient(server); + using (StartLog(out var loggerFactory)) + { + // Arrange + var emails = new ContosoEmailSender(); + var server = ServerFactory.CreateServer(loggerFactory, builder => + builder.ConfigureServices(s => s.SetupTestEmailSender(emails))); + var client = ServerFactory.CreateDefaultClient(server); - var userName = $"{Guid.NewGuid()}@example.com"; - var password = $"!Test.Password1$"; + var userName = $"{Guid.NewGuid()}@example.com"; + var password = $"!Test.Password1$"; - var index = await UserStories.RegisterNewUserAsync(client, userName, password); - var manageIndex = await UserStories.SendEmailConfirmationLinkAsync(index); + var index = await UserStories.RegisterNewUserAsync(client, userName, password); + var manageIndex = await UserStories.SendEmailConfirmationLinkAsync(index); - // Act & Assert - Assert.Equal(2, emails.SentEmails.Count); - var email = emails.SentEmails[1]; - await UserStories.ConfirmEmailAsync(email, client); + // Act & Assert + Assert.Equal(2, emails.SentEmails.Count); + var email = emails.SentEmails[1]; + await UserStories.ConfirmEmailAsync(email, client); + } } [Fact] public async Task CanChangePassword() { - // Arrange - var principals = new List(); - var server = ServerFactory.CreateServer(builder => - builder.ConfigureTestServices(s => s.SetupGetUserClaimsPrincipal(user => principals.Add(user), IdentityConstants.ApplicationScheme))); + using (StartLog(out var loggerFactory)) + { + // Arrange + var principals = new List(); + var server = ServerFactory.CreateServer(loggerFactory, builder => + builder.ConfigureTestServices(s => s.SetupGetUserClaimsPrincipal(user => principals.Add(user), IdentityConstants.ApplicationScheme))); - var client = ServerFactory.CreateDefaultClient(server); - var newClient = ServerFactory.CreateDefaultClient(server); + var client = ServerFactory.CreateDefaultClient(server); + var newClient = ServerFactory.CreateDefaultClient(server); - var userName = $"{Guid.NewGuid()}@example.com"; - var password = "!Test.Password1"; + var userName = $"{Guid.NewGuid()}@example.com"; + var password = "!Test.Password1"; - var index = await UserStories.RegisterNewUserAsync(client, userName, password); + var index = await UserStories.RegisterNewUserAsync(client, userName, password); - // Act 1 - var changedPassword = await UserStories.ChangePasswordAsync(index, "!Test.Password1", "!Test.Password2"); + // Act 1 + var changedPassword = await UserStories.ChangePasswordAsync(index, "!Test.Password1", "!Test.Password2"); - // Assert 1 - // RefreshSignIn generates a new security stamp claim - AssertClaimsNotEqual(principals[0], principals[1], "AspNet.Identity.SecurityStamp"); + // Assert 1 + // RefreshSignIn generates a new security stamp claim + AssertClaimsNotEqual(principals[0], principals[1], "AspNet.Identity.SecurityStamp"); - // Act 2 - await UserStories.LoginExistingUserAsync(newClient, userName, "!Test.Password2"); + // Act 2 + await UserStories.LoginExistingUserAsync(newClient, userName, "!Test.Password2"); - // Assert 2 - // Signing in again with a different client uses the same security stamp claim - AssertClaimsEqual(principals[1], principals[2], "AspNet.Identity.SecurityStamp"); + // Assert 2 + // Signing in again with a different client uses the same security stamp claim + AssertClaimsEqual(principals[1], principals[2], "AspNet.Identity.SecurityStamp"); + } } [Fact] public async Task CanSetPasswordWithExternalLogin() { - // Arrange - var principals = new List(); - var server = ServerFactory.CreateServer(builder => - builder.ConfigureTestServices(s => s.SetupTestThirdPartyLogin() - .SetupGetUserClaimsPrincipal(user => principals.Add(user), IdentityConstants.ApplicationScheme))); + using (StartLog(out var loggerFactory)) + { + // Arrange + var principals = new List(); + var server = ServerFactory.CreateServer(loggerFactory, builder => + builder.ConfigureTestServices(s => s.SetupTestThirdPartyLogin() + .SetupGetUserClaimsPrincipal(user => principals.Add(user), IdentityConstants.ApplicationScheme))); - var client = ServerFactory.CreateDefaultClient(server); - var newClient = ServerFactory.CreateDefaultClient(server); + var client = ServerFactory.CreateDefaultClient(server); + var newClient = ServerFactory.CreateDefaultClient(server); - var guid = Guid.NewGuid(); - var userName = $"{guid}"; - var email = $"{guid}@example.com"; + var guid = Guid.NewGuid(); + var userName = $"{guid}"; + var email = $"{guid}@example.com"; - // Act 1 - var index = await UserStories.RegisterNewUserWithSocialLoginAsync(client, userName, email); - index = await UserStories.LoginWithSocialLoginAsync(newClient, userName); + // Act 1 + var index = await UserStories.RegisterNewUserWithSocialLoginAsync(client, userName, email); + index = await UserStories.LoginWithSocialLoginAsync(newClient, userName); - // Assert 1 - Assert.NotNull(principals[1].Identities.Single().Claims.Single(c => c.Type == ClaimTypes.AuthenticationMethod).Value); + // Assert 1 + Assert.NotNull(principals[1].Identities.Single().Claims.Single(c => c.Type == ClaimTypes.AuthenticationMethod).Value); - // Act 2 - await UserStories.SetPasswordAsync(index, "!Test.Password2"); + // Act 2 + await UserStories.SetPasswordAsync(index, "!Test.Password2"); - // Assert 2 - // RefreshSignIn uses the same AuthenticationMethod claim value - AssertClaimsEqual(principals[1], principals[2], ClaimTypes.AuthenticationMethod); + // Assert 2 + // RefreshSignIn uses the same AuthenticationMethod claim value + AssertClaimsEqual(principals[1], principals[2], ClaimTypes.AuthenticationMethod); - // Act & Assert 3 - // Can log in with the password set above - await UserStories.LoginExistingUserAsync(ServerFactory.CreateDefaultClient(server), email, "!Test.Password2"); + // Act & Assert 3 + // Can log in with the password set above + await UserStories.LoginExistingUserAsync(ServerFactory.CreateDefaultClient(server), email, "!Test.Password2"); + } } [Fact] public async Task CanRemoveExternalLogin() { - // Arrange - var principals = new List(); - var server = ServerFactory.CreateServer(builder => - builder.ConfigureTestServices(s => s.SetupTestThirdPartyLogin() - .SetupGetUserClaimsPrincipal(user => principals.Add(user), IdentityConstants.ApplicationScheme))); + using (StartLog(out var loggerFactory)) + { + // Arrange + var principals = new List(); + var server = ServerFactory.CreateServer(loggerFactory, builder => + builder.ConfigureTestServices(s => s.SetupTestThirdPartyLogin() + .SetupGetUserClaimsPrincipal(user => principals.Add(user), IdentityConstants.ApplicationScheme))); - var client = ServerFactory.CreateDefaultClient(server); + var client = ServerFactory.CreateDefaultClient(server); - var guid = Guid.NewGuid(); - var userName = $"{guid}"; - var email = $"{guid}@example.com"; + var guid = Guid.NewGuid(); + var userName = $"{guid}"; + var email = $"{guid}@example.com"; - // Act - var index = await UserStories.RegisterNewUserAsync(client, email, "!TestPassword1"); - var linkLogin = await UserStories.LinkExternalLoginAsync(index, email); - await UserStories.RemoveExternalLoginAsync(linkLogin, email); + // Act + var index = await UserStories.RegisterNewUserAsync(client, email, "!TestPassword1"); + var linkLogin = await UserStories.LinkExternalLoginAsync(index, email); + await UserStories.RemoveExternalLoginAsync(linkLogin, email); - // RefreshSignIn generates a new security stamp claim - AssertClaimsNotEqual(principals[0], principals[1], "AspNet.Identity.SecurityStamp"); + // RefreshSignIn generates a new security stamp claim + AssertClaimsNotEqual(principals[0], principals[1], "AspNet.Identity.SecurityStamp"); + } } [Fact] public async Task CanResetAuthenticator() { - // Arrange - var principals = new List(); - var server = ServerFactory.CreateServer(builder => - builder.ConfigureTestServices(s => s.SetupTestThirdPartyLogin() - .SetupGetUserClaimsPrincipal(user => principals.Add(user), IdentityConstants.ApplicationScheme))); + using (StartLog(out var loggerFactory)) + { + // Arrange + var principals = new List(); + var server = ServerFactory.CreateServer(loggerFactory, builder => + builder.ConfigureTestServices(s => s.SetupTestThirdPartyLogin() + .SetupGetUserClaimsPrincipal(user => principals.Add(user), IdentityConstants.ApplicationScheme))); - var client = ServerFactory.CreateDefaultClient(server); - var newClient = ServerFactory.CreateDefaultClient(server); + var client = ServerFactory.CreateDefaultClient(server); + var newClient = ServerFactory.CreateDefaultClient(server); - var userName = $"{Guid.NewGuid()}@example.com"; - var password = $"!Test.Password1$"; + var userName = $"{Guid.NewGuid()}@example.com"; + var password = $"!Test.Password1$"; - // Act - var loggedIn = await UserStories.RegisterNewUserAsync(client, userName, password); - var showRecoveryCodes = await UserStories.EnableTwoFactorAuthentication(loggedIn); - var twoFactorKey = showRecoveryCodes.Context.AuthenticatorKey; + // Act + var loggedIn = await UserStories.RegisterNewUserAsync(client, userName, password); + var showRecoveryCodes = await UserStories.EnableTwoFactorAuthentication(loggedIn); + var twoFactorKey = showRecoveryCodes.Context.AuthenticatorKey; - // Use a new client to simulate a new browser session. - var index = await UserStories.LoginExistingUser2FaAsync(newClient, userName, password, twoFactorKey); - await UserStories.ResetAuthenticator(index); + // Use a new client to simulate a new browser session. + var index = await UserStories.LoginExistingUser2FaAsync(newClient, userName, password, twoFactorKey); + await UserStories.ResetAuthenticator(index); - // RefreshSignIn generates a new security stamp claim - AssertClaimsNotEqual(principals[1], principals[2], "AspNet.Identity.SecurityStamp"); + // RefreshSignIn generates a new security stamp claim + AssertClaimsNotEqual(principals[1], principals[2], "AspNet.Identity.SecurityStamp"); + } } [Fact] public async Task CanDownloadPersonalData() { - // Arrange - var client = ServerFactory.CreateDefaultClient(); + using (StartLog(out var loggerFactory)) + { + // Arrange + var client = ServerFactory.CreateDefaultClient(loggerFactory); - var userName = $"{Guid.NewGuid()}@example.com"; - var password = $"!Test.Password1$"; + var userName = $"{Guid.NewGuid()}@example.com"; + var password = $"!Test.Password1$"; - var index = await UserStories.RegisterNewUserAsync(client, userName, password); + var index = await UserStories.RegisterNewUserAsync(client, userName, password); - // Act & Assert - var jsonData = await UserStories.DownloadPersonalData(index, userName); - Assert.Contains($"\"Id\":\"", jsonData); - Assert.Contains($"\"UserName\":\"{userName}\"", jsonData); - Assert.Contains($"\"Email\":\"{userName}\"", jsonData); - Assert.Contains($"\"EmailConfirmed\":\"False\"", jsonData); - Assert.Contains($"\"PhoneNumber\":\"null\"", jsonData); - Assert.Contains($"\"PhoneNumberConfirmed\":\"False\"", jsonData); - Assert.Contains($"\"TwoFactorEnabled\":\"False\"", jsonData); + // Act & Assert + var jsonData = await UserStories.DownloadPersonalData(index, userName); + Assert.Contains($"\"Id\":\"", jsonData); + Assert.Contains($"\"UserName\":\"{userName}\"", jsonData); + Assert.Contains($"\"Email\":\"{userName}\"", jsonData); + Assert.Contains($"\"EmailConfirmed\":\"False\"", jsonData); + Assert.Contains($"\"PhoneNumber\":\"null\"", jsonData); + Assert.Contains($"\"PhoneNumberConfirmed\":\"False\"", jsonData); + Assert.Contains($"\"TwoFactorEnabled\":\"False\"", jsonData); + } } [Fact] public async Task CanDeleteUser() { - // Arrange - var client = ServerFactory.CreateDefaultClient(); + using (StartLog(out var loggerFactory)) + { + // Arrange + var client = ServerFactory.CreateDefaultClient(loggerFactory); - var userName = $"{Guid.NewGuid()}@example.com"; - var password = $"!Test.Password1$"; + var userName = $"{Guid.NewGuid()}@example.com"; + var password = $"!Test.Password1$"; - var index = await UserStories.RegisterNewUserAsync(client, userName, password); + var index = await UserStories.RegisterNewUserAsync(client, userName, password); - // Act & Assert - await UserStories.DeleteUser(index, password); + // Act & Assert + await UserStories.DeleteUser(index, password); + } } private void AssertClaimsEqual(ClaimsPrincipal expectedPrincipal, ClaimsPrincipal actualPrincipal, string claimType) diff --git a/test/Identity.FunctionalTests/RegistrationTests.cs b/test/Identity.FunctionalTests/RegistrationTests.cs index 36dfa2c2..a040c17a 100644 --- a/test/Identity.FunctionalTests/RegistrationTests.cs +++ b/test/Identity.FunctionalTests/RegistrationTests.cs @@ -3,13 +3,15 @@ using System; using System.Threading.Tasks; +using Microsoft.Extensions.Logging.Testing; using Xunit; +using Xunit.Abstractions; namespace Microsoft.AspNetCore.Identity.FunctionalTests { - public class RegistrationTests : IClassFixture + public class RegistrationTests : LoggedTest, IClassFixture { - public RegistrationTests(ServerFactory serverFactory) + public RegistrationTests(ServerFactory serverFactory, ITestOutputHelper output) : base(output) { ServerFactory = serverFactory; } @@ -19,30 +21,36 @@ namespace Microsoft.AspNetCore.Identity.FunctionalTests [Fact] public async Task CanRegisterAUser() { - // Arrange - var client = ServerFactory.CreateDefaultClient(); + using (StartLog(out var loggerFactory)) + { + // Arrange + var client = ServerFactory.CreateDefaultClient(loggerFactory); - var userName = $"{Guid.NewGuid()}@example.com"; - var password = $"!Test.Password1$"; + var userName = $"{Guid.NewGuid()}@example.com"; + var password = $"!Test.Password1$"; - // Act & Assert - await UserStories.RegisterNewUserAsync(client, userName, password); + // Act & Assert + await UserStories.RegisterNewUserAsync(client, userName, password); + } } [Fact] public async Task CanRegisterWithASocialLoginProvider() { - // Arrange - var server = ServerFactory.CreateServer(builder => - builder.ConfigureServices(services => services.SetupTestThirdPartyLogin())); - var client = ServerFactory.CreateDefaultClient(server); + using (StartLog(out var loggerFactory)) + { + // Arrange + var server = ServerFactory.CreateServer(loggerFactory, builder => + builder.ConfigureServices(services => services.SetupTestThirdPartyLogin())); + var client = ServerFactory.CreateDefaultClient(server); - var guid = Guid.NewGuid(); - var userName = $"{guid}"; - var email = $"{guid}@example.com"; + var guid = Guid.NewGuid(); + var userName = $"{guid}"; + var email = $"{guid}@example.com"; - // Act & Assert - await UserStories.RegisterNewUserWithSocialLoginAsync(client, userName, email); + // Act & Assert + await UserStories.RegisterNewUserWithSocialLoginAsync(client, userName, email); + } } } } diff --git a/test/Service.FunctionalTests/Infrastructure/CredentialsServerBuilder.cs b/test/Service.FunctionalTests/Infrastructure/CredentialsServerBuilder.cs index 520041be..af622ad2 100644 --- a/test/Service.FunctionalTests/Infrastructure/CredentialsServerBuilder.cs +++ b/test/Service.FunctionalTests/Infrastructure/CredentialsServerBuilder.cs @@ -11,11 +11,11 @@ using Microsoft.AspNetCore.Hosting; using Microsoft.AspNetCore.Identity.Service; using Microsoft.AspNetCore.Identity.Service.IntegratedWebClient; using Microsoft.AspNetCore.Mvc; -using Microsoft.AspNetCore.Mvc.Testing; using Microsoft.AspNetCore.TestHost; using Microsoft.EntityFrameworkCore; using Microsoft.Extensions.DependencyInjection; using Microsoft.Extensions.DependencyInjection.Extensions; +using Microsoft.Extensions.Logging; using Microsoft.IdentityModel.Tokens; namespace Microsoft.AspnetCore.Identity.Service.FunctionalTests @@ -24,9 +24,10 @@ namespace Microsoft.AspnetCore.Identity.Service.FunctionalTests { private readonly DelegatingHandler _loopBackHandler = new LoopBackHandler(); - public CredentialsServerBuilder(string[] args = null) + public CredentialsServerBuilder(ILoggerFactory loggerFactory, string[] args = null) { Server = Program.CreateWebHostBuilder(args ?? Array.Empty()) + .ConfigureServices(collection => collection.AddSingleton(loggerFactory)) .UseSolutionRelativeContentRoot(@"./test/WebSites/Identity.OpenIdConnect.WebSite"); } diff --git a/test/Service.FunctionalTests/TraditionalWebApplicationTests.cs b/test/Service.FunctionalTests/TraditionalWebApplicationTests.cs index 0cc77e37..89ea1ca3 100644 --- a/test/Service.FunctionalTests/TraditionalWebApplicationTests.cs +++ b/test/Service.FunctionalTests/TraditionalWebApplicationTests.cs @@ -2,97 +2,105 @@ // Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. using System; -using System.Linq; using System.Collections.Generic; +using System.Linq; using System.Net; +using System.Net.Http; using System.Text.RegularExpressions; using System.Threading.Tasks; using Microsoft.AspNetCore.Mvc.Testing; using Microsoft.AspNetCore.Testing.xunit; +using Microsoft.Extensions.Logging; +using Microsoft.Extensions.Logging.Testing; using Microsoft.Extensions.Primitives; using Microsoft.IdentityModel.Protocols.OpenIdConnect; using Microsoft.Net.Http.Headers; using Xunit; -using System.Net.Http; +using Xunit.Abstractions; namespace Microsoft.AspnetCore.Identity.Service.FunctionalTests { - public class TraditionalWebApplicationTests + public class TraditionalWebApplicationTests : LoggedTest { + public TraditionalWebApplicationTests(ITestOutputHelper output) : base(output) { } + [ConditionalFact(Skip = "https://github.com/aspnet/Identity/issues/1630")] [FrameworkSkipCondition(RuntimeFrameworks.CLR, SkipReason = "https://github.com/aspnet/Identity/issues/1346")] public async Task CanPerform_AuthorizationCode_Flow() { - // Arrange - var clientId = Guid.NewGuid().ToString(); - var resourceId = Guid.NewGuid().ToString(); + using (StartLog(out var loggerFactory, minLogLevel: LogLevel.Debug)) + { + // Arrange + var clientId = Guid.NewGuid().ToString(); + var resourceId = Guid.NewGuid().ToString(); - var appBuilder = new CredentialsServerBuilder() - .EnsureDeveloperCertificate() - .ConfigureReferenceData(data => data - .CreateIntegratedWebClientApplication(clientId) - .CreateResourceApplication(resourceId, "ResourceApplication", "read") - .CreateUser("testUser", "Pa$$w0rd")) - .ConfigureInMemoryEntityFrameworkStorage() - .ConfigureMvcAutomaticSignIn() - .ConfigureOpenIdConnectClient(options => - { - options.ClientId = clientId; - options.ResponseType = OpenIdConnectResponseType.Code; - options.ResponseMode = OpenIdConnectResponseMode.Query; - options.Scope.Add("https://localhost/DFC7191F-FF74-42B9-A292-08FEA80F5B20/v2.0/ResourceApplication/read"); - }) - .ConfigureIntegratedClient(clientId); + var appBuilder = new CredentialsServerBuilder(loggerFactory) + .EnsureDeveloperCertificate() + .ConfigureReferenceData(data => data + .CreateIntegratedWebClientApplication(clientId) + .CreateResourceApplication(resourceId, "ResourceApplication", "read") + .CreateUser("testUser", "Pa$$w0rd")) + .ConfigureInMemoryEntityFrameworkStorage() + .ConfigureMvcAutomaticSignIn() + .ConfigureOpenIdConnectClient(options => + { + options.ClientId = clientId; + options.ResponseType = OpenIdConnectResponseType.Code; + options.ResponseMode = OpenIdConnectResponseMode.Query; + options.Scope.Add("https://localhost/DFC7191F-FF74-42B9-A292-08FEA80F5B20/v2.0/ResourceApplication/read"); + }) + .ConfigureIntegratedClient(clientId); - var client = appBuilder.Build(); + var client = appBuilder.Build(); - // Act & Assert + // Act & Assert - // Navigate to protected resource. - var goToAuthorizeResponse = await client.GetAsync("https://localhost/Home/About"); + // Navigate to protected resource. + var goToAuthorizeResponse = await client.GetAsync("https://localhost/Home/About"); - // Redirected to authorize - var location = ResponseAssert.IsRedirect(goToAuthorizeResponse); - var oidcCookiesComparisonCriteria = CookieComparison.Strict & ~CookieComparison.NameEquals | CookieComparison.NameStartsWith; - ResponseAssert.HasCookie(CreateExpectedSetNonceCookie(), goToAuthorizeResponse, oidcCookiesComparisonCriteria); - ResponseAssert.HasCookie(CreateExpectedSetCorrelationIdCookie(), goToAuthorizeResponse, oidcCookiesComparisonCriteria); - var authorizeParameters = ResponseAssert.LocationHasQueryParameters( - goToAuthorizeResponse, - "state"); + // Redirected to authorize + var location = ResponseAssert.IsRedirect(goToAuthorizeResponse); + var oidcCookiesComparisonCriteria = CookieComparison.Strict & ~CookieComparison.NameEquals | CookieComparison.NameStartsWith; + ResponseAssert.HasCookie(CreateExpectedSetNonceCookie(), goToAuthorizeResponse, oidcCookiesComparisonCriteria); + ResponseAssert.HasCookie(CreateExpectedSetCorrelationIdCookie(), goToAuthorizeResponse, oidcCookiesComparisonCriteria); + var authorizeParameters = ResponseAssert.LocationHasQueryParameters( + goToAuthorizeResponse, + "state"); - // Navigate to authorize - var goToLoginResponse = await client.GetAsync(location); + // Navigate to authorize + var goToLoginResponse = await client.GetAsync(location); - // Redirected to login - location = ResponseAssert.IsRedirect(goToLoginResponse); + // Redirected to login + location = ResponseAssert.IsRedirect(goToLoginResponse); - // Navigate to login - var goToAuthorizeWithCookie = await client.GetAsync(location); + // Navigate to login + var goToAuthorizeWithCookie = await client.GetAsync(location); - // Stamp a login cookie and redirect back to authorize. - location = ResponseAssert.IsRedirect(goToAuthorizeWithCookie); - ResponseAssert.HasCookie(".AspNetCore.Identity.Application", goToAuthorizeWithCookie, CookieComparison.NameEquals); + // Stamp a login cookie and redirect back to authorize. + location = ResponseAssert.IsRedirect(goToAuthorizeWithCookie); + ResponseAssert.HasCookie(".AspNetCore.Identity.Application", goToAuthorizeWithCookie, CookieComparison.NameEquals); - // Navigate to authorize with a login cookie. - var goToSignInOidcCallback = await client.GetAsync(location); + // Navigate to authorize with a login cookie. + var goToSignInOidcCallback = await client.GetAsync(location); - // Stamp an application session cookie and redirect to relying party callback with an authorization code on the query string. - location = ResponseAssert.IsRedirect(goToSignInOidcCallback); - ResponseAssert.HasCookie("Microsoft.AspNetCore.Identity.Service", goToSignInOidcCallback, CookieComparison.NameEquals); - var callBackQueryParameters = ResponseAssert.LocationHasQueryParameters(goToSignInOidcCallback, "code", ("state", authorizeParameters.State)); + // Stamp an application session cookie and redirect to relying party callback with an authorization code on the query string. + location = ResponseAssert.IsRedirect(goToSignInOidcCallback); + ResponseAssert.HasCookie("Microsoft.AspNetCore.Identity.Service", goToSignInOidcCallback, CookieComparison.NameEquals); + var callBackQueryParameters = ResponseAssert.LocationHasQueryParameters(goToSignInOidcCallback, "code", ("state", authorizeParameters.State)); - // Navigate to relying party callback. - var goToProtectedResource = await client.GetAsync(location); + // Navigate to relying party callback. + var goToProtectedResource = await client.GetAsync(location); - // Stamp a session cookie and redirect to the protected resource. - location = ResponseAssert.IsRedirect(goToProtectedResource); - ResponseAssert.HasCookie(".AspNetCore.Cookies", goToProtectedResource, CookieComparison.NameEquals); - ResponseAssert.HasCookie(CreateExpectedSetCorrelationIdCookie(DateTime.Parse("1/1/1970 12:00:00 AM +00:00")), goToProtectedResource, CookieComparison.Delete); - ResponseAssert.HasCookie(CreateExpectedSetNonceCookie(DateTime.Parse("1/1/1970 12:00:00 AM +00:00")), goToProtectedResource, CookieComparison.Delete); + // Stamp a session cookie and redirect to the protected resource. + location = ResponseAssert.IsRedirect(goToProtectedResource); + ResponseAssert.HasCookie(".AspNetCore.Cookies", goToProtectedResource, CookieComparison.NameEquals); + ResponseAssert.HasCookie(CreateExpectedSetCorrelationIdCookie(DateTime.Parse("1/1/1970 12:00:00 AM +00:00")), goToProtectedResource, CookieComparison.Delete); + ResponseAssert.HasCookie(CreateExpectedSetNonceCookie(DateTime.Parse("1/1/1970 12:00:00 AM +00:00")), goToProtectedResource, CookieComparison.Delete); - var protectedResourceResponse = await client.GetAsync(location); - ResponseAssert.IsOK(protectedResourceResponse); - ResponseAssert.IsHtmlDocument(protectedResourceResponse); + var protectedResourceResponse = await client.GetAsync(location); + ResponseAssert.IsOK(protectedResourceResponse); + ResponseAssert.IsHtmlDocument(protectedResourceResponse); + } } private SetCookieHeaderValue CreateExpectedSetCorrelationIdCookie(DateTime expires = default(DateTime)) @@ -121,67 +129,70 @@ namespace Microsoft.AspnetCore.Identity.Service.FunctionalTests [FrameworkSkipCondition(RuntimeFrameworks.CLR, SkipReason = "https://github.com/aspnet/Identity/issues/1346")] public async Task CanPerform_IdToken_Flow() { - // Arrange - var clientId = Guid.NewGuid().ToString(); - var resourceId = Guid.NewGuid().ToString(); - - var appBuilder = new CredentialsServerBuilder() - .EnsureDeveloperCertificate() - .ConfigureReferenceData(data => data - .CreateIntegratedWebClientApplication(clientId) - .CreateUser("testUser", "Pa$$w0rd")) - .ConfigureInMemoryEntityFrameworkStorage() - .ConfigureMvcAutomaticSignIn() - .ConfigureOpenIdConnectClient(options => - { - options.ClientId = clientId; - }) - .ConfigureIntegratedClient(clientId); - - var client = appBuilder.Build(); - - // Act - var goToAuthorizeResponse = await client.GetAsync("https://localhost/Home/About"); - - // Assert - Assert.Equal(HttpStatusCode.Redirect, goToAuthorizeResponse.StatusCode); - - // Act - var goToLoginResponse = await client.GetAsync(goToAuthorizeResponse.Headers.Location); - - // Assert - Assert.Equal(HttpStatusCode.Redirect, goToLoginResponse.StatusCode); - - // Act - var goToAuthorizeWithCookie = await client.GetAsync(goToLoginResponse.Headers.Location); - - // Assert - Assert.Equal(HttpStatusCode.Redirect, goToAuthorizeWithCookie.StatusCode); - - // Act - var goToSignInOidcCallback = await client.GetAsync(goToAuthorizeWithCookie.Headers.Location); - - // Assert - Assert.Equal(HttpStatusCode.OK, goToSignInOidcCallback.StatusCode); - ResponseAssert.IsHtmlDocument(goToSignInOidcCallback); - var form = GetForm(await goToSignInOidcCallback.Content.ReadAsStringAsync()); - var formRequest = new HttpRequestMessage(new HttpMethod(form.Method), form.Action) + using (StartLog(out var loggerFactory, minLogLevel: LogLevel.Debug)) { - Content = new FormUrlEncodedContent(form.Values) - }; + // Arrange + var clientId = Guid.NewGuid().ToString(); + var resourceId = Guid.NewGuid().ToString(); - // Act - var goToProtectedResource = await client.SendAsync(formRequest); + var appBuilder = new CredentialsServerBuilder(loggerFactory) + .EnsureDeveloperCertificate() + .ConfigureReferenceData(data => data + .CreateIntegratedWebClientApplication(clientId) + .CreateUser("testUser", "Pa$$w0rd")) + .ConfigureInMemoryEntityFrameworkStorage() + .ConfigureMvcAutomaticSignIn() + .ConfigureOpenIdConnectClient(options => + { + options.ClientId = clientId; + }) + .ConfigureIntegratedClient(clientId); - // Assert - Assert.Equal(HttpStatusCode.Redirect, goToProtectedResource.StatusCode); + var client = appBuilder.Build(); - // Act - var protectedResourceResponse = await client.GetAsync(goToProtectedResource.Headers.Location); + // Act + var goToAuthorizeResponse = await client.GetAsync("https://localhost/Home/About"); - // Assert - Assert.Equal(HttpStatusCode.OK, protectedResourceResponse.StatusCode); - ResponseAssert.IsHtmlDocument(protectedResourceResponse); + // Assert + Assert.Equal(HttpStatusCode.Redirect, goToAuthorizeResponse.StatusCode); + + // Act + var goToLoginResponse = await client.GetAsync(goToAuthorizeResponse.Headers.Location); + + // Assert + Assert.Equal(HttpStatusCode.Redirect, goToLoginResponse.StatusCode); + + // Act + var goToAuthorizeWithCookie = await client.GetAsync(goToLoginResponse.Headers.Location); + + // Assert + Assert.Equal(HttpStatusCode.Redirect, goToAuthorizeWithCookie.StatusCode); + + // Act + var goToSignInOidcCallback = await client.GetAsync(goToAuthorizeWithCookie.Headers.Location); + + // Assert + Assert.Equal(HttpStatusCode.OK, goToSignInOidcCallback.StatusCode); + ResponseAssert.IsHtmlDocument(goToSignInOidcCallback); + var form = GetForm(await goToSignInOidcCallback.Content.ReadAsStringAsync()); + var formRequest = new HttpRequestMessage(new HttpMethod(form.Method), form.Action) + { + Content = new FormUrlEncodedContent(form.Values) + }; + + // Act + var goToProtectedResource = await client.SendAsync(formRequest); + + // Assert + Assert.Equal(HttpStatusCode.Redirect, goToProtectedResource.StatusCode); + + // Act + var protectedResourceResponse = await client.GetAsync(goToProtectedResource.Headers.Location); + + // Assert + Assert.Equal(HttpStatusCode.OK, protectedResourceResponse.StatusCode); + ResponseAssert.IsHtmlDocument(protectedResourceResponse); + } }