[Fixes #1742, #1722, #1706, #1725, #1688] Fixes multiple issues

* Update test infrastructure to use the latest bits.
* Add tests for different types of users.
* Logout must redirect instead of just rendering
  the page so that the identity in the request gets
  properly updated
* Remove IUserFactory and IdentityUserFactory.
* Added tests to verify that the default UI endpoints are not accessible
  when the default UI is not enabled.
* Update the user name at the same time when the email is updated.
This commit is contained in:
Javier Calvarro Nelson 2018-04-10 18:26:13 -07:00
parent a273e349ee
commit f51af820a5
68 changed files with 1596 additions and 1172 deletions

View File

@ -1,6 +1,6 @@
{ {
"ConnectionStrings": { "ConnectionStrings": {
"DefaultConnection": "Server=(localdb)\\mssqllocaldb;Database=aspnet-IdentitySample.DefaultUI-d97faff4-1cfe-4c5d-b031-aa23aeb03a5e;Trusted_Connection=True;MultipleActiveResultSets=true" "DefaultConnection": "Server=(localdb)\\mssqllocaldb;Database=aspnet-IdentitySample.DefaultUI-47781151-7d38-4b7b-8fe4-9a8b299f124f;Trusted_Connection=True;MultipleActiveResultSets=true"
}, },
"Logging": { "Logging": {
"IncludeScopes": false, "IncludeScopes": false,

View File

@ -4,6 +4,7 @@
using System; using System;
using System.ComponentModel.DataAnnotations; using System.ComponentModel.DataAnnotations;
using System.Security.Claims; using System.Security.Claims;
using System.Threading;
using System.Threading.Tasks; using System.Threading.Tasks;
using Microsoft.AspNetCore.Mvc; using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.RazorPages; using Microsoft.AspNetCore.Mvc.RazorPages;
@ -44,18 +45,20 @@ namespace Microsoft.AspNetCore.Identity.UI.Pages.Account.Internal
{ {
private readonly SignInManager<TUser> _signInManager; private readonly SignInManager<TUser> _signInManager;
private readonly UserManager<TUser> _userManager; private readonly UserManager<TUser> _userManager;
private readonly IUserFactory<TUser> _userFactory; private readonly IUserStore<TUser> _userStore;
private readonly IUserEmailStore<TUser> _emailStore;
private readonly ILogger<ExternalLoginModel> _logger; private readonly ILogger<ExternalLoginModel> _logger;
public ExternalLoginModel( public ExternalLoginModel(
SignInManager<TUser> signInManager, SignInManager<TUser> signInManager,
UserManager<TUser> userManager, UserManager<TUser> userManager,
IUserFactory<TUser> userFactory, IUserStore<TUser> userStore,
ILogger<ExternalLoginModel> logger) ILogger<ExternalLoginModel> logger)
{ {
_signInManager = signInManager; _signInManager = signInManager;
_userManager = userManager; _userManager = userManager;
_userFactory = userFactory; _userStore = userStore;
_emailStore = GetEmailStore();
_logger = logger; _logger = logger;
} }
@ -127,7 +130,11 @@ namespace Microsoft.AspNetCore.Identity.UI.Pages.Account.Internal
if (ModelState.IsValid) if (ModelState.IsValid)
{ {
var user = _userFactory.CreateUser(email: Input.Email, userName: Input.Email); var user = CreateUser();
await _userStore.SetUserNameAsync(user, Input.Email, CancellationToken.None);
await _emailStore.SetEmailAsync(user, Input.Email, CancellationToken.None);
var result = await _userManager.CreateAsync(user); var result = await _userManager.CreateAsync(user);
if (result.Succeeded) if (result.Succeeded)
{ {
@ -149,5 +156,28 @@ namespace Microsoft.AspNetCore.Identity.UI.Pages.Account.Internal
ReturnUrl = returnUrl; ReturnUrl = returnUrl;
return Page(); return Page();
} }
private TUser CreateUser()
{
try
{
return Activator.CreateInstance<TUser>();
}
catch
{
throw new InvalidOperationException($"Can't create an instance of '{nameof(TUser)}'. " +
$"Ensure that '{nameof(TUser)}' is not an abstract class and has a parameterless constructor, or alternatively " +
$"override the external login page in /Areas/Identity/Pages/Account/ExternalLogin.cshtml");
}
}
private IUserEmailStore<TUser> GetEmailStore()
{
if (!_userManager.SupportsUserEmail)
{
throw new NotSupportedException("The default UI requires a user store with email support.");
}
return (IUserEmailStore<TUser>)_userStore;
}
} }
} }

View File

@ -42,7 +42,9 @@ namespace Microsoft.AspNetCore.Identity.UI.Pages.Account.Internal
} }
else else
{ {
return Page(); // This needs to be a redirect so that the browser performs a new
// request and the identity for the user gets updated.
return RedirectToPage();
} }
} }
} }

View File

@ -35,7 +35,7 @@
<input asp-for="Input.PhoneNumber" class="form-control" /> <input asp-for="Input.PhoneNumber" class="form-control" />
<span asp-validation-for="Input.PhoneNumber" class="text-danger"></span> <span asp-validation-for="Input.PhoneNumber" class="text-danger"></span>
</div> </div>
<button type="submit" class="btn btn-default">Save</button> <button id="update-profile-button" type="submit" class="btn btn-default">Save</button>
</form> </form>
</div> </div>
</div> </div>

View File

@ -104,6 +104,15 @@ namespace Microsoft.AspNetCore.Identity.UI.Pages.Account.Manage.Internal
var userId = await _userManager.GetUserIdAsync(user); var userId = await _userManager.GetUserIdAsync(user);
throw new InvalidOperationException($"Unexpected error occurred setting email for user with ID '{userId}'."); throw new InvalidOperationException($"Unexpected error occurred setting email for user with ID '{userId}'.");
} }
// In our UI email and user name are one and the same, so when we update the email
// we need to update the user name.
var setUserNameResult = await _userManager.SetUserNameAsync(user, Input.Email);
if (!setUserNameResult.Succeeded)
{
var userId = await _userManager.GetUserIdAsync(user);
throw new InvalidOperationException($"Unexpected error occurred setting name for user with ID '{userId}'.");
}
} }
var phoneNumber = await _userManager.GetPhoneNumberAsync(user); var phoneNumber = await _userManager.GetPhoneNumberAsync(user);

View File

@ -4,6 +4,7 @@
using System; using System;
using System.ComponentModel.DataAnnotations; using System.ComponentModel.DataAnnotations;
using System.Text.Encodings.Web; using System.Text.Encodings.Web;
using System.Threading;
using System.Threading.Tasks; using System.Threading.Tasks;
using Microsoft.AspNetCore.Authorization; using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Identity.UI.Services; using Microsoft.AspNetCore.Identity.UI.Services;
@ -49,21 +50,23 @@ namespace Microsoft.AspNetCore.Identity.UI.Pages.Account.Internal
internal class RegisterModel<TUser> : RegisterModel where TUser : class internal class RegisterModel<TUser> : RegisterModel where TUser : class
{ {
private readonly SignInManager<TUser> _signInManager; private readonly SignInManager<TUser> _signInManager;
private readonly IUserFactory<TUser> _userFactory;
private readonly UserManager<TUser> _userManager; private readonly UserManager<TUser> _userManager;
private readonly IUserStore<TUser> _userStore;
private readonly IUserEmailStore<TUser> _emailStore;
private readonly ILogger<LoginModel> _logger; private readonly ILogger<LoginModel> _logger;
private readonly IEmailSender _emailSender; private readonly IEmailSender _emailSender;
public RegisterModel( public RegisterModel(
UserManager<TUser> userManager, UserManager<TUser> userManager,
IUserStore<TUser> userStore,
SignInManager<TUser> signInManager, SignInManager<TUser> signInManager,
IUserFactory<TUser> userFactory,
ILogger<LoginModel> logger, ILogger<LoginModel> logger,
IEmailSender emailSender) IEmailSender emailSender)
{ {
_userManager = userManager; _userManager = userManager;
_userStore = userStore;
_emailStore = GetEmailStore();
_signInManager = signInManager; _signInManager = signInManager;
_userFactory = userFactory;
_logger = logger; _logger = logger;
_emailSender = emailSender; _emailSender = emailSender;
} }
@ -78,8 +81,12 @@ namespace Microsoft.AspNetCore.Identity.UI.Pages.Account.Internal
returnUrl = returnUrl ?? Url.Content("~/"); returnUrl = returnUrl ?? Url.Content("~/");
if (ModelState.IsValid) if (ModelState.IsValid)
{ {
var user = _userFactory.CreateUser(email: Input.Email, userName: Input.Email); var user = CreateUser();
await _userStore.SetUserNameAsync(user, Input.Email, CancellationToken.None);
await _emailStore.SetEmailAsync(user, Input.Email, CancellationToken.None);
var result = await _userManager.CreateAsync(user, Input.Password); var result = await _userManager.CreateAsync(user, Input.Password);
if (result.Succeeded) if (result.Succeeded)
{ {
_logger.LogInformation("User created a new account with password."); _logger.LogInformation("User created a new account with password.");
@ -107,5 +114,28 @@ namespace Microsoft.AspNetCore.Identity.UI.Pages.Account.Internal
// If we got this far, something failed, redisplay form // If we got this far, something failed, redisplay form
return Page(); return Page();
} }
private TUser CreateUser()
{
try
{
return Activator.CreateInstance<TUser>();
}
catch
{
throw new InvalidOperationException($"Can't create an instance of '{nameof(TUser)}'. " +
$"Ensure that '{nameof(TUser)}' is not an abstract class and has a parameterless constructor, or alternatively " +
$"override the register page in /Areas/Identity/Pages/Account/Register.cshtml");
}
}
private IUserEmailStore<TUser> GetEmailStore()
{
if (!_userManager.SupportsUserEmail)
{
throw new NotSupportedException("The default UI requires a user store with email support.");
}
return (IUserEmailStore<TUser>)_userStore;
}
} }
} }

View File

@ -5,7 +5,7 @@ using System.Threading.Tasks;
namespace Microsoft.AspNetCore.Identity.UI.Services namespace Microsoft.AspNetCore.Identity.UI.Services
{ {
public class EmailSender : IEmailSender internal class EmailSender : IEmailSender
{ {
public Task SendEmailAsync(string email, string subject, string htmlMessage) public Task SendEmailAsync(string email, string subject, string htmlMessage)
{ {

View File

@ -1,20 +0,0 @@
// 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.
namespace Microsoft.AspNetCore.Identity.UI
{
/// <summary>
/// Provides an abstraction for instantiating the given user type.
/// </summary>
/// <typeparam name="TUser">The type of user.</typeparam>
public interface IUserFactory<TUser> where TUser : class
{
/// <summary>
/// Creates an instance of a user and assigns the provided values.
/// </summary>
/// <param name="email">Email address</param>
/// <param name="userName">User name</param>
/// <returns>Created user</returns>
TUser CreateUser(string email, string userName);
}
}

View File

@ -37,13 +37,6 @@ namespace Microsoft.AspNetCore.Identity
.MakeGenericType(builder.UserType)); .MakeGenericType(builder.UserType));
builder.Services.TryAddTransient<IEmailSender, EmailSender>(); builder.Services.TryAddTransient<IEmailSender, EmailSender>();
if (TryGetIdentityUserType(builder.UserType, out var primaryKeyType))
{
var userFactoryType = typeof(IUserFactory<>).MakeGenericType(builder.UserType);
var defaultUserFactoryType = typeof(UserFactory<,>).MakeGenericType(builder.UserType, primaryKeyType);
builder.Services.TryAddSingleton(userFactoryType, defaultUserFactoryType);
}
return builder; return builder;
} }
@ -71,24 +64,5 @@ namespace Microsoft.AspNetCore.Identity
} }
}); });
} }
private static bool TryGetIdentityUserType(Type userType, out Type primaryKeyType)
{
primaryKeyType = null;
var baseType = userType.BaseType;
while (baseType != null)
{
if (baseType.IsGenericType &&
baseType.GetGenericTypeDefinition() == typeof(IdentityUser<>))
{
primaryKeyType = baseType.GetGenericArguments()[0];
return true;
}
baseType = baseType.BaseType;
}
return false;
}
} }
} }

View File

@ -1,17 +0,0 @@
// 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;
namespace Microsoft.AspNetCore.Identity.UI
{
internal class UserFactory<TUser, TKey> : IUserFactory<TUser>
where TUser : IdentityUser<TKey>, new()
where TKey : IEquatable<TKey>
{
public TUser CreateUser(string email, string userName)
{
return new TUser() { Email = email, UserName = userName };
}
}
}

View File

@ -0,0 +1,16 @@
// 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 Identity.DefaultUI.WebSite;
using Identity.DefaultUI.WebSite.Data;
using Xunit.Abstractions;
namespace Microsoft.AspNetCore.Identity.FunctionalTests.IdentityUserTests
{
public class ApplicationUserAuthorizationTests : AuthorizationTests<ApplicationUserStartup,ApplicationDbContext>
{
public ApplicationUserAuthorizationTests(ServerFactory<ApplicationUserStartup, ApplicationDbContext> serverFactory) : base(serverFactory)
{
}
}
}

View File

@ -0,0 +1,16 @@
// 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 Identity.DefaultUI.WebSite;
using Identity.DefaultUI.WebSite.Data;
using Xunit.Abstractions;
namespace Microsoft.AspNetCore.Identity.FunctionalTests.IdentityUserTests
{
public class ApplicationUserLoginTests : LoginTests<ApplicationUserStartup,ApplicationDbContext>
{
public ApplicationUserLoginTests(ServerFactory<ApplicationUserStartup, ApplicationDbContext> serverFactory) : base(serverFactory)
{
}
}
}

View File

@ -0,0 +1,16 @@
// 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 Identity.DefaultUI.WebSite;
using Identity.DefaultUI.WebSite.Data;
using Xunit.Abstractions;
namespace Microsoft.AspNetCore.Identity.FunctionalTests.IdentityUserTests
{
public class ApplicationUserManagementTests : ManagementTests<ApplicationUserStartup, ApplicationDbContext>
{
public ApplicationUserManagementTests(ServerFactory<ApplicationUserStartup, ApplicationDbContext> serverFactory) : base(serverFactory)
{
}
}
}

View File

@ -0,0 +1,16 @@
// 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 Identity.DefaultUI.WebSite;
using Identity.DefaultUI.WebSite.Data;
using Xunit.Abstractions;
namespace Microsoft.AspNetCore.Identity.FunctionalTests.IdentityUserTests
{
public class ApplicationUserRegistrationTests : RegistrationTests<ApplicationUserStartup,ApplicationDbContext>
{
public ApplicationUserRegistrationTests(ServerFactory<ApplicationUserStartup,ApplicationDbContext> serverFactory) : base(serverFactory)
{
}
}
}

View File

@ -3,20 +3,24 @@
using System.Net; using System.Net;
using System.Threading.Tasks; using System.Threading.Tasks;
using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Logging.Testing; using Microsoft.Extensions.Logging.Testing;
using Xunit; using Xunit;
using Xunit.Abstractions; using Xunit.Abstractions;
namespace Microsoft.AspNetCore.Identity.FunctionalTests namespace Microsoft.AspNetCore.Identity.FunctionalTests
{ {
public class AuthorizationTests : LoggedTest, IClassFixture<ServerFactory> public abstract class AuthorizationTests<TStartup, TContext> : IClassFixture<ServerFactory<TStartup, TContext>>
where TStartup : class
where TContext : DbContext
{ {
public AuthorizationTests(ServerFactory serverFactory, ITestOutputHelper output) : base(output) public AuthorizationTests(ServerFactory<TStartup, TContext> serverFactory)
{ {
ServerFactory = serverFactory; ServerFactory = serverFactory;
} }
public ServerFactory ServerFactory { get; } public ServerFactory<TStartup, TContext> ServerFactory { get; }
public static TheoryData<string> AuthorizedPages => public static TheoryData<string> AuthorizedPages =>
new TheoryData<string> new TheoryData<string>
@ -40,18 +44,16 @@ namespace Microsoft.AspNetCore.Identity.FunctionalTests
[MemberData(nameof(AuthorizedPages))] [MemberData(nameof(AuthorizedPages))]
public async Task AnonymousUserCantAccessAuthorizedPages(string url) public async Task AnonymousUserCantAccessAuthorizedPages(string url)
{ {
using (StartLog(out var loggerFactory, $"{nameof(AnonymousUserCantAccessAuthorizedPages)}_{WebUtility.UrlEncode(url)}")) // Arrange
{ var client = ServerFactory
// Arrange .CreateClient();
var client = ServerFactory.CreateDefaultClient(loggerFactory);
// Act // Act
var response = await client.GetAsync(url); var response = await client.GetAsync(url);
// Assert // Assert
var location = ResponseAssert.IsRedirect(response); var location = ResponseAssert.IsRedirect(response);
Assert.StartsWith("/Identity/Account/Login?", location.PathAndQuery); Assert.StartsWith("/Identity/Account/Login?", location.PathAndQuery);
}
} }
// The routes commented below are not directly accessible by // The routes commented below are not directly accessible by
@ -79,18 +81,17 @@ namespace Microsoft.AspNetCore.Identity.FunctionalTests
[MemberData(nameof(RouteableAuthorizedPages))] [MemberData(nameof(RouteableAuthorizedPages))]
public async Task AuthenticatedUserCanAccessAuthorizedPages(string url) public async Task AuthenticatedUserCanAccessAuthorizedPages(string url)
{ {
using (StartLog(out var loggerFactory, $"{nameof(AuthenticatedUserCanAccessAuthorizedPages)}_{WebUtility.UrlEncode(url)}")) // Arrange
{ var client = ServerFactory
// Arrange .CreateClient();
var client = ServerFactory.CreateDefaultClient(loggerFactory);
await UserStories.RegisterNewUserAsync(client);
// Act await UserStories.RegisterNewUserAsync(client);
var response = await client.GetAsync(url);
// Assert // Act
await ResponseAssert.IsHtmlDocumentAsync(response); var response = await client.GetAsync(url);
}
// Assert
await ResponseAssert.IsHtmlDocumentAsync(response);
} }
// The routes commented below are not directly accessible by // The routes commented below are not directly accessible by
@ -115,17 +116,15 @@ namespace Microsoft.AspNetCore.Identity.FunctionalTests
[MemberData(nameof(UnauthorizedPages))] [MemberData(nameof(UnauthorizedPages))]
public async Task AnonymousUserCanAccessNotAuthorizedPages(string url) public async Task AnonymousUserCanAccessNotAuthorizedPages(string url)
{ {
using (StartLog(out var loggerFactory, $"{nameof(AnonymousUserCanAccessNotAuthorizedPages)}_{WebUtility.UrlEncode(url)}")) // Arrange
{ var client = ServerFactory
// Arrange .CreateClient();
var client = ServerFactory.CreateDefaultClient(loggerFactory);
// Act // Act
var response = await client.GetAsync(url); var response = await client.GetAsync(url);
// Assert // Assert
await ResponseAssert.IsHtmlDocumentAsync(response); await ResponseAssert.IsHtmlDocumentAsync(response);
}
} }
public static TheoryData<string> UnauthorizedPagesAllowAnonymous => public static TheoryData<string> UnauthorizedPagesAllowAnonymous =>
@ -142,19 +141,18 @@ namespace Microsoft.AspNetCore.Identity.FunctionalTests
[MemberData(nameof(UnauthorizedPagesAllowAnonymous))] [MemberData(nameof(UnauthorizedPagesAllowAnonymous))]
public async Task AnonymousUserAllowedAccessToPages_WithGlobalAuthorizationFilter(string url) public async Task AnonymousUserAllowedAccessToPages_WithGlobalAuthorizationFilter(string url)
{ {
using (StartLog(out var loggerFactory, $"{nameof(AnonymousUserAllowedAccessToPages_WithGlobalAuthorizationFilter)}_{WebUtility.UrlEncode(url)}")) // Arrange
{ void TestServicesConfiguration(IServiceCollection services) =>
// Arrange services.SetupGlobalAuthorizeFilter();
var server = ServerFactory.CreateServer(loggerFactory, builder =>
builder.ConfigureServices(services => services.SetupGlobalAuthorizeFilter()));
var client = ServerFactory.CreateDefaultClient(server);
// Act var client = ServerFactory.WithWebHostBuilder(whb => whb.ConfigureServices(TestServicesConfiguration))
var response = await client.GetAsync(url); .CreateClient();
// Assert // Act
await ResponseAssert.IsHtmlDocumentAsync(response); var response = await client.GetAsync(url);
}
// Assert
await ResponseAssert.IsHtmlDocumentAsync(response);
} }
} }
} }

View File

@ -53,5 +53,10 @@ namespace Microsoft.AspNetCore.Identity.FunctionalTests
} }
} }
} }
internal static void IsOK(HttpResponseMessage download)
{
Assert.Equal(HttpStatusCode.OK, download.StatusCode);
}
} }
} }

View File

@ -0,0 +1,16 @@
// 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 Identity.DefaultUI.WebSite;
using Microsoft.AspNetCore.Identity.EntityFrameworkCore;
using Xunit.Abstractions;
namespace Microsoft.AspNetCore.Identity.FunctionalTests.IdentityUserTests
{
public class IdentityUserAuthorizationTests : AuthorizationTests<Startup, IdentityDbContext>
{
public IdentityUserAuthorizationTests(ServerFactory<Startup, IdentityDbContext> serverFactory) : base(serverFactory)
{
}
}
}

View File

@ -0,0 +1,16 @@
// 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 Identity.DefaultUI.WebSite;
using Microsoft.AspNetCore.Identity.EntityFrameworkCore;
using Xunit.Abstractions;
namespace Microsoft.AspNetCore.Identity.FunctionalTests.IdentityUserTests
{
public class IdentityUserLoginTests : LoginTests<Startup, IdentityDbContext>
{
public IdentityUserLoginTests(ServerFactory<Startup, IdentityDbContext> serverFactory) : base(serverFactory)
{
}
}
}

View File

@ -0,0 +1,16 @@
// 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 Identity.DefaultUI.WebSite;
using Microsoft.AspNetCore.Identity.EntityFrameworkCore;
using Xunit.Abstractions;
namespace Microsoft.AspNetCore.Identity.FunctionalTests.IdentityUserTests
{
public class IdentityUserManagementTests : ManagementTests<Startup, IdentityDbContext>
{
public IdentityUserManagementTests(ServerFactory<Startup, IdentityDbContext> serverFactory) : base(serverFactory)
{
}
}
}

View File

@ -0,0 +1,16 @@
// 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 Identity.DefaultUI.WebSite;
using Microsoft.AspNetCore.Identity.EntityFrameworkCore;
using Xunit.Abstractions;
namespace Microsoft.AspNetCore.Identity.FunctionalTests.IdentityUserTests
{
public class IdentityUserRegistrationTests : RegistrationTests<Startup, IdentityDbContext>
{
public IdentityUserRegistrationTests(ServerFactory<Startup, IdentityDbContext> serverFactory) : base(serverFactory)
{
}
}
}

View File

@ -1,38 +0,0 @@
// 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.Net.Http;
using System.Threading;
using System.Threading.Tasks;
namespace Microsoft.AspNetCore.Identity.FunctionalTests
{
public class CookieContainerHandler : DelegatingHandler
{
public CookieContainerHandler(HttpMessageHandler innerHandler)
: base(innerHandler)
{
}
public CookieContainer Container { get; } = new CookieContainer();
protected override async Task<HttpResponseMessage> SendAsync(HttpRequestMessage request, CancellationToken cancellationToken)
{
var cookieHeader = Container.GetCookieHeader(request.RequestUri);
request.Headers.Add("Cookie", cookieHeader);
var response = await base.SendAsync(request, cancellationToken);
if (response.Headers.TryGetValues("Set-Cookie", out var setCookieHeaders))
{
foreach (var header in setCookieHeaders)
{
Container.SetCookies(response.RequestMessage.RequestUri, header);
}
}
return response;
}
}
}

View File

@ -17,8 +17,8 @@ namespace Microsoft.AspNetCore.Identity.FunctionalTests
{ {
public static class FunctionalTestsServiceCollectionExtensions public static class FunctionalTestsServiceCollectionExtensions
{ {
public static IServiceCollection SetupTestDatabase(this IServiceCollection services, string databaseName) => public static IServiceCollection SetupTestDatabase<TContext>(this IServiceCollection services, string databaseName) where TContext : DbContext =>
services.AddDbContext<IdentityDbContext>(options => services.AddDbContext<TContext>(options =>
options.UseInMemoryDatabase(databaseName, memoryOptions => { })); options.UseInMemoryDatabase(databaseName, memoryOptions => { }));
public static IServiceCollection SetupTestThirdPartyLogin(this IServiceCollection services) => public static IServiceCollection SetupTestThirdPartyLogin(this IServiceCollection services) =>

View File

@ -2,81 +2,33 @@
// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. // Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
using System; using System;
using System.Collections.Generic;
using System.IO;
using System.Net.Http;
using System.Runtime.CompilerServices;
using Identity.DefaultUI.WebSite;
using Microsoft.AspNetCore.Hosting; using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.TestHost; using Microsoft.AspNetCore.Identity.EntityFrameworkCore;
using Microsoft.AspNetCore.Mvc.Testing;
using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.DependencyInjection; using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Logging;
namespace Microsoft.AspNetCore.Identity.FunctionalTests namespace Microsoft.AspNetCore.Identity.FunctionalTests
{ {
public class ServerFactory : IDisposable public class ServerFactory<TStartup,TContext>: WebApplicationFactory<TStartup>
where TStartup : class
where TContext : DbContext
{ {
private bool disposedValue = false; public ServerFactory()
private IList<IDisposable> _disposableServers = new List<IDisposable>();
public TestServer CreateServer(
ILoggerFactory loggerFactory,
Action<IWebHostBuilder> configureBuilder,
[CallerMemberName] string isolationKey = "")
{ {
var builder = WebHostBuilderFactory ClientOptions.AllowAutoRedirect = false;
.CreateFromTypesAssemblyEntryPoint<Startup>(new string[] { }) ClientOptions.BaseAddress = new Uri("https://localhost");
.UseSolutionRelativeContentRoot(Path.Combine("test", "WebSites", "Identity.DefaultUI.WebSite")) }
.ConfigureServices(collection => collection.AddSingleton(loggerFactory))
.ConfigureServices(sc => sc.SetupTestDatabase(isolationKey) protected override void ConfigureWebHost(IWebHostBuilder builder)
{
base.ConfigureWebHost(builder);
builder.UseStartup<TStartup>();
builder.ConfigureServices(sc => sc.SetupTestDatabase<TContext>(Guid.NewGuid().ToString())
.AddMvc() .AddMvc()
// Mark the cookie as essential for right now, as Identity uses it on // Mark the cookie as essential for right now, as Identity uses it on
// several places to pass important data in post-redirect-get flows. // several places to pass important data in post-redirect-get flows.
.AddCookieTempDataProvider(o => o.Cookie.IsEssential = true)); .AddCookieTempDataProvider(o => o.Cookie.IsEssential = true));
configureBuilder(builder);
var server = new TestServer(builder);
_disposableServers.Add(server);
return server;
}
public TestServer CreateDefaultServer(ILoggerFactory loggerFactory, [CallerMemberName] string isolationKey = "") =>
CreateServer(loggerFactory, b => { }, isolationKey);
public HttpClient CreateDefaultClient(TestServer server)
{
var client = new HttpClient(new CookieContainerHandler(server.CreateHandler()))
{
BaseAddress = new Uri("https://localhost")
};
return client;
}
public HttpClient CreateDefaultClient(ILoggerFactory loggerFactory) =>
CreateDefaultClient(CreateDefaultServer(loggerFactory));
protected virtual void Dispose(bool disposing)
{
if (!disposedValue)
{
if (disposing)
{
foreach (var disposable in _disposableServers)
{
disposable?.Dispose();
}
}
_disposableServers = null;
disposedValue = true;
}
}
public void Dispose()
{
Dispose(true);
} }
} }
} }

View File

@ -5,249 +5,228 @@ using System;
using System.Linq; using System.Linq;
using System.Threading.Tasks; using System.Threading.Tasks;
using Identity.DefaultUI.WebSite; using Identity.DefaultUI.WebSite;
using Microsoft.Extensions.Logging.Testing; using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.DependencyInjection;
using Xunit; using Xunit;
using Xunit.Abstractions; using Xunit.Abstractions;
using Xunit.Sdk; using Xunit.Sdk;
namespace Microsoft.AspNetCore.Identity.FunctionalTests namespace Microsoft.AspNetCore.Identity.FunctionalTests
{ {
public class LoginTests : LoggedTest, IClassFixture<ServerFactory> public abstract class LoginTests<TStartup, TContext> : IClassFixture<ServerFactory<TStartup, TContext>>
where TStartup : class
where TContext : DbContext
{ {
public LoginTests(ServerFactory serverFactory, ITestOutputHelper output) : base(output) public LoginTests(ServerFactory<TStartup, TContext> serverFactory)
{ {
ServerFactory = serverFactory; ServerFactory = serverFactory;
} }
public ServerFactory ServerFactory { get; } public ServerFactory<TStartup, TContext> ServerFactory { get; }
[Fact] [Fact]
public async Task CanLogInWithAPreviouslyRegisteredUser() public async Task CanLogInWithAPreviouslyRegisteredUser()
{ {
using (StartLog(out var loggerFactory)) // Arrange
{ var client = ServerFactory.CreateClient();
// Arrange var newClient = ServerFactory.CreateClient();
var server = ServerFactory.CreateDefaultServer(loggerFactory);
var client = ServerFactory.CreateDefaultClient(server);
var newClient = ServerFactory.CreateDefaultClient(server);
var userName = $"{Guid.NewGuid()}@example.com"; var userName = $"{Guid.NewGuid()}@example.com";
var password = $"!Test.Password1$"; var password = $"!Test.Password1$";
// Act & Assert // Act & Assert
await UserStories.RegisterNewUserAsync(client, userName, password); await UserStories.RegisterNewUserAsync(client, userName, password);
// Use a new client to simulate a new browser session. // Use a new client to simulate a new browser session.
await UserStories.LoginExistingUserAsync(newClient, userName, password); await UserStories.LoginExistingUserAsync(newClient, userName, password);
}
} }
[Fact] [Fact]
public async Task CanLogInWithTwoFactorAuthentication() public async Task CanLogInWithTwoFactorAuthentication()
{ {
using (StartLog(out var loggerFactory)) // Arrange
{ var client = ServerFactory.CreateClient();
// Arrange var newClient = ServerFactory.CreateClient();
var server = ServerFactory.CreateDefaultServer(loggerFactory);
var client = ServerFactory.CreateDefaultClient(server);
var newClient = ServerFactory.CreateDefaultClient(server);
var userName = $"{Guid.NewGuid()}@example.com"; var userName = $"{Guid.NewGuid()}@example.com";
var password = $"!Test.Password1$"; var password = $"!Test.Password1$";
var loggedIn = await UserStories.RegisterNewUserAsync(client, userName, password); var loggedIn = await UserStories.RegisterNewUserAsync(client, userName, password);
var showRecoveryCodes = await UserStories.EnableTwoFactorAuthentication(loggedIn); var showRecoveryCodes = await UserStories.EnableTwoFactorAuthentication(loggedIn);
var twoFactorKey = showRecoveryCodes.Context.AuthenticatorKey; var twoFactorKey = showRecoveryCodes.Context.AuthenticatorKey;
// Act & Assert // Act & Assert
// Use a new client to simulate a new browser session. // Use a new client to simulate a new browser session.
await UserStories.LoginExistingUser2FaAsync(newClient, userName, password, twoFactorKey); await UserStories.LoginExistingUser2FaAsync(newClient, userName, password, twoFactorKey);
}
} }
[Fact] [Fact]
public async Task CanLogInWithTwoFactorAuthentication_WithGlobalAuthorizeFilter() public async Task CanLogInWithTwoFactorAuthentication_WithGlobalAuthorizeFilter()
{ {
using (StartLog(out var loggerFactory)) // Arrange
{ var client = ServerFactory.CreateClient();
// Arrange var newClient = ServerFactory.CreateClient();
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 userName = $"{Guid.NewGuid()}@example.com";
var password = $"!Test.Password1$"; var password = $"!Test.Password1$";
var loggedIn = await UserStories.RegisterNewUserAsync(client, userName, password); var loggedIn = await UserStories.RegisterNewUserAsync(client, userName, password);
var showRecoveryCodes = await UserStories.EnableTwoFactorAuthentication(loggedIn); var showRecoveryCodes = await UserStories.EnableTwoFactorAuthentication(loggedIn);
var twoFactorKey = showRecoveryCodes.Context.AuthenticatorKey; var twoFactorKey = showRecoveryCodes.Context.AuthenticatorKey;
// Act & Assert // Act & Assert
// Use a new client to simulate a new browser session. // Use a new client to simulate a new browser session.
await UserStories.LoginExistingUser2FaAsync(newClient, userName, password, twoFactorKey); await UserStories.LoginExistingUser2FaAsync(newClient, userName, password, twoFactorKey);
}
} }
[Fact] [Fact]
public async Task CanLogInWithRecoveryCode() public async Task CanLogInWithRecoveryCode()
{ {
using (StartLog(out var loggerFactory)) // Arrange
{ var client = ServerFactory.CreateClient();
// Arrange var newClient = ServerFactory.CreateClient();
var server = ServerFactory.CreateDefaultServer(loggerFactory);
var client = ServerFactory.CreateDefaultClient(server);
var newClient = ServerFactory.CreateDefaultClient(server);
var userName = $"{Guid.NewGuid()}@example.com"; var userName = $"{Guid.NewGuid()}@example.com";
var password = $"!Test.Password1$"; var password = $"!Test.Password1$";
var loggedIn = await UserStories.RegisterNewUserAsync(client, userName, password); var loggedIn = await UserStories.RegisterNewUserAsync(client, userName, password);
var showRecoveryCodes = await UserStories.EnableTwoFactorAuthentication(loggedIn); var showRecoveryCodes = await UserStories.EnableTwoFactorAuthentication(loggedIn);
var recoveryCode = showRecoveryCodes.Context.RecoveryCodes.First(); var recoveryCode = showRecoveryCodes.Context.RecoveryCodes.First();
// Act & Assert // Act & Assert
// Use a new client to simulate a new browser session. // Use a new client to simulate a new browser session.
await UserStories.LoginExistingUserRecoveryCodeAsync(newClient, userName, password, recoveryCode); await UserStories.LoginExistingUserRecoveryCodeAsync(newClient, userName, password, recoveryCode);
}
} }
[Fact] [Fact]
public async Task CanLogInWithRecoveryCode_WithGlobalAuthorizeFilter() public async Task CanLogInWithRecoveryCode_WithGlobalAuthorizeFilter()
{ {
using (StartLog(out var loggerFactory)) // Arrange
{ void ConfigureTestServices(IServiceCollection services) =>
// Arrange services.SetupGlobalAuthorizeFilter();
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 server = ServerFactory
var password = $"!Test.Password1$"; .WithWebHostBuilder(whb => whb.ConfigureServices(ConfigureTestServices));
var client = server.CreateClient();
var newClient = server.CreateClient();
var loggedIn = await UserStories.RegisterNewUserAsync(client, userName, password); var userName = $"{Guid.NewGuid()}@example.com";
var showRecoveryCodes = await UserStories.EnableTwoFactorAuthentication(loggedIn); var password = $"!Test.Password1$";
var recoveryCode = showRecoveryCodes.Context.RecoveryCodes.First(); var loggedIn = await UserStories.RegisterNewUserAsync(client, userName, password);
var showRecoveryCodes = await UserStories.EnableTwoFactorAuthentication(loggedIn);
// Act & Assert var recoveryCode = showRecoveryCodes.Context.RecoveryCodes.First();
// 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] [Fact]
public async Task CannotLogInWithoutRequiredEmailConfirmation() public async Task CannotLogInWithoutRequiredEmailConfirmation()
{ {
using (StartLog(out var loggerFactory)) // Arrange
{
// Arrange
var emailSender = new ContosoEmailSender();
var server = ServerFactory.CreateServer(loggerFactory, builder =>
{
builder.ConfigureServices(services => services
.SetupTestEmailSender(emailSender)
.SetupEmailRequired());
});
var client = ServerFactory.CreateDefaultClient(server); var emailSender = new ContosoEmailSender();
var newClient = ServerFactory.CreateDefaultClient(server); void ConfigureTestServices(IServiceCollection services) => services
.SetupTestEmailSender(emailSender)
.SetupEmailRequired();
var userName = $"{Guid.NewGuid()}@example.com"; var server = ServerFactory.WithWebHostBuilder(whb => whb.ConfigureServices(ConfigureTestServices));
var password = $"!Test.Password1$";
var loggedIn = await UserStories.RegisterNewUserAsync(client, userName, password); var client = server.CreateClient();
var newClient = server.CreateClient();
// Act & Assert var userName = $"{Guid.NewGuid()}@example.com";
// Use a new client to simulate a new browser session. var password = $"!Test.Password1$";
await Assert.ThrowsAnyAsync<XunitException>(() => UserStories.LoginExistingUserAsync(newClient, 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<XunitException>(() => UserStories.LoginExistingUserAsync(newClient, userName, password));
} }
[Fact] [Fact]
public async Task CanLogInAfterConfirmingEmail() public async Task CanLogInAfterConfirmingEmail()
{ {
using (StartLog(out var loggerFactory)) // Arrange
{ var emailSender = new ContosoEmailSender();
// Arrange void ConfigureTestServices(IServiceCollection services) => services
var emailSender = new ContosoEmailSender(); .SetupTestEmailSender(emailSender)
var server = ServerFactory.CreateServer(loggerFactory, builder => .SetupEmailRequired();
{
builder.ConfigureServices(services => services
.SetupTestEmailSender(emailSender)
.SetupEmailRequired());
});
var client = ServerFactory.CreateDefaultClient(server); var server = ServerFactory.WithWebHostBuilder(whb => whb.ConfigureServices(ConfigureTestServices));
var newClient = ServerFactory.CreateDefaultClient(server);
var userName = $"{Guid.NewGuid()}@example.com"; var client = server.CreateClient();
var password = $"!Test.Password1$"; var newClient = server.CreateClient();
var loggedIn = await UserStories.RegisterNewUserAsync(client, userName, password); var userName = $"{Guid.NewGuid()}@example.com";
var password = $"!Test.Password1$";
// Act & Assert var loggedIn = await UserStories.RegisterNewUserAsync(client, userName, password);
// 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); // 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);
} }
[Fact] [Fact]
public async Task CanLoginWithASocialLoginProvider() public async Task CanLoginWithASocialLoginProvider()
{ {
using (StartLog(out var loggerFactory)) // Arrange
{ void ConfigureTestServices(IServiceCollection services) =>
// Arrange services.SetupTestThirdPartyLogin();
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 server = ServerFactory.WithWebHostBuilder(whb => whb.ConfigureServices(ConfigureTestServices));
var userName = $"{guid}";
var email = $"{guid}@example.com";
// Act & Assert var client = server.CreateClient();
await UserStories.RegisterNewUserWithSocialLoginAsync(client, userName, email); var newClient = server.CreateClient();
await UserStories.LoginWithSocialLoginAsync(newClient, userName);
} 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);
} }
[Fact] [Fact]
public async Task CanLogInAfterResettingThePassword() public async Task CanLogInAfterResettingThePassword()
{ {
using (StartLog(out var loggerFactory)) // Arrange
{ var emailSender = new ContosoEmailSender();
// Arrange void ConfigureTestServices(IServiceCollection services) => services
var emailSender = new ContosoEmailSender(); .SetupTestEmailSender(emailSender);
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 server = ServerFactory.WithWebHostBuilder(whb => whb.ConfigureServices(ConfigureTestServices));
var password = $"!Test.Password1$";
var newPassword = $"!New.Password1$";
await UserStories.RegisterNewUserAsync(client, userName, password); var client = server.CreateClient();
var registrationEmail = Assert.Single(emailSender.SentEmails); var resetPasswordClient = server.CreateClient();
await UserStories.ConfirmEmailAsync(registrationEmail, client); var newClient = server.CreateClient();
// Act & Assert var userName = $"{Guid.NewGuid()}@example.com";
await UserStories.ForgotPasswordAsync(resetPasswordClient, userName); var password = $"!Test.Password1$";
Assert.Equal(2, emailSender.SentEmails.Count); var newPassword = $"!New.Password1$";
var email = emailSender.SentEmails[1];
await UserStories.ResetPasswordAsync(resetPasswordClient, email, userName, newPassword); await UserStories.RegisterNewUserAsync(client, userName, password);
await UserStories.LoginExistingUserAsync(newClient, userName, newPassword); 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);
} }
} }
} }

View File

@ -8,192 +8,221 @@ using System.Net;
using System.Security.Claims; using System.Security.Claims;
using System.Threading.Tasks; using System.Threading.Tasks;
using Identity.DefaultUI.WebSite; using Identity.DefaultUI.WebSite;
using Microsoft.AspNetCore.Identity.EntityFrameworkCore;
using Microsoft.AspNetCore.TestHost; using Microsoft.AspNetCore.TestHost;
using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Logging.Testing; using Microsoft.Extensions.Logging.Testing;
using Xunit; using Xunit;
using Xunit.Abstractions; using Xunit.Abstractions;
namespace Microsoft.AspNetCore.Identity.FunctionalTests namespace Microsoft.AspNetCore.Identity.FunctionalTests
{ {
public class ManagementTests : LoggedTest, IClassFixture<ServerFactory> public abstract class ManagementTests<TStartup, TContext> : IClassFixture<ServerFactory<TStartup, TContext>>
where TStartup : class
where TContext : DbContext
{ {
public ManagementTests(ServerFactory serverFactory, ITestOutputHelper output) : base(output) public ManagementTests(ServerFactory<TStartup, TContext> serverFactory)
{ {
ServerFactory = serverFactory; ServerFactory = serverFactory;
} }
public ServerFactory ServerFactory { get; } public ServerFactory<TStartup, TContext> ServerFactory { get; }
[Fact] [Fact]
public async Task CanEnableTwoFactorAuthentication() public async Task CanEnableTwoFactorAuthentication()
{ {
using (StartLog(out var loggerFactory)) // Arrange
{ var client = ServerFactory
// Arrange .CreateClient();
var client = ServerFactory.CreateDefaultClient(loggerFactory);
var userName = $"{Guid.NewGuid()}@example.com"; var userName = $"{Guid.NewGuid()}@example.com";
var password = $"!Test.Password1$"; var password = $"!Test.Password1$";
var index = await UserStories.RegisterNewUserAsync(client, userName, password); var index = await UserStories.RegisterNewUserAsync(client, userName, password);
// Act & Assert // Act & Assert
await UserStories.EnableTwoFactorAuthentication(index); await UserStories.EnableTwoFactorAuthentication(index);
}
} }
[Fact] [Fact]
public async Task CanConfirmEmail() public async Task CanConfirmEmail()
{ {
using (StartLog(out var loggerFactory)) // Arrange
{ var emails = new ContosoEmailSender();
// Arrange void ConfigureTestServices(IServiceCollection services) =>
var emails = new ContosoEmailSender(); services.SetupTestEmailSender(emails);
var server = ServerFactory.CreateServer(loggerFactory, builder =>
builder.ConfigureServices(s => s.SetupTestEmailSender(emails)));
var client = ServerFactory.CreateDefaultClient(server);
var userName = $"{Guid.NewGuid()}@example.com"; var client = ServerFactory
var password = $"!Test.Password1$"; .WithWebHostBuilder(whb => whb.ConfigureServices(ConfigureTestServices))
.CreateClient();
var index = await UserStories.RegisterNewUserAsync(client, userName, password); var userName = $"{Guid.NewGuid()}@example.com";
var manageIndex = await UserStories.SendEmailConfirmationLinkAsync(index); var password = $"!Test.Password1$";
// Act & Assert var index = await UserStories.RegisterNewUserAsync(client, userName, password);
Assert.Equal(2, emails.SentEmails.Count); var manageIndex = await UserStories.SendEmailConfirmationLinkAsync(index);
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 CanChangeEmail()
{
// Arrange
var emails = new ContosoEmailSender();
var client = ServerFactory
.CreateClient();
var userName = $"{Guid.NewGuid()}@example.com";
var password = $"!Test.Password1$";
var newEmail = "updatedEmail@example.com";
var index = await UserStories.RegisterNewUserAsync(client, userName, password);
var manageIndex = await UserStories.SendUpdateProfileAsync(index, newEmail);
// Act & Assert
var pageUserName = manageIndex.GetUserName();
Assert.Equal(newEmail, pageUserName);
var pageEmail = manageIndex.GetEmail();
Assert.Equal(newEmail, pageEmail);
} }
[Fact] [Fact]
public async Task CanChangePassword() public async Task CanChangePassword()
{ {
using (StartLog(out var loggerFactory)) // Arrange
{ var principals = new List<ClaimsPrincipal>();
// Arrange void ConfigureTestServices(IServiceCollection services) =>
var principals = new List<ClaimsPrincipal>(); services.SetupGetUserClaimsPrincipal(user => principals.Add(user), IdentityConstants.ApplicationScheme);
var server = ServerFactory.CreateServer(loggerFactory, builder =>
builder.ConfigureTestServices(s => s.SetupGetUserClaimsPrincipal(user => principals.Add(user), IdentityConstants.ApplicationScheme)));
var client = ServerFactory.CreateDefaultClient(server); var server = ServerFactory
var newClient = ServerFactory.CreateDefaultClient(server); .WithWebHostBuilder(whb => whb.ConfigureTestServices(ConfigureTestServices));
var userName = $"{Guid.NewGuid()}@example.com"; var client = server.CreateClient();
var password = "!Test.Password1"; var newClient = server.CreateClient();
var index = await UserStories.RegisterNewUserAsync(client, userName, password); var userName = $"{Guid.NewGuid()}@example.com";
var password = "!Test.Password1";
// Act 1 var index = await UserStories.RegisterNewUserAsync(client, userName, password);
var changedPassword = await UserStories.ChangePasswordAsync(index, "!Test.Password1", "!Test.Password2");
// Assert 1 // Act 1
// RefreshSignIn generates a new security stamp claim var changedPassword = await UserStories.ChangePasswordAsync(index, "!Test.Password1", "!Test.Password2");
AssertClaimsNotEqual(principals[0], principals[1], "AspNet.Identity.SecurityStamp");
// Act 2 // Assert 1
await UserStories.LoginExistingUserAsync(newClient, userName, "!Test.Password2"); // RefreshSignIn generates a new security stamp claim
AssertClaimsNotEqual(principals[0], principals[1], "AspNet.Identity.SecurityStamp");
// Assert 2 // Act 2
// Signing in again with a different client uses the same security stamp claim await UserStories.LoginExistingUserAsync(newClient, userName, "!Test.Password2");
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] [Fact]
public async Task CanSetPasswordWithExternalLogin() public async Task CanSetPasswordWithExternalLogin()
{ {
using (StartLog(out var loggerFactory)) // Arrange
{ var principals = new List<ClaimsPrincipal>();
// Arrange void ConfigureTestServices(IServiceCollection services) =>
var principals = new List<ClaimsPrincipal>(); services
var server = ServerFactory.CreateServer(loggerFactory, builder => .SetupTestThirdPartyLogin()
builder.ConfigureTestServices(s => s.SetupTestThirdPartyLogin() .SetupGetUserClaimsPrincipal(user => principals.Add(user), IdentityConstants.ApplicationScheme);
.SetupGetUserClaimsPrincipal(user => principals.Add(user), IdentityConstants.ApplicationScheme)));
var client = ServerFactory.CreateDefaultClient(server); var server = ServerFactory
var newClient = ServerFactory.CreateDefaultClient(server); .WithWebHostBuilder(whb => whb.ConfigureTestServices(ConfigureTestServices));
var guid = Guid.NewGuid(); var client = server.CreateClient();
var userName = $"{guid}"; var newClient = server.CreateClient();
var email = $"{guid}@example.com"; var loginAfterSetPasswordClient = server.CreateClient();
// Act 1 var guid = Guid.NewGuid();
var index = await UserStories.RegisterNewUserWithSocialLoginAsync(client, userName, email); var userName = $"{guid}";
index = await UserStories.LoginWithSocialLoginAsync(newClient, userName); var email = $"{guid}@example.com";
// Assert 1 // Act 1
Assert.NotNull(principals[1].Identities.Single().Claims.Single(c => c.Type == ClaimTypes.AuthenticationMethod).Value); var index = await UserStories.RegisterNewUserWithSocialLoginAsync(client, userName, email);
index = await UserStories.LoginWithSocialLoginAsync(newClient, userName);
// Act 2 // Assert 1
await UserStories.SetPasswordAsync(index, "!Test.Password2"); Assert.NotNull(principals[1].Identities.Single().Claims.Single(c => c.Type == ClaimTypes.AuthenticationMethod).Value);
// Assert 2 // Act 2
// RefreshSignIn uses the same AuthenticationMethod claim value await UserStories.SetPasswordAsync(index, "!Test.Password2");
AssertClaimsEqual(principals[1], principals[2], ClaimTypes.AuthenticationMethod);
// Act & Assert 3 // Assert 2
// Can log in with the password set above // RefreshSignIn uses the same AuthenticationMethod claim value
await UserStories.LoginExistingUserAsync(ServerFactory.CreateDefaultClient(server), email, "!Test.Password2"); AssertClaimsEqual(principals[1], principals[2], ClaimTypes.AuthenticationMethod);
}
// Act & Assert 3
// Can log in with the password set above
await UserStories.LoginExistingUserAsync(loginAfterSetPasswordClient, email, "!Test.Password2");
} }
[Fact] [Fact]
public async Task CanRemoveExternalLogin() public async Task CanRemoveExternalLogin()
{ {
using (StartLog(out var loggerFactory)) // Arrange
{ var principals = new List<ClaimsPrincipal>();
// Arrange void ConfigureTestServices(IServiceCollection services) =>
var principals = new List<ClaimsPrincipal>(); services
var server = ServerFactory.CreateServer(loggerFactory, builder => .SetupTestThirdPartyLogin()
builder.ConfigureTestServices(s => s.SetupTestThirdPartyLogin() .SetupGetUserClaimsPrincipal(user => principals.Add(user), IdentityConstants.ApplicationScheme);
.SetupGetUserClaimsPrincipal(user => principals.Add(user), IdentityConstants.ApplicationScheme)));
var client = ServerFactory.CreateDefaultClient(server); var server = ServerFactory
.WithWebHostBuilder(whb => whb.ConfigureTestServices(ConfigureTestServices));
var guid = Guid.NewGuid(); var client = server.CreateClient();
var userName = $"{guid}";
var email = $"{guid}@example.com";
// Act var guid = Guid.NewGuid();
var index = await UserStories.RegisterNewUserAsync(client, email, "!TestPassword1"); var userName = $"{guid}";
var linkLogin = await UserStories.LinkExternalLoginAsync(index, email); var email = $"{guid}@example.com";
await UserStories.RemoveExternalLoginAsync(linkLogin, email);
// RefreshSignIn generates a new security stamp claim // Act
AssertClaimsNotEqual(principals[0], principals[1], "AspNet.Identity.SecurityStamp"); 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");
} }
[Fact] [Fact]
public async Task CanResetAuthenticator() public async Task CanResetAuthenticator()
{ {
using (StartLog(out var loggerFactory)) // Arrange
{ var principals = new List<ClaimsPrincipal>();
// Arrange void ConfigureTestServices(IServiceCollection services) =>
var principals = new List<ClaimsPrincipal>(); services
var server = ServerFactory.CreateServer(loggerFactory, builder => .SetupTestThirdPartyLogin()
builder.ConfigureTestServices(s => s.SetupTestThirdPartyLogin() .SetupGetUserClaimsPrincipal(user => principals.Add(user), IdentityConstants.ApplicationScheme);
.SetupGetUserClaimsPrincipal(user => principals.Add(user), IdentityConstants.ApplicationScheme)));
var client = ServerFactory.CreateDefaultClient(server); var server = ServerFactory
var newClient = ServerFactory.CreateDefaultClient(server); .WithWebHostBuilder(whb => whb.ConfigureTestServices(ConfigureTestServices));
var userName = $"{Guid.NewGuid()}@example.com"; var client = server.CreateClient();
var password = $"!Test.Password1$"; var newClient = server.CreateClient();
// Act var userName = $"{Guid.NewGuid()}@example.com";
var loggedIn = await UserStories.RegisterNewUserAsync(client, userName, password); var password = $"!Test.Password1$";
var showRecoveryCodes = await UserStories.EnableTwoFactorAuthentication(loggedIn);
var twoFactorKey = showRecoveryCodes.Context.AuthenticatorKey;
// Use a new client to simulate a new browser session. // Act
var index = await UserStories.LoginExistingUser2FaAsync(newClient, userName, password, twoFactorKey); var loggedIn = await UserStories.RegisterNewUserAsync(client, userName, password);
await UserStories.ResetAuthenticator(index); var showRecoveryCodes = await UserStories.EnableTwoFactorAuthentication(loggedIn);
var twoFactorKey = showRecoveryCodes.Context.AuthenticatorKey;
// RefreshSignIn generates a new security stamp claim // Use a new client to simulate a new browser session.
AssertClaimsNotEqual(principals[1], principals[2], "AspNet.Identity.SecurityStamp"); 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");
} }
[Theory] [Theory]
@ -203,74 +232,93 @@ namespace Microsoft.AspNetCore.Identity.FunctionalTests
[InlineData(true, true)] [InlineData(true, true)]
public async Task CanDownloadPersonalData(bool twoFactor, bool social) public async Task CanDownloadPersonalData(bool twoFactor, bool social)
{ {
using (StartLog(out var loggerFactory)) // Arrange
void ConfigureTestServices(IServiceCollection services) =>
services.SetupTestThirdPartyLogin();
var client = ServerFactory
.WithWebHostBuilder(whb => whb.ConfigureTestServices(ConfigureTestServices))
.CreateClient();
var userName = $"{Guid.NewGuid()}@example.com";
var guid = Guid.NewGuid();
var email = userName;
var index = social
? await UserStories.RegisterNewUserWithSocialLoginAsync(client, userName, email)
: await UserStories.RegisterNewUserAsync(client, email, "!TestPassword1");
if (twoFactor)
{ {
// Arrange await UserStories.EnableTwoFactorAuthentication(index);
var server = ServerFactory.CreateServer(loggerFactory, builder => }
builder.ConfigureTestServices(s => s.SetupTestThirdPartyLogin()));
var client = ServerFactory.CreateDefaultClient(server); // Act & Assert
var jsonData = await UserStories.DownloadPersonalData(index, userName);
Assert.NotNull(jsonData);
Assert.True(jsonData.ContainsKey("Id"));
Assert.NotNull(jsonData["Id"]);
Assert.True(jsonData.ContainsKey("UserName"));
Assert.Equal(userName, (string)jsonData["UserName"]);
Assert.True(jsonData.ContainsKey("Email"));
Assert.Equal(userName, (string)jsonData["Email"]);
Assert.True(jsonData.ContainsKey("EmailConfirmed"));
Assert.False((bool)jsonData["EmailConfirmed"]);
Assert.True(jsonData.ContainsKey("PhoneNumber"));
Assert.Equal("null", (string)jsonData["PhoneNumber"]);
Assert.True(jsonData.ContainsKey("PhoneNumberConfirmed"));
Assert.False((bool)jsonData["PhoneNumberConfirmed"]);
Assert.Equal(twoFactor, (bool)jsonData["TwoFactorEnabled"]);
var userName = $"{Guid.NewGuid()}@example.com"; if (twoFactor)
var guid = Guid.NewGuid(); {
var email = userName; Assert.NotNull(jsonData["Authenticator Key"]);
}
else
{
Assert.Null((string)jsonData["Authenticator Key"]);
}
var index = social if (social)
? await UserStories.RegisterNewUserWithSocialLoginAsync(client, userName, email) {
: await UserStories.RegisterNewUserAsync(client, email, "!TestPassword1"); Assert.Equal(userName, (string)jsonData["Contoso external login provider key"]);
}
if (twoFactor) else
{ {
await UserStories.EnableTwoFactorAuthentication(index); Assert.Null((string)jsonData["Contoso external login provider key"]);
}
// 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\":\"{twoFactor}\"", jsonData);
Assert.Equal(twoFactor, jsonData.Contains($"\"Authenticator Key\":\""));
Assert.Equal(social, jsonData.Contains($"\"Contoso external login provider key\":\"{userName}\""));
} }
} }
[Fact] [Fact]
public async Task GetOnDownloadPersonalData_ReturnsNotFound() public async Task GetOnDownloadPersonalData_ReturnsNotFound()
{ {
using (StartLog(out var loggerFactory)) // Arrange
{ var client = ServerFactory
// Arrange .CreateClient();
var client = ServerFactory.CreateDefaultClient(loggerFactory);
await UserStories.RegisterNewUserAsync(client);
// Act await UserStories.RegisterNewUserAsync(client);
var response = await client.GetAsync("/Identity/Account/Manage/DownloadPersonalData");
// Assert // Act
Assert.Equal(HttpStatusCode.NotFound, response.StatusCode); var response = await client.GetAsync("/Identity/Account/Manage/DownloadPersonalData");
}
// Assert
Assert.Equal(HttpStatusCode.NotFound, response.StatusCode);
} }
[Fact] [Fact]
public async Task CanDeleteUser() public async Task CanDeleteUser()
{ {
using (StartLog(out var loggerFactory)) // Arrange
{ var client = ServerFactory
// Arrange .CreateClient();
var client = ServerFactory.CreateDefaultClient(loggerFactory);
var userName = $"{Guid.NewGuid()}@example.com"; var userName = $"{Guid.NewGuid()}@example.com";
var password = $"!Test.Password1$"; var password = $"!Test.Password1$";
var index = await UserStories.RegisterNewUserAsync(client, userName, password); var index = await UserStories.RegisterNewUserAsync(client, userName, password);
// Act & Assert // Act & Assert
await UserStories.DeleteUser(index, password); await UserStories.DeleteUser(index, password);
}
} }
private void AssertClaimsEqual(ClaimsPrincipal expectedPrincipal, ClaimsPrincipal actualPrincipal, string claimType) private void AssertClaimsEqual(ClaimsPrincipal expectedPrincipal, ClaimsPrincipal actualPrincipal, string claimType)

View File

@ -0,0 +1,71 @@
// 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 Identity.DefaultUI.WebSite;
using Microsoft.AspNetCore.Identity.EntityFrameworkCore;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Logging.Testing;
using Xunit;
using Xunit.Abstractions;
namespace Microsoft.AspNetCore.Identity.FunctionalTests
{
public class NoIdentityAddedTests : IClassFixture<ServerFactory<NoIdentityStartup, IdentityDbContext>>
{
public NoIdentityAddedTests(ServerFactory<NoIdentityStartup, IdentityDbContext> serverFactory)
{
ServerFactory = serverFactory;
}
public ServerFactory<NoIdentityStartup, IdentityDbContext> ServerFactory { get; }
[Theory]
[MemberData(nameof(IdentityEndpoints))]
public async Task QueryingIdentityEndpointsReturnsNotFoundWhenIdentityIsNotPresent(string endpoint)
{
// Arrange
void ConfigureTestServices(IServiceCollection services) { return; };
var client = ServerFactory
.WithWebHostBuilder(whb => whb.ConfigureServices(ConfigureTestServices))
.CreateClient();
// Act
var response = await client.GetAsync(endpoint);
Assert.Equal(HttpStatusCode.NotFound, response.StatusCode);
}
public static TheoryData<string> IdentityEndpoints => new TheoryData<string>
{
"/Identity/Account/AccessDenied",
"/Identity/Account/ConfirmEmail",
"/Identity/Account/ExternalLogin",
"/Identity/Account/ForgotPassword",
"/Identity/Account/ForgotPasswordConfirmation",
"/Identity/Account/Lockout",
"/Identity/Account/Login",
"/Identity/Account/LoginWith2fa",
"/Identity/Account/LoginWithRecoveryCode",
"/Identity/Account/Logout",
"/Identity/Account/Register",
"/Identity/Account/ResetPassword",
"/Identity/Account/ResetPasswordConfirmation",
"/Identity/Account/Manage/ChangePassword",
"/Identity/Account/Manage/DeletePersonalData",
"/Identity/Account/Manage/Disable2fa",
"/Identity/Account/Manage/DownloadPersonalData",
"/Identity/Account/Manage/EnableAuthenticator",
"/Identity/Account/Manage/ExternalLogins",
"/Identity/Account/Manage/GenerateRecoveryCodes",
"/Identity/Account/Manage/Index",
"/Identity/Account/Manage/PersonalData",
"/Identity/Account/Manage/ResetAuthenticator",
"/Identity/Account/Manage/SetPassword",
"/Identity/Account/Manage/ShowRecoveryCodes",
"/Identity/Account/Manage/TwoFactorAuthentication",
};
}
}

View File

@ -1,6 +1,8 @@
// Copyright (c) .NET Foundation. All rights reserved. // 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. // Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
using System;
using System.Collections.Generic;
using System.Net.Http; using System.Net.Http;
using System.Threading.Tasks; using System.Threading.Tasks;
using AngleSharp.Dom.Html; using AngleSharp.Dom.Html;
@ -16,6 +18,9 @@ namespace Microsoft.AspNetCore.Identity.FunctionalTests.Account.Manage
private readonly IHtmlAnchorElement _externalLoginLink; private readonly IHtmlAnchorElement _externalLoginLink;
private readonly IHtmlAnchorElement _personalDataLink; private readonly IHtmlAnchorElement _personalDataLink;
private readonly IHtmlFormElement _updateProfileForm; private readonly IHtmlFormElement _updateProfileForm;
private readonly IHtmlElement _emailInput;
private readonly IHtmlElement _userNameInput;
private readonly IHtmlElement _updateProfileButton;
private readonly IHtmlElement _confirmEmailButton; private readonly IHtmlElement _confirmEmailButton;
public static readonly string Path = "/"; public static readonly string Path = "/";
@ -33,6 +38,9 @@ namespace Microsoft.AspNetCore.Identity.FunctionalTests.Account.Manage
} }
_personalDataLink = HtmlAssert.HasLink("#personal-data", manage); _personalDataLink = HtmlAssert.HasLink("#personal-data", manage);
_updateProfileForm = HtmlAssert.HasForm("#profile-form", manage); _updateProfileForm = HtmlAssert.HasForm("#profile-form", manage);
_emailInput = HtmlAssert.HasElement("#Input_Email", manage);
_userNameInput = HtmlAssert.HasElement("#Username", manage);
_updateProfileButton = HtmlAssert.HasElement("#update-profile-button", manage);
if (!Context.EmailConfirmed) if (!Context.EmailConfirmed)
{ {
_confirmEmailButton = HtmlAssert.HasElement("button#email-verification", manage); _confirmEmailButton = HtmlAssert.HasElement("button#email-verification", manage);
@ -67,6 +75,19 @@ namespace Microsoft.AspNetCore.Identity.FunctionalTests.Account.Manage
return new Index(Client, manage, Context); return new Index(Client, manage, Context);
} }
internal async Task<Index> SendUpdateProfileAsync(string newEmail)
{
var response = await Client.SendAsync(_updateProfileForm, _updateProfileButton, new Dictionary<string, string>
{
["Input_Email"] = newEmail
});
var goToManage = ResponseAssert.IsRedirect(response);
var manageResponse = await Client.GetAsync(goToManage);
var manage = await ResponseAssert.IsHtmlDocumentAsync(manageResponse);
return new Index(Client, manage, Context);
}
public async Task<ChangePassword> ClickChangePasswordLinkAsync() public async Task<ChangePassword> ClickChangePasswordLinkAsync()
{ {
var goToChangePassword = await Client.GetAsync(_changePasswordLink.Href); var goToChangePassword = await Client.GetAsync(_changePasswordLink.Href);
@ -74,6 +95,10 @@ namespace Microsoft.AspNetCore.Identity.FunctionalTests.Account.Manage
return new ChangePassword(Client, changePasswordDocument, Context); return new ChangePassword(Client, changePasswordDocument, Context);
} }
internal string GetEmail() => _emailInput.GetAttribute("value");
internal object GetUserName() => _userNameInput.GetAttribute("value");
public async Task<SetPassword> ClickChangePasswordLinkExternalLoginAsync() public async Task<SetPassword> ClickChangePasswordLinkExternalLoginAsync()
{ {
var response = await Client.GetAsync(_changePasswordLink.Href); var response = await Client.GetAsync(_changePasswordLink.Href);

View File

@ -0,0 +1,16 @@
// 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 Identity.DefaultUI.WebSite;
using Microsoft.AspNetCore.Identity.EntityFrameworkCore;
using Xunit.Abstractions;
namespace Microsoft.AspNetCore.Identity.FunctionalTests.IdentityUserTests
{
public class PocoUserAuthorizationTests : AuthorizationTests<PocoUserStartup, IdentityDbContext>
{
public PocoUserAuthorizationTests(ServerFactory<PocoUserStartup, IdentityDbContext> serverFactory) : base(serverFactory)
{
}
}
}

View File

@ -0,0 +1,16 @@
// 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 Identity.DefaultUI.WebSite;
using Microsoft.AspNetCore.Identity.EntityFrameworkCore;
using Xunit.Abstractions;
namespace Microsoft.AspNetCore.Identity.FunctionalTests.IdentityUserTests
{
public class PocoUserLoginTests : LoginTests<PocoUserStartup, IdentityDbContext>
{
public PocoUserLoginTests(ServerFactory<PocoUserStartup, IdentityDbContext> serverFactory) : base(serverFactory)
{
}
}
}

View File

@ -0,0 +1,16 @@
// 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 Identity.DefaultUI.WebSite;
using Microsoft.AspNetCore.Identity.EntityFrameworkCore;
using Xunit.Abstractions;
namespace Microsoft.AspNetCore.Identity.FunctionalTests.IdentityUserTests
{
public class PocoUserManagementTests : ManagementTests<PocoUserStartup, IdentityDbContext>
{
public PocoUserManagementTests(ServerFactory<PocoUserStartup, IdentityDbContext> serverFactory) : base(serverFactory)
{
}
}
}

View File

@ -0,0 +1,16 @@
// 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 Identity.DefaultUI.WebSite;
using Microsoft.AspNetCore.Identity.EntityFrameworkCore;
using Xunit.Abstractions;
namespace Microsoft.AspNetCore.Identity.FunctionalTests.IdentityUserTests
{
public class PocoUserRegistrationTests : RegistrationTests<PocoUserStartup, IdentityDbContext>
{
public PocoUserRegistrationTests(ServerFactory<PocoUserStartup, IdentityDbContext> serverFactory) : base(serverFactory)
{
}
}
}

View File

@ -3,54 +3,58 @@
using System; using System;
using System.Threading.Tasks; using System.Threading.Tasks;
using Microsoft.Extensions.Logging.Testing; using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.DependencyInjection;
using Xunit; using Xunit;
using Xunit.Abstractions;
namespace Microsoft.AspNetCore.Identity.FunctionalTests namespace Microsoft.AspNetCore.Identity.FunctionalTests
{ {
public class RegistrationTests : LoggedTest, IClassFixture<ServerFactory> public abstract class RegistrationTests<TStartup, TContext> : IClassFixture<ServerFactory<TStartup, TContext>>
where TStartup : class
where TContext : DbContext
{ {
public RegistrationTests(ServerFactory serverFactory, ITestOutputHelper output) : base(output) public RegistrationTests(ServerFactory<TStartup, TContext> serverFactory)
{ {
ServerFactory = serverFactory; ServerFactory = serverFactory;
} }
public ServerFactory ServerFactory { get; } public ServerFactory<TStartup, TContext> ServerFactory { get; }
[Fact] [Fact]
public async Task CanRegisterAUser() public async Task CanRegisterAUser()
{ {
using (StartLog(out var loggerFactory)) // Arrange
{ void ConfigureTestServices(IServiceCollection services) { return; };
// Arrange
var client = ServerFactory.CreateDefaultClient(loggerFactory);
var userName = $"{Guid.NewGuid()}@example.com"; var client = ServerFactory
var password = $"!Test.Password1$"; .WithWebHostBuilder(whb => whb.ConfigureServices(ConfigureTestServices))
.CreateClient();
// Act & Assert var userName = $"{Guid.NewGuid()}@example.com";
await UserStories.RegisterNewUserAsync(client, userName, password); var password = $"!Test.Password1$";
}
// Act & Assert
await UserStories.RegisterNewUserAsync(client, userName, password);
} }
[Fact] [Fact]
public async Task CanRegisterWithASocialLoginProvider() public async Task CanRegisterWithASocialLoginProvider()
{ {
using (StartLog(out var loggerFactory)) // Arrange
{ void ConfigureTestServices(IServiceCollection services) =>
// Arrange services
var server = ServerFactory.CreateServer(loggerFactory, builder => .SetupTestThirdPartyLogin();
builder.ConfigureServices(services => services.SetupTestThirdPartyLogin()));
var client = ServerFactory.CreateDefaultClient(server);
var guid = Guid.NewGuid(); var client = ServerFactory
var userName = $"{guid}"; .WithWebHostBuilder(whb => whb.ConfigureServices(ConfigureTestServices))
var email = $"{guid}@example.com"; .CreateClient();
// Act & Assert var guid = Guid.NewGuid();
await UserStories.RegisterNewUserWithSocialLoginAsync(client, userName, email); var userName = $"{guid}";
} var email = $"{guid}@example.com";
// Act & Assert
await UserStories.RegisterNewUserWithSocialLoginAsync(client, userName, email);
} }
} }
} }

View File

@ -8,6 +8,8 @@ using AngleSharp.Dom.Html;
using Identity.DefaultUI.WebSite; using Identity.DefaultUI.WebSite;
using Microsoft.AspNetCore.Identity.FunctionalTests.Account; using Microsoft.AspNetCore.Identity.FunctionalTests.Account;
using Microsoft.AspNetCore.Identity.FunctionalTests.Account.Manage; using Microsoft.AspNetCore.Identity.FunctionalTests.Account.Manage;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
using Xunit; using Xunit;
namespace Microsoft.AspNetCore.Identity.FunctionalTests namespace Microsoft.AspNetCore.Identity.FunctionalTests
@ -53,6 +55,12 @@ namespace Microsoft.AspNetCore.Identity.FunctionalTests
return await manage.SendConfirmationEmailAsync(); return await manage.SendConfirmationEmailAsync();
} }
internal static async Task<Account.Manage.Index> SendUpdateProfileAsync(Index index, string newEmail)
{
var manage = await index.ClickManageLinkAsync();
return await manage.SendUpdateProfileAsync(newEmail);
}
internal static async Task<Index> LoginWithSocialLoginAsync(HttpClient client, string userName) internal static async Task<Index> LoginWithSocialLoginAsync(HttpClient client, string userName)
{ {
var index = await Index.CreateAsync( var index = await Index.CreateAsync(
@ -185,12 +193,13 @@ namespace Microsoft.AspNetCore.Identity.FunctionalTests
return await deleteUser.Delete(password); return await deleteUser.Delete(password);
} }
internal static async Task<string> DownloadPersonalData(Index index, string userName) internal static async Task<JObject> DownloadPersonalData(Index index, string userName)
{ {
var manage = await index.ClickManageLinkAsync(); var manage = await index.ClickManageLinkAsync();
var personalData = await manage.ClickPersonalDataLinkAsync(); var personalData = await manage.ClickPersonalDataLinkAsync();
var download = await personalData.SubmitDownloadForm(); var download = await personalData.SubmitDownloadForm();
return await download.Content.ReadAsStringAsync(); ResponseAssert.IsOK(download);
return JsonConvert.DeserializeObject<JObject>(await download.Content.ReadAsStringAsync());
} }
} }
} }

View File

@ -20,25 +20,25 @@ namespace Microsoft.AspNetCore.Identity.Test
public void AddRolesServicesAdded() public void AddRolesServicesAdded()
{ {
var services = new ServiceCollection(); var services = new ServiceCollection();
services.AddIdentityCore<TestUser>(o => { }) services.AddIdentityCore<PocoUser>(o => { })
.AddRoles<TestRole>() .AddRoles<PocoRole>()
.AddRoleStore<NoopRoleStore>(); .AddRoleStore<NoopRoleStore>();
var sp = services.BuildServiceProvider(); var sp = services.BuildServiceProvider();
Assert.NotNull(sp.GetRequiredService<IRoleValidator<TestRole>>()); Assert.NotNull(sp.GetRequiredService<IRoleValidator<PocoRole>>());
Assert.IsType<NoopRoleStore>(sp.GetRequiredService<IRoleStore<TestRole>>()); Assert.IsType<NoopRoleStore>(sp.GetRequiredService<IRoleStore<PocoRole>>());
Assert.NotNull(sp.GetRequiredService<RoleManager<TestRole>>()); Assert.NotNull(sp.GetRequiredService<RoleManager<PocoRole>>());
} }
[Fact] [Fact]
public void AddRolesWithoutStoreWillError() public void AddRolesWithoutStoreWillError()
{ {
var services = new ServiceCollection(); var services = new ServiceCollection();
services.AddIdentityCore<TestUser>(o => { }) services.AddIdentityCore<PocoUser>(o => { })
.AddRoles<TestRole>(); .AddRoles<PocoRole>();
var sp = services.BuildServiceProvider(); var sp = services.BuildServiceProvider();
Assert.NotNull(sp.GetRequiredService<IRoleValidator<TestRole>>()); Assert.NotNull(sp.GetRequiredService<IRoleValidator<PocoRole>>());
Assert.Null(sp.GetService<IRoleStore<TestRole>>()); Assert.Null(sp.GetService<IRoleStore<PocoRole>>());
Assert.Throws<InvalidOperationException>(() => sp.GetService<RoleManager<TestRole>>()); Assert.Throws<InvalidOperationException>(() => sp.GetService<RoleManager<PocoRole>>());
} }
@ -47,8 +47,8 @@ namespace Microsoft.AspNetCore.Identity.Test
{ {
var services = new ServiceCollection() var services = new ServiceCollection()
.AddSingleton<IConfiguration>(new ConfigurationBuilder().Build()); .AddSingleton<IConfiguration>(new ConfigurationBuilder().Build());
services.AddIdentity<TestUser,TestRole>().AddUserStore<MyUberThingy>(); services.AddIdentity<PocoUser,PocoRole>().AddUserStore<MyUberThingy>();
var thingy = services.BuildServiceProvider().GetRequiredService<IUserStore<TestUser>>() as MyUberThingy; var thingy = services.BuildServiceProvider().GetRequiredService<IUserStore<PocoUser>>() as MyUberThingy;
Assert.NotNull(thingy); Assert.NotNull(thingy);
} }
@ -57,8 +57,8 @@ namespace Microsoft.AspNetCore.Identity.Test
{ {
var services = new ServiceCollection() var services = new ServiceCollection()
.AddSingleton<IConfiguration>(new ConfigurationBuilder().Build()); .AddSingleton<IConfiguration>(new ConfigurationBuilder().Build());
services.AddIdentity<TestUser,TestRole>().AddRoleStore<MyUberThingy>(); services.AddIdentity<PocoUser,PocoRole>().AddRoleStore<MyUberThingy>();
var thingy = services.BuildServiceProvider().GetRequiredService<IRoleStore<TestRole>>() as MyUberThingy; var thingy = services.BuildServiceProvider().GetRequiredService<IRoleStore<PocoRole>>() as MyUberThingy;
Assert.NotNull(thingy); Assert.NotNull(thingy);
} }
@ -68,12 +68,12 @@ namespace Microsoft.AspNetCore.Identity.Test
var services = new ServiceCollection() var services = new ServiceCollection()
.AddLogging() .AddLogging()
.AddSingleton<IConfiguration>(new ConfigurationBuilder().Build()); .AddSingleton<IConfiguration>(new ConfigurationBuilder().Build());
services.AddIdentity<TestUser, TestRole>() services.AddIdentity<PocoUser, PocoRole>()
.AddClaimsPrincipalFactory<MyClaimsPrincipalFactory>() .AddClaimsPrincipalFactory<MyClaimsPrincipalFactory>()
.AddUserManager<MyUserManager>() .AddUserManager<MyUserManager>()
.AddUserStore<NoopUserStore>() .AddUserStore<NoopUserStore>()
.AddRoleStore<NoopRoleStore>(); .AddRoleStore<NoopRoleStore>();
var thingy = services.BuildServiceProvider().GetRequiredService<IUserClaimsPrincipalFactory<TestUser>>() as MyClaimsPrincipalFactory; var thingy = services.BuildServiceProvider().GetRequiredService<IUserClaimsPrincipalFactory<PocoUser>>() as MyClaimsPrincipalFactory;
Assert.NotNull(thingy); Assert.NotNull(thingy);
} }
@ -82,8 +82,8 @@ namespace Microsoft.AspNetCore.Identity.Test
{ {
var services = new ServiceCollection() var services = new ServiceCollection()
.AddSingleton<IConfiguration>(new ConfigurationBuilder().Build()); .AddSingleton<IConfiguration>(new ConfigurationBuilder().Build());
services.AddIdentity<TestUser,TestRole>().AddRoleValidator<MyUberThingy>(); services.AddIdentity<PocoUser,PocoRole>().AddRoleValidator<MyUberThingy>();
var thingy = services.BuildServiceProvider().GetRequiredService<IRoleValidator<TestRole>>() as MyUberThingy; var thingy = services.BuildServiceProvider().GetRequiredService<IRoleValidator<PocoRole>>() as MyUberThingy;
Assert.NotNull(thingy); Assert.NotNull(thingy);
} }
@ -92,8 +92,8 @@ namespace Microsoft.AspNetCore.Identity.Test
{ {
var services = new ServiceCollection() var services = new ServiceCollection()
.AddSingleton<IConfiguration>(new ConfigurationBuilder().Build()); .AddSingleton<IConfiguration>(new ConfigurationBuilder().Build());
services.AddIdentity<TestUser,TestRole>().AddUserValidator<MyUberThingy>(); services.AddIdentity<PocoUser,PocoRole>().AddUserValidator<MyUberThingy>();
var thingy = services.BuildServiceProvider().GetRequiredService<IUserValidator<TestUser>>() as MyUberThingy; var thingy = services.BuildServiceProvider().GetRequiredService<IUserValidator<PocoUser>>() as MyUberThingy;
Assert.NotNull(thingy); Assert.NotNull(thingy);
} }
@ -102,8 +102,8 @@ namespace Microsoft.AspNetCore.Identity.Test
{ {
var services = new ServiceCollection() var services = new ServiceCollection()
.AddSingleton<IConfiguration>(new ConfigurationBuilder().Build()); .AddSingleton<IConfiguration>(new ConfigurationBuilder().Build());
services.AddIdentity<TestUser,TestRole>().AddPasswordValidator<MyUberThingy>(); services.AddIdentity<PocoUser,PocoRole>().AddPasswordValidator<MyUberThingy>();
var thingy = services.BuildServiceProvider().GetRequiredService<IPasswordValidator<TestUser>>() as MyUberThingy; var thingy = services.BuildServiceProvider().GetRequiredService<IPasswordValidator<PocoUser>>() as MyUberThingy;
Assert.NotNull(thingy); Assert.NotNull(thingy);
} }
@ -112,10 +112,10 @@ namespace Microsoft.AspNetCore.Identity.Test
{ {
var services = new ServiceCollection() var services = new ServiceCollection()
.AddSingleton<IConfiguration>(new ConfigurationBuilder().Build()); .AddSingleton<IConfiguration>(new ConfigurationBuilder().Build());
services.AddIdentity<TestUser, TestRole>() services.AddIdentity<PocoUser, PocoRole>()
.AddUserStore<NoopUserStore>() .AddUserStore<NoopUserStore>()
.AddUserManager<MyUserManager>(); .AddUserManager<MyUserManager>();
var myUserManager = services.BuildServiceProvider().GetRequiredService(typeof(UserManager<TestUser>)) as MyUserManager; var myUserManager = services.BuildServiceProvider().GetRequiredService(typeof(UserManager<PocoUser>)) as MyUserManager;
Assert.NotNull(myUserManager); Assert.NotNull(myUserManager);
} }
@ -124,10 +124,10 @@ namespace Microsoft.AspNetCore.Identity.Test
{ {
var services = new ServiceCollection() var services = new ServiceCollection()
.AddSingleton<IConfiguration>(new ConfigurationBuilder().Build()); .AddSingleton<IConfiguration>(new ConfigurationBuilder().Build());
services.AddIdentity<TestUser, TestRole>() services.AddIdentity<PocoUser, PocoRole>()
.AddRoleStore<NoopRoleStore>() .AddRoleStore<NoopRoleStore>()
.AddRoleManager<MyRoleManager>(); .AddRoleManager<MyRoleManager>();
var myRoleManager = services.BuildServiceProvider().GetRequiredService<RoleManager<TestRole>>() as MyRoleManager; var myRoleManager = services.BuildServiceProvider().GetRequiredService<RoleManager<PocoRole>>() as MyRoleManager;
Assert.NotNull(myRoleManager); Assert.NotNull(myRoleManager);
} }
@ -138,13 +138,13 @@ namespace Microsoft.AspNetCore.Identity.Test
.AddSingleton<IConfiguration>(new ConfigurationBuilder().Build()) .AddSingleton<IConfiguration>(new ConfigurationBuilder().Build())
.AddHttpContextAccessor() .AddHttpContextAccessor()
.AddLogging(); .AddLogging();
services.AddIdentity<TestUser, TestRole>() services.AddIdentity<PocoUser, PocoRole>()
.AddUserStore<NoopUserStore>() .AddUserStore<NoopUserStore>()
.AddRoleStore<NoopRoleStore>() .AddRoleStore<NoopRoleStore>()
.AddUserManager<MyUserManager>() .AddUserManager<MyUserManager>()
.AddClaimsPrincipalFactory<MyClaimsPrincipalFactory>() .AddClaimsPrincipalFactory<MyClaimsPrincipalFactory>()
.AddSignInManager<MySignInManager>(); .AddSignInManager<MySignInManager>();
var myUserManager = services.BuildServiceProvider().GetRequiredService(typeof(SignInManager<TestUser>)) as MySignInManager; var myUserManager = services.BuildServiceProvider().GetRequiredService(typeof(SignInManager<PocoUser>)) as MySignInManager;
Assert.NotNull(myUserManager); Assert.NotNull(myUserManager);
} }
@ -153,16 +153,16 @@ namespace Microsoft.AspNetCore.Identity.Test
{ {
var services = new ServiceCollection() var services = new ServiceCollection()
.AddSingleton<IConfiguration>(new ConfigurationBuilder().Build()); .AddSingleton<IConfiguration>(new ConfigurationBuilder().Build());
services.AddIdentity<TestUser,TestRole>(); services.AddIdentity<PocoUser,PocoRole>();
var provider = services.BuildServiceProvider(); var provider = services.BuildServiceProvider();
var userValidator = provider.GetRequiredService<IUserValidator<TestUser>>() as UserValidator<TestUser>; var userValidator = provider.GetRequiredService<IUserValidator<PocoUser>>() as UserValidator<PocoUser>;
Assert.NotNull(userValidator); Assert.NotNull(userValidator);
var pwdValidator = provider.GetRequiredService<IPasswordValidator<TestUser>>() as PasswordValidator<TestUser>; var pwdValidator = provider.GetRequiredService<IPasswordValidator<PocoUser>>() as PasswordValidator<PocoUser>;
Assert.NotNull(pwdValidator); Assert.NotNull(pwdValidator);
var hasher = provider.GetRequiredService<IPasswordHasher<TestUser>>() as PasswordHasher<TestUser>; var hasher = provider.GetRequiredService<IPasswordHasher<PocoUser>>() as PasswordHasher<PocoUser>;
Assert.NotNull(hasher); Assert.NotNull(hasher);
} }
@ -171,7 +171,7 @@ namespace Microsoft.AspNetCore.Identity.Test
{ {
var services = new ServiceCollection() var services = new ServiceCollection()
.AddSingleton<IConfiguration>(new ConfigurationBuilder().Build()); .AddSingleton<IConfiguration>(new ConfigurationBuilder().Build());
services.AddIdentity<TestUser,TestRole>().AddDefaultTokenProviders(); services.AddIdentity<PocoUser,PocoRole>().AddDefaultTokenProviders();
var provider = services.BuildServiceProvider(); var provider = services.BuildServiceProvider();
var tokenProviders = provider.GetRequiredService<IOptions<IdentityOptions>>().Value.Tokens.ProviderMap.Values; var tokenProviders = provider.GetRequiredService<IOptions<IdentityOptions>>().Value.Tokens.ProviderMap.Values;
@ -183,7 +183,7 @@ namespace Microsoft.AspNetCore.Identity.Test
{ {
var services = new ServiceCollection() var services = new ServiceCollection()
.AddSingleton<IConfiguration>(new ConfigurationBuilder().Build()); .AddSingleton<IConfiguration>(new ConfigurationBuilder().Build());
var builder = services.AddIdentity<TestUser, TestRole>(); var builder = services.AddIdentity<PocoUser, PocoRole>();
Assert.Throws<InvalidOperationException>(() => builder.AddUserManager<object>()); Assert.Throws<InvalidOperationException>(() => builder.AddUserManager<object>());
Assert.Throws<InvalidOperationException>(() => builder.AddRoleManager<object>()); Assert.Throws<InvalidOperationException>(() => builder.AddRoleManager<object>());
Assert.Throws<InvalidOperationException>(() => builder.AddSignInManager<object>()); Assert.Throws<InvalidOperationException>(() => builder.AddSignInManager<object>());
@ -194,29 +194,29 @@ namespace Microsoft.AspNetCore.Identity.Test
{ {
var services = new ServiceCollection() var services = new ServiceCollection()
.AddSingleton<IConfiguration>(new ConfigurationBuilder().Build()); .AddSingleton<IConfiguration>(new ConfigurationBuilder().Build());
var builder = services.AddIdentity<TestUser, TestRole>(); var builder = services.AddIdentity<PocoUser, PocoRole>();
Assert.Throws<InvalidOperationException>(() => builder.AddTokenProvider<object>("whatevs")); Assert.Throws<InvalidOperationException>(() => builder.AddTokenProvider<object>("whatevs"));
Assert.Throws<InvalidOperationException>(() => builder.AddTokenProvider("whatevs", typeof(object))); Assert.Throws<InvalidOperationException>(() => builder.AddTokenProvider("whatevs", typeof(object)));
} }
private class MyUberThingy : IUserValidator<TestUser>, IPasswordValidator<TestUser>, IRoleValidator<TestRole>, IUserStore<TestUser>, IRoleStore<TestRole> private class MyUberThingy : IUserValidator<PocoUser>, IPasswordValidator<PocoUser>, IRoleValidator<PocoRole>, IUserStore<PocoUser>, IRoleStore<PocoRole>
{ {
public Task<IdentityResult> CreateAsync(TestRole role, CancellationToken cancellationToken = default(CancellationToken)) public Task<IdentityResult> CreateAsync(PocoRole role, CancellationToken cancellationToken = default(CancellationToken))
{ {
throw new NotImplementedException(); throw new NotImplementedException();
} }
public Task<IdentityResult> CreateAsync(TestUser user, CancellationToken cancellationToken = default(CancellationToken)) public Task<IdentityResult> CreateAsync(PocoUser user, CancellationToken cancellationToken = default(CancellationToken))
{ {
throw new NotImplementedException(); throw new NotImplementedException();
} }
public Task<IdentityResult> DeleteAsync(TestRole role, CancellationToken cancellationToken = default(CancellationToken)) public Task<IdentityResult> DeleteAsync(PocoRole role, CancellationToken cancellationToken = default(CancellationToken))
{ {
throw new NotImplementedException(); throw new NotImplementedException();
} }
public Task<IdentityResult> DeleteAsync(TestUser user, CancellationToken cancellationToken = default(CancellationToken)) public Task<IdentityResult> DeleteAsync(PocoUser user, CancellationToken cancellationToken = default(CancellationToken))
{ {
throw new NotImplementedException(); throw new NotImplementedException();
} }
@ -226,123 +226,123 @@ namespace Microsoft.AspNetCore.Identity.Test
throw new NotImplementedException(); throw new NotImplementedException();
} }
public Task<TestUser> FindByIdAsync(string userId, CancellationToken cancellationToken = default(CancellationToken)) public Task<PocoUser> FindByIdAsync(string userId, CancellationToken cancellationToken = default(CancellationToken))
{ {
throw new NotImplementedException(); throw new NotImplementedException();
} }
public Task<TestUser> FindByNameAsync(string normalizedUserName, CancellationToken cancellationToken = default(CancellationToken)) public Task<PocoUser> FindByNameAsync(string normalizedUserName, CancellationToken cancellationToken = default(CancellationToken))
{ {
throw new NotImplementedException(); throw new NotImplementedException();
} }
public Task<string> GetNormalizedRoleNameAsync(TestRole role, CancellationToken cancellationToken = default(CancellationToken)) public Task<string> GetNormalizedRoleNameAsync(PocoRole role, CancellationToken cancellationToken = default(CancellationToken))
{ {
throw new NotImplementedException(); throw new NotImplementedException();
} }
public Task<string> GetNormalizedUserNameAsync(TestUser user, CancellationToken cancellationToken = default(CancellationToken)) public Task<string> GetNormalizedUserNameAsync(PocoUser user, CancellationToken cancellationToken = default(CancellationToken))
{ {
throw new NotImplementedException(); throw new NotImplementedException();
} }
public Task<string> GetRoleIdAsync(TestRole role, CancellationToken cancellationToken = default(CancellationToken)) public Task<string> GetRoleIdAsync(PocoRole role, CancellationToken cancellationToken = default(CancellationToken))
{ {
throw new NotImplementedException(); throw new NotImplementedException();
} }
public Task<string> GetRoleNameAsync(TestRole role, CancellationToken cancellationToken = default(CancellationToken)) public Task<string> GetRoleNameAsync(PocoRole role, CancellationToken cancellationToken = default(CancellationToken))
{ {
throw new NotImplementedException(); throw new NotImplementedException();
} }
public Task<string> GetUserIdAsync(TestUser user, CancellationToken cancellationToken = default(CancellationToken)) public Task<string> GetUserIdAsync(PocoUser user, CancellationToken cancellationToken = default(CancellationToken))
{ {
throw new NotImplementedException(); throw new NotImplementedException();
} }
public Task<string> GetUserNameAsync(TestUser user, CancellationToken cancellationToken = default(CancellationToken)) public Task<string> GetUserNameAsync(PocoUser user, CancellationToken cancellationToken = default(CancellationToken))
{ {
throw new NotImplementedException(); throw new NotImplementedException();
} }
public Task SetNormalizedRoleNameAsync(TestRole role, string normalizedName, CancellationToken cancellationToken = default(CancellationToken)) public Task SetNormalizedRoleNameAsync(PocoRole role, string normalizedName, CancellationToken cancellationToken = default(CancellationToken))
{ {
throw new NotImplementedException(); throw new NotImplementedException();
} }
public Task SetNormalizedUserNameAsync(TestUser user, string normalizedName, CancellationToken cancellationToken = default(CancellationToken)) public Task SetNormalizedUserNameAsync(PocoUser user, string normalizedName, CancellationToken cancellationToken = default(CancellationToken))
{ {
throw new NotImplementedException(); throw new NotImplementedException();
} }
public Task SetRoleNameAsync(TestRole role, string roleName, CancellationToken cancellationToken = default(CancellationToken)) public Task SetRoleNameAsync(PocoRole role, string roleName, CancellationToken cancellationToken = default(CancellationToken))
{ {
throw new NotImplementedException(); throw new NotImplementedException();
} }
public Task SetUserNameAsync(TestUser user, string userName, CancellationToken cancellationToken = default(CancellationToken)) public Task SetUserNameAsync(PocoUser user, string userName, CancellationToken cancellationToken = default(CancellationToken))
{ {
throw new NotImplementedException(); throw new NotImplementedException();
} }
public Task<IdentityResult> UpdateAsync(TestRole role, CancellationToken cancellationToken = default(CancellationToken)) public Task<IdentityResult> UpdateAsync(PocoRole role, CancellationToken cancellationToken = default(CancellationToken))
{ {
throw new NotImplementedException(); throw new NotImplementedException();
} }
public Task<IdentityResult> UpdateAsync(TestUser user, CancellationToken cancellationToken = default(CancellationToken)) public Task<IdentityResult> UpdateAsync(PocoUser user, CancellationToken cancellationToken = default(CancellationToken))
{ {
throw new NotImplementedException(); throw new NotImplementedException();
} }
public Task<IdentityResult> ValidateAsync(RoleManager<TestRole> manager, TestRole role) public Task<IdentityResult> ValidateAsync(RoleManager<PocoRole> manager, PocoRole role)
{ {
throw new NotImplementedException(); throw new NotImplementedException();
} }
public Task<IdentityResult> ValidateAsync(UserManager<TestUser> manager, TestUser user) public Task<IdentityResult> ValidateAsync(UserManager<PocoUser> manager, PocoUser user)
{ {
throw new NotImplementedException(); throw new NotImplementedException();
} }
public Task<IdentityResult> ValidateAsync(UserManager<TestUser> manager, TestUser user, string password) public Task<IdentityResult> ValidateAsync(UserManager<PocoUser> manager, PocoUser user, string password)
{ {
throw new NotImplementedException(); throw new NotImplementedException();
} }
Task<TestRole> IRoleStore<TestRole>.FindByIdAsync(string roleId, CancellationToken cancellationToken) Task<PocoRole> IRoleStore<PocoRole>.FindByIdAsync(string roleId, CancellationToken cancellationToken)
{ {
throw new NotImplementedException(); throw new NotImplementedException();
} }
Task<TestRole> IRoleStore<TestRole>.FindByNameAsync(string roleName, CancellationToken cancellationToken) Task<PocoRole> IRoleStore<PocoRole>.FindByNameAsync(string roleName, CancellationToken cancellationToken)
{ {
throw new NotImplementedException(); throw new NotImplementedException();
} }
} }
private class MySignInManager : SignInManager<TestUser> private class MySignInManager : SignInManager<PocoUser>
{ {
public MySignInManager(UserManager<TestUser> manager, IHttpContextAccessor context, IUserClaimsPrincipalFactory<TestUser> claimsFactory) : base(manager, context, claimsFactory, null, null, null) { } public MySignInManager(UserManager<PocoUser> manager, IHttpContextAccessor context, IUserClaimsPrincipalFactory<PocoUser> claimsFactory) : base(manager, context, claimsFactory, null, null, null) { }
} }
private class MyUserManager : UserManager<TestUser> private class MyUserManager : UserManager<PocoUser>
{ {
public MyUserManager(IUserStore<TestUser> store) : base(store, null, null, null, null, null, null, null, null) { } public MyUserManager(IUserStore<PocoUser> store) : base(store, null, null, null, null, null, null, null, null) { }
} }
private class MyClaimsPrincipalFactory : UserClaimsPrincipalFactory<TestUser, TestRole> private class MyClaimsPrincipalFactory : UserClaimsPrincipalFactory<PocoUser, PocoRole>
{ {
public MyClaimsPrincipalFactory(UserManager<TestUser> userManager, RoleManager<TestRole> roleManager, IOptions<IdentityOptions> optionsAccessor) : base(userManager, roleManager, optionsAccessor) public MyClaimsPrincipalFactory(UserManager<PocoUser> userManager, RoleManager<PocoRole> roleManager, IOptions<IdentityOptions> optionsAccessor) : base(userManager, roleManager, optionsAccessor)
{ {
} }
} }
private class MyRoleManager : RoleManager<TestRole> private class MyRoleManager : RoleManager<PocoRole>
{ {
public MyRoleManager(IRoleStore<TestRole> store, public MyRoleManager(IRoleStore<PocoRole> store,
IEnumerable<IRoleValidator<TestRole>> roleValidators) : base(store, null, null, null, null) IEnumerable<IRoleValidator<PocoRole>> roleValidators) : base(store, null, null, null, null)
{ {
} }

View File

@ -40,7 +40,7 @@ namespace Microsoft.AspNetCore.Identity.Test
public void CanCustomizeIdentityOptions() public void CanCustomizeIdentityOptions()
{ {
var services = new ServiceCollection().Configure<IdentityOptions>(options => options.Password.RequiredLength = -1); var services = new ServiceCollection().Configure<IdentityOptions>(options => options.Password.RequiredLength = -1);
services.AddIdentity<TestUser,TestRole>(); services.AddIdentity<PocoUser,PocoRole>();
var serviceProvider = services.BuildServiceProvider(); var serviceProvider = services.BuildServiceProvider();
var setup = serviceProvider.GetRequiredService<IConfigureOptions<IdentityOptions>>(); var setup = serviceProvider.GetRequiredService<IConfigureOptions<IdentityOptions>>();
@ -60,7 +60,7 @@ namespace Microsoft.AspNetCore.Identity.Test
public void CanSetupIdentityOptions() public void CanSetupIdentityOptions()
{ {
var services = new ServiceCollection(); var services = new ServiceCollection();
services.AddIdentity<TestUser,TestRole>(options => options.User.RequireUniqueEmail = true); services.AddIdentity<PocoUser,PocoRole>(options => options.User.RequireUniqueEmail = true);
var serviceProvider = services.BuildServiceProvider(); var serviceProvider = services.BuildServiceProvider();
var optionsGetter = serviceProvider.GetRequiredService<IOptions<IdentityOptions>>(); var optionsGetter = serviceProvider.GetRequiredService<IOptions<IdentityOptions>>();

View File

@ -6,58 +6,58 @@ using System.Threading.Tasks;
namespace Microsoft.AspNetCore.Identity.Test namespace Microsoft.AspNetCore.Identity.Test
{ {
public class NoopRoleStore : IRoleStore<TestRole> public class NoopRoleStore : IRoleStore<PocoRole>
{ {
public Task<IdentityResult> CreateAsync(TestRole user, CancellationToken cancellationToken = default(CancellationToken)) public Task<IdentityResult> CreateAsync(PocoRole user, CancellationToken cancellationToken = default(CancellationToken))
{ {
return Task.FromResult(IdentityResult.Success); return Task.FromResult(IdentityResult.Success);
} }
public Task<IdentityResult> UpdateAsync(TestRole user, CancellationToken cancellationToken = default(CancellationToken)) public Task<IdentityResult> UpdateAsync(PocoRole user, CancellationToken cancellationToken = default(CancellationToken))
{ {
return Task.FromResult(IdentityResult.Success); return Task.FromResult(IdentityResult.Success);
} }
public Task<string> GetRoleNameAsync(TestRole role, CancellationToken cancellationToken = default(CancellationToken)) public Task<string> GetRoleNameAsync(PocoRole role, CancellationToken cancellationToken = default(CancellationToken))
{ {
return Task.FromResult<string>(null); return Task.FromResult<string>(null);
} }
public Task SetRoleNameAsync(TestRole role, string roleName, CancellationToken cancellationToken = default(CancellationToken)) public Task SetRoleNameAsync(PocoRole role, string roleName, CancellationToken cancellationToken = default(CancellationToken))
{ {
return Task.FromResult(0); return Task.FromResult(0);
} }
public Task<TestRole> FindByIdAsync(string roleId, CancellationToken cancellationToken = default(CancellationToken)) public Task<PocoRole> FindByIdAsync(string roleId, CancellationToken cancellationToken = default(CancellationToken))
{ {
return Task.FromResult<TestRole>(null); return Task.FromResult<PocoRole>(null);
} }
public Task<TestRole> FindByNameAsync(string userName, CancellationToken cancellationToken = default(CancellationToken)) public Task<PocoRole> FindByNameAsync(string userName, CancellationToken cancellationToken = default(CancellationToken))
{ {
return Task.FromResult<TestRole>(null); return Task.FromResult<PocoRole>(null);
} }
public void Dispose() public void Dispose()
{ {
} }
public Task<IdentityResult> DeleteAsync(TestRole user, CancellationToken cancellationToken = default(CancellationToken)) public Task<IdentityResult> DeleteAsync(PocoRole user, CancellationToken cancellationToken = default(CancellationToken))
{ {
return Task.FromResult(IdentityResult.Success); return Task.FromResult(IdentityResult.Success);
} }
public Task<string> GetRoleIdAsync(TestRole role, CancellationToken cancellationToken = default(CancellationToken)) public Task<string> GetRoleIdAsync(PocoRole role, CancellationToken cancellationToken = default(CancellationToken))
{ {
return Task.FromResult<string>(null); return Task.FromResult<string>(null);
} }
public Task<string> GetNormalizedRoleNameAsync(TestRole role, CancellationToken cancellationToken = default(CancellationToken)) public Task<string> GetNormalizedRoleNameAsync(PocoRole role, CancellationToken cancellationToken = default(CancellationToken))
{ {
return Task.FromResult<string>(null); return Task.FromResult<string>(null);
} }
public Task SetNormalizedRoleNameAsync(TestRole role, string normalizedName, CancellationToken cancellationToken = default(CancellationToken)) public Task SetNormalizedRoleNameAsync(PocoRole role, string normalizedName, CancellationToken cancellationToken = default(CancellationToken))
{ {
return Task.FromResult(0); return Task.FromResult(0);
} }

View File

@ -7,58 +7,58 @@ using System.Threading.Tasks;
namespace Microsoft.AspNetCore.Identity.Test namespace Microsoft.AspNetCore.Identity.Test
{ {
public class NoopUserStore : IUserStore<TestUser> public class NoopUserStore : IUserStore<PocoUser>
{ {
public Task<string> GetUserIdAsync(TestUser user, CancellationToken cancellationToken = default(CancellationToken)) public Task<string> GetUserIdAsync(PocoUser user, CancellationToken cancellationToken = default(CancellationToken))
{ {
return Task.FromResult(user.Id); return Task.FromResult(user.Id);
} }
public Task<string> GetUserNameAsync(TestUser user, CancellationToken cancellationToken = default(CancellationToken)) public Task<string> GetUserNameAsync(PocoUser user, CancellationToken cancellationToken = default(CancellationToken))
{ {
return Task.FromResult(user.UserName); return Task.FromResult(user.UserName);
} }
public Task SetUserNameAsync(TestUser user, string userName, CancellationToken cancellationToken = default(CancellationToken)) public Task SetUserNameAsync(PocoUser user, string userName, CancellationToken cancellationToken = default(CancellationToken))
{ {
return Task.FromResult(0); return Task.FromResult(0);
} }
public Task<IdentityResult> CreateAsync(TestUser user, CancellationToken cancellationToken = default(CancellationToken)) public Task<IdentityResult> CreateAsync(PocoUser user, CancellationToken cancellationToken = default(CancellationToken))
{ {
return Task.FromResult(IdentityResult.Success); return Task.FromResult(IdentityResult.Success);
} }
public Task<IdentityResult> UpdateAsync(TestUser user, CancellationToken cancellationToken = default(CancellationToken)) public Task<IdentityResult> UpdateAsync(PocoUser user, CancellationToken cancellationToken = default(CancellationToken))
{ {
return Task.FromResult(IdentityResult.Success); return Task.FromResult(IdentityResult.Success);
} }
public Task<TestUser> FindByIdAsync(string userId, CancellationToken cancellationToken = default(CancellationToken)) public Task<PocoUser> FindByIdAsync(string userId, CancellationToken cancellationToken = default(CancellationToken))
{ {
return Task.FromResult<TestUser>(null); return Task.FromResult<PocoUser>(null);
} }
public Task<TestUser> FindByNameAsync(string userName, CancellationToken cancellationToken = default(CancellationToken)) public Task<PocoUser> FindByNameAsync(string userName, CancellationToken cancellationToken = default(CancellationToken))
{ {
return Task.FromResult<TestUser>(null); return Task.FromResult<PocoUser>(null);
} }
public void Dispose() public void Dispose()
{ {
} }
public Task<IdentityResult> DeleteAsync(TestUser user, CancellationToken cancellationToken = default(CancellationToken)) public Task<IdentityResult> DeleteAsync(PocoUser user, CancellationToken cancellationToken = default(CancellationToken))
{ {
return Task.FromResult(IdentityResult.Success); return Task.FromResult(IdentityResult.Success);
} }
public Task<string> GetNormalizedUserNameAsync(TestUser user, CancellationToken cancellationToken = default(CancellationToken)) public Task<string> GetNormalizedUserNameAsync(PocoUser user, CancellationToken cancellationToken = default(CancellationToken))
{ {
return Task.FromResult<string>(null); return Task.FromResult<string>(null);
} }
public Task SetNormalizedUserNameAsync(TestUser user, string userName, CancellationToken cancellationToken = default(CancellationToken)) public Task SetNormalizedUserNameAsync(PocoUser user, string userName, CancellationToken cancellationToken = default(CancellationToken))
{ {
return Task.FromResult(0); return Task.FromResult(0);
} }

View File

@ -26,7 +26,7 @@ namespace Microsoft.AspNetCore.Identity.Test
public async Task ValidateThrowsWithNullTest() public async Task ValidateThrowsWithNullTest()
{ {
// Setup // Setup
var validator = new PasswordValidator<TestUser>(); var validator = new PasswordValidator<PocoUser>();
// Act // Act
// Assert // Assert
@ -42,8 +42,8 @@ namespace Microsoft.AspNetCore.Identity.Test
public async Task FailsIfTooShortTests(string input) public async Task FailsIfTooShortTests(string input)
{ {
const string error = "Passwords must be at least 6 characters."; const string error = "Passwords must be at least 6 characters.";
var manager = MockHelpers.TestUserManager<TestUser>(); var manager = MockHelpers.TestUserManager<PocoUser>();
var valid = new PasswordValidator<TestUser>(); var valid = new PasswordValidator<PocoUser>();
manager.Options.Password.RequireUppercase = false; manager.Options.Password.RequireUppercase = false;
manager.Options.Password.RequireNonAlphanumeric = false; manager.Options.Password.RequireNonAlphanumeric = false;
manager.Options.Password.RequireLowercase = false; manager.Options.Password.RequireLowercase = false;
@ -56,8 +56,8 @@ namespace Microsoft.AspNetCore.Identity.Test
[InlineData("aaaaaaaaaaa")] [InlineData("aaaaaaaaaaa")]
public async Task SuccessIfLongEnoughTests(string input) public async Task SuccessIfLongEnoughTests(string input)
{ {
var manager = MockHelpers.TestUserManager<TestUser>(); var manager = MockHelpers.TestUserManager<PocoUser>();
var valid = new PasswordValidator<TestUser>(); var valid = new PasswordValidator<PocoUser>();
manager.Options.Password.RequireUppercase = false; manager.Options.Password.RequireUppercase = false;
manager.Options.Password.RequireNonAlphanumeric = false; manager.Options.Password.RequireNonAlphanumeric = false;
manager.Options.Password.RequireLowercase = false; manager.Options.Password.RequireLowercase = false;
@ -70,8 +70,8 @@ namespace Microsoft.AspNetCore.Identity.Test
[InlineData("aaaaaaaaaaa")] [InlineData("aaaaaaaaaaa")]
public async Task FailsWithoutRequiredNonAlphanumericTests(string input) public async Task FailsWithoutRequiredNonAlphanumericTests(string input)
{ {
var manager = MockHelpers.TestUserManager<TestUser>(); var manager = MockHelpers.TestUserManager<PocoUser>();
var valid = new PasswordValidator<TestUser>(); var valid = new PasswordValidator<PocoUser>();
manager.Options.Password.RequireUppercase = false; manager.Options.Password.RequireUppercase = false;
manager.Options.Password.RequireNonAlphanumeric = true; manager.Options.Password.RequireNonAlphanumeric = true;
manager.Options.Password.RequireLowercase = false; manager.Options.Password.RequireLowercase = false;
@ -87,8 +87,8 @@ namespace Microsoft.AspNetCore.Identity.Test
[InlineData("!!!!!!")] [InlineData("!!!!!!")]
public async Task SucceedsWithRequiredNonAlphanumericTests(string input) public async Task SucceedsWithRequiredNonAlphanumericTests(string input)
{ {
var manager = MockHelpers.TestUserManager<TestUser>(); var manager = MockHelpers.TestUserManager<PocoUser>();
var valid = new PasswordValidator<TestUser>(); var valid = new PasswordValidator<PocoUser>();
manager.Options.Password.RequireUppercase = false; manager.Options.Password.RequireUppercase = false;
manager.Options.Password.RequireNonAlphanumeric = true; manager.Options.Password.RequireNonAlphanumeric = true;
manager.Options.Password.RequireLowercase = false; manager.Options.Password.RequireLowercase = false;
@ -103,8 +103,8 @@ namespace Microsoft.AspNetCore.Identity.Test
[InlineData("abcdabcdabcdabcdabcdabcdabcd", 5)] [InlineData("abcdabcdabcdabcdabcdabcdabcd", 5)]
public async Task FailsWithoutRequiredUniqueCharsTests(string input, int uniqueChars) public async Task FailsWithoutRequiredUniqueCharsTests(string input, int uniqueChars)
{ {
var manager = MockHelpers.TestUserManager<TestUser>(); var manager = MockHelpers.TestUserManager<PocoUser>();
var valid = new PasswordValidator<TestUser>(); var valid = new PasswordValidator<PocoUser>();
manager.Options.Password.RequireUppercase = false; manager.Options.Password.RequireUppercase = false;
manager.Options.Password.RequireNonAlphanumeric = false; manager.Options.Password.RequireNonAlphanumeric = false;
manager.Options.Password.RequireLowercase = false; manager.Options.Password.RequireLowercase = false;
@ -124,8 +124,8 @@ namespace Microsoft.AspNetCore.Identity.Test
[InlineData("this is a long password with many chars", 10)] [InlineData("this is a long password with many chars", 10)]
public async Task SucceedsWithRequiredUniqueCharsTests(string input, int uniqueChars) public async Task SucceedsWithRequiredUniqueCharsTests(string input, int uniqueChars)
{ {
var manager = MockHelpers.TestUserManager<TestUser>(); var manager = MockHelpers.TestUserManager<PocoUser>();
var valid = new PasswordValidator<TestUser>(); var valid = new PasswordValidator<PocoUser>();
manager.Options.Password.RequireUppercase = false; manager.Options.Password.RequireUppercase = false;
manager.Options.Password.RequireNonAlphanumeric = false; manager.Options.Password.RequireNonAlphanumeric = false;
manager.Options.Password.RequireLowercase = false; manager.Options.Password.RequireLowercase = false;
@ -149,8 +149,8 @@ namespace Microsoft.AspNetCore.Identity.Test
const string lowerError = "Passwords must have at least one lowercase ('a'-'z')."; const string lowerError = "Passwords must have at least one lowercase ('a'-'z').";
const string digitError = "Passwords must have at least one digit ('0'-'9')."; const string digitError = "Passwords must have at least one digit ('0'-'9').";
const string lengthError = "Passwords must be at least 6 characters."; const string lengthError = "Passwords must be at least 6 characters.";
var manager = MockHelpers.TestUserManager<TestUser>(); var manager = MockHelpers.TestUserManager<PocoUser>();
var valid = new PasswordValidator<TestUser>(); var valid = new PasswordValidator<PocoUser>();
var errors = new List<string>(); var errors = new List<string>();
if ((errorMask & Errors.Length) != Errors.None) if ((errorMask & Errors.Length) != Errors.None)
{ {

View File

@ -17,8 +17,8 @@ namespace Microsoft.AspNetCore.Identity.Test
public async Task CreateCallsStore() public async Task CreateCallsStore()
{ {
// Setup // Setup
var store = new Mock<IRoleStore<TestRole>>(); var store = new Mock<IRoleStore<PocoRole>>();
var role = new TestRole { Name = "Foo" }; var role = new PocoRole { Name = "Foo" };
store.Setup(s => s.CreateAsync(role, CancellationToken.None)).ReturnsAsync(IdentityResult.Success).Verifiable(); store.Setup(s => s.CreateAsync(role, CancellationToken.None)).ReturnsAsync(IdentityResult.Success).Verifiable();
store.Setup(s => s.GetRoleNameAsync(role, CancellationToken.None)).Returns(Task.FromResult(role.Name)).Verifiable(); store.Setup(s => s.GetRoleNameAsync(role, CancellationToken.None)).Returns(Task.FromResult(role.Name)).Verifiable();
store.Setup(s => s.SetNormalizedRoleNameAsync(role, role.Name.ToUpperInvariant(), CancellationToken.None)).Returns(Task.FromResult(0)).Verifiable(); store.Setup(s => s.SetNormalizedRoleNameAsync(role, role.Name.ToUpperInvariant(), CancellationToken.None)).Returns(Task.FromResult(0)).Verifiable();
@ -36,8 +36,8 @@ namespace Microsoft.AspNetCore.Identity.Test
public async Task UpdateCallsStore() public async Task UpdateCallsStore()
{ {
// Setup // Setup
var store = new Mock<IRoleStore<TestRole>>(); var store = new Mock<IRoleStore<PocoRole>>();
var role = new TestRole { Name = "Foo" }; var role = new PocoRole { Name = "Foo" };
store.Setup(s => s.UpdateAsync(role, CancellationToken.None)).ReturnsAsync(IdentityResult.Success).Verifiable(); store.Setup(s => s.UpdateAsync(role, CancellationToken.None)).ReturnsAsync(IdentityResult.Success).Verifiable();
store.Setup(s => s.GetRoleNameAsync(role, CancellationToken.None)).Returns(Task.FromResult(role.Name)).Verifiable(); store.Setup(s => s.GetRoleNameAsync(role, CancellationToken.None)).Returns(Task.FromResult(role.Name)).Verifiable();
store.Setup(s => s.SetNormalizedRoleNameAsync(role, role.Name.ToUpperInvariant(), CancellationToken.None)).Returns(Task.FromResult(0)).Verifiable(); store.Setup(s => s.SetNormalizedRoleNameAsync(role, role.Name.ToUpperInvariant(), CancellationToken.None)).Returns(Task.FromResult(0)).Verifiable();
@ -63,8 +63,8 @@ namespace Microsoft.AspNetCore.Identity.Test
public async Task FindByNameCallsStoreWithNormalizedName() public async Task FindByNameCallsStoreWithNormalizedName()
{ {
// Setup // Setup
var store = new Mock<IRoleStore<TestRole>>(); var store = new Mock<IRoleStore<PocoRole>>();
var role = new TestRole { Name = "Foo" }; var role = new PocoRole { Name = "Foo" };
store.Setup(s => s.FindByNameAsync("FOO", CancellationToken.None)).Returns(Task.FromResult(role)).Verifiable(); store.Setup(s => s.FindByNameAsync("FOO", CancellationToken.None)).Returns(Task.FromResult(role)).Verifiable();
var manager = MockHelpers.TestRoleManager(store.Object); var manager = MockHelpers.TestRoleManager(store.Object);
@ -80,8 +80,8 @@ namespace Microsoft.AspNetCore.Identity.Test
public async Task CanFindByNameCallsStoreWithoutNormalizedName() public async Task CanFindByNameCallsStoreWithoutNormalizedName()
{ {
// Setup // Setup
var store = new Mock<IRoleStore<TestRole>>(); var store = new Mock<IRoleStore<PocoRole>>();
var role = new TestRole { Name = "Foo" }; var role = new PocoRole { Name = "Foo" };
store.Setup(s => s.FindByNameAsync(role.Name, CancellationToken.None)).Returns(Task.FromResult(role)).Verifiable(); store.Setup(s => s.FindByNameAsync(role.Name, CancellationToken.None)).Returns(Task.FromResult(role)).Verifiable();
var manager = MockHelpers.TestRoleManager(store.Object); var manager = MockHelpers.TestRoleManager(store.Object);
manager.KeyNormalizer = null; manager.KeyNormalizer = null;
@ -98,8 +98,8 @@ namespace Microsoft.AspNetCore.Identity.Test
public async Task RoleExistsCallsStoreWithNormalizedName() public async Task RoleExistsCallsStoreWithNormalizedName()
{ {
// Setup // Setup
var store = new Mock<IRoleStore<TestRole>>(); var store = new Mock<IRoleStore<PocoRole>>();
var role = new TestRole { Name = "Foo" }; var role = new PocoRole { Name = "Foo" };
store.Setup(s => s.FindByNameAsync("FOO", CancellationToken.None)).Returns(Task.FromResult(role)).Verifiable(); store.Setup(s => s.FindByNameAsync("FOO", CancellationToken.None)).Returns(Task.FromResult(role)).Verifiable();
var manager = MockHelpers.TestRoleManager(store.Object); var manager = MockHelpers.TestRoleManager(store.Object);
@ -124,7 +124,7 @@ namespace Microsoft.AspNetCore.Identity.Test
public async Task RoleManagerPublicNullChecks() public async Task RoleManagerPublicNullChecks()
{ {
Assert.Throws<ArgumentNullException>("store", Assert.Throws<ArgumentNullException>("store",
() => new RoleManager<TestRole>(null, null, null, null, null)); () => new RoleManager<PocoRole>(null, null, null, null, null));
var manager = CreateRoleManager(new NotImplementedStore()); var manager = CreateRoleManager(new NotImplementedStore());
await Assert.ThrowsAsync<ArgumentNullException>("role", async () => await manager.CreateAsync(null)); await Assert.ThrowsAsync<ArgumentNullException>("role", async () => await manager.CreateAsync(null));
await Assert.ThrowsAsync<ArgumentNullException>("role", async () => await manager.UpdateAsync(null)); await Assert.ThrowsAsync<ArgumentNullException>("role", async () => await manager.UpdateAsync(null));
@ -146,49 +146,49 @@ namespace Microsoft.AspNetCore.Identity.Test
await Assert.ThrowsAsync<ObjectDisposedException>(() => manager.DeleteAsync(null)); await Assert.ThrowsAsync<ObjectDisposedException>(() => manager.DeleteAsync(null));
} }
private static RoleManager<TestRole> CreateRoleManager(IRoleStore<TestRole> roleStore) private static RoleManager<PocoRole> CreateRoleManager(IRoleStore<PocoRole> roleStore)
{ {
return MockHelpers.TestRoleManager(roleStore); return MockHelpers.TestRoleManager(roleStore);
} }
private class NotImplementedStore : IRoleStore<TestRole> private class NotImplementedStore : IRoleStore<PocoRole>
{ {
public Task<IdentityResult> CreateAsync(TestRole role, CancellationToken cancellationToken = default(CancellationToken)) public Task<IdentityResult> CreateAsync(PocoRole role, CancellationToken cancellationToken = default(CancellationToken))
{ {
throw new NotImplementedException(); throw new NotImplementedException();
} }
public Task<IdentityResult> UpdateAsync(TestRole role, CancellationToken cancellationToken = default(CancellationToken)) public Task<IdentityResult> UpdateAsync(PocoRole role, CancellationToken cancellationToken = default(CancellationToken))
{ {
throw new NotImplementedException(); throw new NotImplementedException();
} }
public Task<IdentityResult> DeleteAsync(TestRole role, CancellationToken cancellationToken = default(CancellationToken)) public Task<IdentityResult> DeleteAsync(PocoRole role, CancellationToken cancellationToken = default(CancellationToken))
{ {
throw new NotImplementedException(); throw new NotImplementedException();
} }
public Task<string> GetRoleIdAsync(TestRole role, CancellationToken cancellationToken = default(CancellationToken)) public Task<string> GetRoleIdAsync(PocoRole role, CancellationToken cancellationToken = default(CancellationToken))
{ {
throw new NotImplementedException(); throw new NotImplementedException();
} }
public Task<string> GetRoleNameAsync(TestRole role, CancellationToken cancellationToken = default(CancellationToken)) public Task<string> GetRoleNameAsync(PocoRole role, CancellationToken cancellationToken = default(CancellationToken))
{ {
throw new NotImplementedException(); throw new NotImplementedException();
} }
public Task SetRoleNameAsync(TestRole role, string roleName, CancellationToken cancellationToken = default(CancellationToken)) public Task SetRoleNameAsync(PocoRole role, string roleName, CancellationToken cancellationToken = default(CancellationToken))
{ {
throw new NotImplementedException(); throw new NotImplementedException();
} }
public Task<TestRole> FindByIdAsync(string roleId, CancellationToken cancellationToken = default(CancellationToken)) public Task<PocoRole> FindByIdAsync(string roleId, CancellationToken cancellationToken = default(CancellationToken))
{ {
throw new NotImplementedException(); throw new NotImplementedException();
} }
public Task<TestRole> FindByNameAsync(string roleName, CancellationToken cancellationToken = default(CancellationToken)) public Task<PocoRole> FindByNameAsync(string roleName, CancellationToken cancellationToken = default(CancellationToken))
{ {
throw new NotImplementedException(); throw new NotImplementedException();
} }
@ -198,12 +198,12 @@ namespace Microsoft.AspNetCore.Identity.Test
throw new NotImplementedException(); throw new NotImplementedException();
} }
public Task<string> GetNormalizedRoleNameAsync(TestRole role, CancellationToken cancellationToken = default(CancellationToken)) public Task<string> GetNormalizedRoleNameAsync(PocoRole role, CancellationToken cancellationToken = default(CancellationToken))
{ {
throw new NotImplementedException(); throw new NotImplementedException();
} }
public Task SetNormalizedRoleNameAsync(TestRole role, string normalizedName, CancellationToken cancellationToken = default(CancellationToken)) public Task SetNormalizedRoleNameAsync(PocoRole role, string normalizedName, CancellationToken cancellationToken = default(CancellationToken))
{ {
throw new NotImplementedException(); throw new NotImplementedException();
} }

View File

@ -13,8 +13,8 @@ namespace Microsoft.AspNetCore.Identity.Test
public async Task ValidateThrowsWithNull() public async Task ValidateThrowsWithNull()
{ {
// Setup // Setup
var validator = new RoleValidator<TestRole>(); var validator = new RoleValidator<PocoRole>();
var manager = MockHelpers.TestRoleManager<TestRole>(); var manager = MockHelpers.TestRoleManager<PocoRole>();
// Act // Act
// Assert // Assert
@ -28,9 +28,9 @@ namespace Microsoft.AspNetCore.Identity.Test
public async Task ValidateFailsWithTooShortRoleName(string input) public async Task ValidateFailsWithTooShortRoleName(string input)
{ {
// Setup // Setup
var validator = new RoleValidator<TestRole>(); var validator = new RoleValidator<PocoRole>();
var manager = MockHelpers.TestRoleManager<TestRole>(); var manager = MockHelpers.TestRoleManager<PocoRole>();
var user = new TestRole {Name = input}; var user = new PocoRole {Name = input};
// Act // Act
var result = await validator.ValidateAsync(manager, user); var result = await validator.ValidateAsync(manager, user);

View File

@ -70,7 +70,7 @@ namespace Microsoft.AspNetCore.Identity.Test
[InlineData(false)] [InlineData(false)]
public async Task OnValidatePrincipalTestSuccess(bool isPersistent) public async Task OnValidatePrincipalTestSuccess(bool isPersistent)
{ {
var user = new TestUser("test"); var user = new PocoUser("test");
var httpContext = new Mock<HttpContext>(); var httpContext = new Mock<HttpContext>();
await RunApplicationCookieTest(user, httpContext, /*shouldStampValidate*/true, async () => await RunApplicationCookieTest(user, httpContext, /*shouldStampValidate*/true, async () =>
@ -92,19 +92,19 @@ namespace Microsoft.AspNetCore.Identity.Test
}); });
} }
private async Task RunApplicationCookieTest(TestUser user, Mock<HttpContext> httpContext, bool shouldStampValidate, Func<Task> testCode) private async Task RunApplicationCookieTest(PocoUser user, Mock<HttpContext> httpContext, bool shouldStampValidate, Func<Task> testCode)
{ {
var userManager = MockHelpers.MockUserManager<TestUser>(); var userManager = MockHelpers.MockUserManager<PocoUser>();
var claimsManager = new Mock<IUserClaimsPrincipalFactory<TestUser>>(); var claimsManager = new Mock<IUserClaimsPrincipalFactory<PocoUser>>();
var identityOptions = new Mock<IOptions<IdentityOptions>>(); var identityOptions = new Mock<IOptions<IdentityOptions>>();
identityOptions.Setup(a => a.Value).Returns(new IdentityOptions()); identityOptions.Setup(a => a.Value).Returns(new IdentityOptions());
var options = new Mock<IOptions<SecurityStampValidatorOptions>>(); var options = new Mock<IOptions<SecurityStampValidatorOptions>>();
options.Setup(a => a.Value).Returns(new SecurityStampValidatorOptions { ValidationInterval = TimeSpan.Zero }); options.Setup(a => a.Value).Returns(new SecurityStampValidatorOptions { ValidationInterval = TimeSpan.Zero });
var contextAccessor = new Mock<IHttpContextAccessor>(); var contextAccessor = new Mock<IHttpContextAccessor>();
contextAccessor.Setup(a => a.HttpContext).Returns(httpContext.Object); contextAccessor.Setup(a => a.HttpContext).Returns(httpContext.Object);
var signInManager = new Mock<SignInManager<TestUser>>(userManager.Object, var signInManager = new Mock<SignInManager<PocoUser>>(userManager.Object,
contextAccessor.Object, claimsManager.Object, identityOptions.Object, null, new Mock<IAuthenticationSchemeProvider>().Object); contextAccessor.Object, claimsManager.Object, identityOptions.Object, null, new Mock<IAuthenticationSchemeProvider>().Object);
signInManager.Setup(s => s.ValidateSecurityStampAsync(It.IsAny<ClaimsPrincipal>())).ReturnsAsync(shouldStampValidate ? user : default(TestUser)).Verifiable(); signInManager.Setup(s => s.ValidateSecurityStampAsync(It.IsAny<ClaimsPrincipal>())).ReturnsAsync(shouldStampValidate ? user : default(PocoUser)).Verifiable();
if (shouldStampValidate) if (shouldStampValidate)
{ {
@ -117,7 +117,7 @@ namespace Microsoft.AspNetCore.Identity.Test
var services = new ServiceCollection(); var services = new ServiceCollection();
services.AddSingleton(options.Object); services.AddSingleton(options.Object);
services.AddSingleton(signInManager.Object); services.AddSingleton(signInManager.Object);
services.AddSingleton<ISecurityStampValidator>(new SecurityStampValidator<TestUser>(options.Object, signInManager.Object, new SystemClock())); services.AddSingleton<ISecurityStampValidator>(new SecurityStampValidator<PocoUser>(options.Object, signInManager.Object, new SystemClock()));
httpContext.Setup(c => c.RequestServices).Returns(services.BuildServiceProvider()); httpContext.Setup(c => c.RequestServices).Returns(services.BuildServiceProvider());
await testCode.Invoke(); await testCode.Invoke();
@ -127,7 +127,7 @@ namespace Microsoft.AspNetCore.Identity.Test
[Fact] [Fact]
public async Task OnValidateIdentityRejectsWhenValidateSecurityStampFails() public async Task OnValidateIdentityRejectsWhenValidateSecurityStampFails()
{ {
var user = new TestUser("test"); var user = new PocoUser("test");
var httpContext = new Mock<HttpContext>(); var httpContext = new Mock<HttpContext>();
await RunApplicationCookieTest(user, httpContext, /*shouldStampValidate*/false, async () => await RunApplicationCookieTest(user, httpContext, /*shouldStampValidate*/false, async () =>
@ -150,23 +150,23 @@ namespace Microsoft.AspNetCore.Identity.Test
[Fact] [Fact]
public async Task OnValidateIdentityRejectsWhenNoIssuedUtc() public async Task OnValidateIdentityRejectsWhenNoIssuedUtc()
{ {
var user = new TestUser("test"); var user = new PocoUser("test");
var httpContext = new Mock<HttpContext>(); var httpContext = new Mock<HttpContext>();
var userManager = MockHelpers.MockUserManager<TestUser>(); var userManager = MockHelpers.MockUserManager<PocoUser>();
var identityOptions = new Mock<IOptions<IdentityOptions>>(); var identityOptions = new Mock<IOptions<IdentityOptions>>();
identityOptions.Setup(a => a.Value).Returns(new IdentityOptions()); identityOptions.Setup(a => a.Value).Returns(new IdentityOptions());
var claimsManager = new Mock<IUserClaimsPrincipalFactory<TestUser>>(); var claimsManager = new Mock<IUserClaimsPrincipalFactory<PocoUser>>();
var options = new Mock<IOptions<SecurityStampValidatorOptions>>(); var options = new Mock<IOptions<SecurityStampValidatorOptions>>();
options.Setup(a => a.Value).Returns(new SecurityStampValidatorOptions { ValidationInterval = TimeSpan.Zero }); options.Setup(a => a.Value).Returns(new SecurityStampValidatorOptions { ValidationInterval = TimeSpan.Zero });
var contextAccessor = new Mock<IHttpContextAccessor>(); var contextAccessor = new Mock<IHttpContextAccessor>();
contextAccessor.Setup(a => a.HttpContext).Returns(httpContext.Object); contextAccessor.Setup(a => a.HttpContext).Returns(httpContext.Object);
var signInManager = new Mock<SignInManager<TestUser>>(userManager.Object, var signInManager = new Mock<SignInManager<PocoUser>>(userManager.Object,
contextAccessor.Object, claimsManager.Object, identityOptions.Object, null, new Mock<IAuthenticationSchemeProvider>().Object); contextAccessor.Object, claimsManager.Object, identityOptions.Object, null, new Mock<IAuthenticationSchemeProvider>().Object);
signInManager.Setup(s => s.ValidateSecurityStampAsync(It.IsAny<ClaimsPrincipal>())).ReturnsAsync(default(TestUser)).Verifiable(); signInManager.Setup(s => s.ValidateSecurityStampAsync(It.IsAny<ClaimsPrincipal>())).ReturnsAsync(default(PocoUser)).Verifiable();
var services = new ServiceCollection(); var services = new ServiceCollection();
services.AddSingleton(options.Object); services.AddSingleton(options.Object);
services.AddSingleton(signInManager.Object); services.AddSingleton(signInManager.Object);
services.AddSingleton<ISecurityStampValidator>(new SecurityStampValidator<TestUser>(options.Object, signInManager.Object, new SystemClock())); services.AddSingleton<ISecurityStampValidator>(new SecurityStampValidator<PocoUser>(options.Object, signInManager.Object, new SystemClock()));
httpContext.Setup(c => c.RequestServices).Returns(services.BuildServiceProvider()); httpContext.Setup(c => c.RequestServices).Returns(services.BuildServiceProvider());
var id = new ClaimsIdentity(IdentityConstants.ApplicationScheme); var id = new ClaimsIdentity(IdentityConstants.ApplicationScheme);
id.AddClaim(new Claim(ClaimTypes.NameIdentifier, user.Id)); id.AddClaim(new Claim(ClaimTypes.NameIdentifier, user.Id));
@ -186,24 +186,24 @@ namespace Microsoft.AspNetCore.Identity.Test
[Fact] [Fact]
public async Task OnValidateIdentityDoesNotRejectsWhenNotExpired() public async Task OnValidateIdentityDoesNotRejectsWhenNotExpired()
{ {
var user = new TestUser("test"); var user = new PocoUser("test");
var httpContext = new Mock<HttpContext>(); var httpContext = new Mock<HttpContext>();
var userManager = MockHelpers.MockUserManager<TestUser>(); var userManager = MockHelpers.MockUserManager<PocoUser>();
var identityOptions = new Mock<IOptions<IdentityOptions>>(); var identityOptions = new Mock<IOptions<IdentityOptions>>();
identityOptions.Setup(a => a.Value).Returns(new IdentityOptions()); identityOptions.Setup(a => a.Value).Returns(new IdentityOptions());
var claimsManager = new Mock<IUserClaimsPrincipalFactory<TestUser>>(); var claimsManager = new Mock<IUserClaimsPrincipalFactory<PocoUser>>();
var options = new Mock<IOptions<SecurityStampValidatorOptions>>(); var options = new Mock<IOptions<SecurityStampValidatorOptions>>();
options.Setup(a => a.Value).Returns(new SecurityStampValidatorOptions { ValidationInterval = TimeSpan.FromDays(1) }); options.Setup(a => a.Value).Returns(new SecurityStampValidatorOptions { ValidationInterval = TimeSpan.FromDays(1) });
var contextAccessor = new Mock<IHttpContextAccessor>(); var contextAccessor = new Mock<IHttpContextAccessor>();
contextAccessor.Setup(a => a.HttpContext).Returns(httpContext.Object); contextAccessor.Setup(a => a.HttpContext).Returns(httpContext.Object);
var signInManager = new Mock<SignInManager<TestUser>>(userManager.Object, var signInManager = new Mock<SignInManager<PocoUser>>(userManager.Object,
contextAccessor.Object, claimsManager.Object, identityOptions.Object, null, new Mock<IAuthenticationSchemeProvider>().Object); contextAccessor.Object, claimsManager.Object, identityOptions.Object, null, new Mock<IAuthenticationSchemeProvider>().Object);
signInManager.Setup(s => s.ValidateSecurityStampAsync(It.IsAny<ClaimsPrincipal>())).Throws(new Exception("Shouldn't be called")); signInManager.Setup(s => s.ValidateSecurityStampAsync(It.IsAny<ClaimsPrincipal>())).Throws(new Exception("Shouldn't be called"));
signInManager.Setup(s => s.SignInAsync(user, false, null)).Throws(new Exception("Shouldn't be called")); signInManager.Setup(s => s.SignInAsync(user, false, null)).Throws(new Exception("Shouldn't be called"));
var services = new ServiceCollection(); var services = new ServiceCollection();
services.AddSingleton(options.Object); services.AddSingleton(options.Object);
services.AddSingleton(signInManager.Object); services.AddSingleton(signInManager.Object);
services.AddSingleton<ISecurityStampValidator>(new SecurityStampValidator<TestUser>(options.Object, signInManager.Object, new SystemClock())); services.AddSingleton<ISecurityStampValidator>(new SecurityStampValidator<PocoUser>(options.Object, signInManager.Object, new SystemClock()));
httpContext.Setup(c => c.RequestServices).Returns(services.BuildServiceProvider()); httpContext.Setup(c => c.RequestServices).Returns(services.BuildServiceProvider());
var id = new ClaimsIdentity(IdentityConstants.ApplicationScheme); var id = new ClaimsIdentity(IdentityConstants.ApplicationScheme);
id.AddClaim(new Claim(ClaimTypes.NameIdentifier, user.Id)); id.AddClaim(new Claim(ClaimTypes.NameIdentifier, user.Id));
@ -221,25 +221,25 @@ namespace Microsoft.AspNetCore.Identity.Test
private async Task RunRememberClientCookieTest(bool shouldStampValidate, bool validationSuccess) private async Task RunRememberClientCookieTest(bool shouldStampValidate, bool validationSuccess)
{ {
var user = new TestUser("test"); var user = new PocoUser("test");
var httpContext = new Mock<HttpContext>(); var httpContext = new Mock<HttpContext>();
var userManager = MockHelpers.MockUserManager<TestUser>(); var userManager = MockHelpers.MockUserManager<PocoUser>();
userManager.Setup(u => u.GetUserIdAsync(user)).ReturnsAsync(user.Id).Verifiable(); userManager.Setup(u => u.GetUserIdAsync(user)).ReturnsAsync(user.Id).Verifiable();
var claimsManager = new Mock<IUserClaimsPrincipalFactory<TestUser>>(); var claimsManager = new Mock<IUserClaimsPrincipalFactory<PocoUser>>();
var identityOptions = new Mock<IOptions<IdentityOptions>>(); var identityOptions = new Mock<IOptions<IdentityOptions>>();
identityOptions.Setup(a => a.Value).Returns(new IdentityOptions()); identityOptions.Setup(a => a.Value).Returns(new IdentityOptions());
var options = new Mock<IOptions<SecurityStampValidatorOptions>>(); var options = new Mock<IOptions<SecurityStampValidatorOptions>>();
options.Setup(a => a.Value).Returns(new SecurityStampValidatorOptions { ValidationInterval = TimeSpan.Zero }); options.Setup(a => a.Value).Returns(new SecurityStampValidatorOptions { ValidationInterval = TimeSpan.Zero });
var contextAccessor = new Mock<IHttpContextAccessor>(); var contextAccessor = new Mock<IHttpContextAccessor>();
contextAccessor.Setup(a => a.HttpContext).Returns(httpContext.Object); contextAccessor.Setup(a => a.HttpContext).Returns(httpContext.Object);
var signInManager = new Mock<SignInManager<TestUser>>(userManager.Object, var signInManager = new Mock<SignInManager<PocoUser>>(userManager.Object,
contextAccessor.Object, claimsManager.Object, identityOptions.Object, null, new Mock<IAuthenticationSchemeProvider>().Object); contextAccessor.Object, claimsManager.Object, identityOptions.Object, null, new Mock<IAuthenticationSchemeProvider>().Object);
signInManager.Setup(s => s.ValidateTwoFactorSecurityStampAsync(It.IsAny<ClaimsPrincipal>())).ReturnsAsync(shouldStampValidate ? user : default).Verifiable(); signInManager.Setup(s => s.ValidateTwoFactorSecurityStampAsync(It.IsAny<ClaimsPrincipal>())).ReturnsAsync(shouldStampValidate ? user : default).Verifiable();
var services = new ServiceCollection(); var services = new ServiceCollection();
services.AddSingleton(options.Object); services.AddSingleton(options.Object);
services.AddSingleton(signInManager.Object); services.AddSingleton(signInManager.Object);
services.AddSingleton<ITwoFactorSecurityStampValidator>(new TwoFactorSecurityStampValidator<TestUser>(options.Object, signInManager.Object, new SystemClock())); services.AddSingleton<ITwoFactorSecurityStampValidator>(new TwoFactorSecurityStampValidator<PocoUser>(options.Object, signInManager.Object, new SystemClock()));
httpContext.Setup(c => c.RequestServices).Returns(services.BuildServiceProvider()); httpContext.Setup(c => c.RequestServices).Returns(services.BuildServiceProvider());
var principal = await signInManager.Object.StoreRememberClient(user); var principal = await signInManager.Object.StoreRememberClient(user);

View File

@ -67,13 +67,13 @@ namespace Microsoft.AspNetCore.Identity.Test
[Fact] [Fact]
public void ConstructorNullChecks() public void ConstructorNullChecks()
{ {
Assert.Throws<ArgumentNullException>("userManager", () => new SignInManager<TestUser>(null, null, null, null, null, null)); Assert.Throws<ArgumentNullException>("userManager", () => new SignInManager<PocoUser>(null, null, null, null, null, null));
var userManager = MockHelpers.MockUserManager<TestUser>().Object; var userManager = MockHelpers.MockUserManager<PocoUser>().Object;
Assert.Throws<ArgumentNullException>("contextAccessor", () => new SignInManager<TestUser>(userManager, null, null, null, null, null)); Assert.Throws<ArgumentNullException>("contextAccessor", () => new SignInManager<PocoUser>(userManager, null, null, null, null, null));
var contextAccessor = new Mock<IHttpContextAccessor>(); var contextAccessor = new Mock<IHttpContextAccessor>();
var context = new Mock<HttpContext>(); var context = new Mock<HttpContext>();
contextAccessor.Setup(a => a.HttpContext).Returns(context.Object); contextAccessor.Setup(a => a.HttpContext).Returns(context.Object);
Assert.Throws<ArgumentNullException>("claimsFactory", () => new SignInManager<TestUser>(userManager, contextAccessor.Object, null, null, null, null)); Assert.Throws<ArgumentNullException>("claimsFactory", () => new SignInManager<PocoUser>(userManager, contextAccessor.Object, null, null, null, null));
} }
//[Fact] //[Fact]
@ -108,7 +108,7 @@ namespace Microsoft.AspNetCore.Identity.Test
public async Task PasswordSignInReturnsLockedOutWhenLockedOut() public async Task PasswordSignInReturnsLockedOutWhenLockedOut()
{ {
// Setup // Setup
var user = new TestUser { UserName = "Foo" }; var user = new PocoUser { UserName = "Foo" };
var manager = SetupUserManager(user); var manager = SetupUserManager(user);
manager.Setup(m => m.SupportsUserLockout).Returns(true).Verifiable(); manager.Setup(m => m.SupportsUserLockout).Returns(true).Verifiable();
manager.Setup(m => m.IsLockedOutAsync(user)).ReturnsAsync(true).Verifiable(); manager.Setup(m => m.IsLockedOutAsync(user)).ReturnsAsync(true).Verifiable();
@ -116,14 +116,14 @@ namespace Microsoft.AspNetCore.Identity.Test
var context = new Mock<HttpContext>(); var context = new Mock<HttpContext>();
var contextAccessor = new Mock<IHttpContextAccessor>(); var contextAccessor = new Mock<IHttpContextAccessor>();
contextAccessor.Setup(a => a.HttpContext).Returns(context.Object); contextAccessor.Setup(a => a.HttpContext).Returns(context.Object);
var roleManager = MockHelpers.MockRoleManager<TestRole>(); var roleManager = MockHelpers.MockRoleManager<PocoRole>();
var identityOptions = new IdentityOptions(); var identityOptions = new IdentityOptions();
var options = new Mock<IOptions<IdentityOptions>>(); var options = new Mock<IOptions<IdentityOptions>>();
options.Setup(a => a.Value).Returns(identityOptions); options.Setup(a => a.Value).Returns(identityOptions);
var claimsFactory = new UserClaimsPrincipalFactory<TestUser, TestRole>(manager.Object, roleManager.Object, options.Object); var claimsFactory = new UserClaimsPrincipalFactory<PocoUser, PocoRole>(manager.Object, roleManager.Object, options.Object);
var logStore = new StringBuilder(); var logStore = new StringBuilder();
var logger = MockHelpers.MockILogger<SignInManager<TestUser>>(logStore); var logger = MockHelpers.MockILogger<SignInManager<PocoUser>>(logStore);
var helper = new SignInManager<TestUser>(manager.Object, contextAccessor.Object, claimsFactory, options.Object, logger.Object, new Mock<IAuthenticationSchemeProvider>().Object); var helper = new SignInManager<PocoUser>(manager.Object, contextAccessor.Object, claimsFactory, options.Object, logger.Object, new Mock<IAuthenticationSchemeProvider>().Object);
// Act // Act
var result = await helper.PasswordSignInAsync(user.UserName, "bogus", false, false); var result = await helper.PasswordSignInAsync(user.UserName, "bogus", false, false);
@ -139,7 +139,7 @@ namespace Microsoft.AspNetCore.Identity.Test
public async Task CheckPasswordSignInReturnsLockedOutWhenLockedOut() public async Task CheckPasswordSignInReturnsLockedOutWhenLockedOut()
{ {
// Setup // Setup
var user = new TestUser { UserName = "Foo" }; var user = new PocoUser { UserName = "Foo" };
var manager = SetupUserManager(user); var manager = SetupUserManager(user);
manager.Setup(m => m.SupportsUserLockout).Returns(true).Verifiable(); manager.Setup(m => m.SupportsUserLockout).Returns(true).Verifiable();
manager.Setup(m => m.IsLockedOutAsync(user)).ReturnsAsync(true).Verifiable(); manager.Setup(m => m.IsLockedOutAsync(user)).ReturnsAsync(true).Verifiable();
@ -147,14 +147,14 @@ namespace Microsoft.AspNetCore.Identity.Test
var context = new Mock<HttpContext>(); var context = new Mock<HttpContext>();
var contextAccessor = new Mock<IHttpContextAccessor>(); var contextAccessor = new Mock<IHttpContextAccessor>();
contextAccessor.Setup(a => a.HttpContext).Returns(context.Object); contextAccessor.Setup(a => a.HttpContext).Returns(context.Object);
var roleManager = MockHelpers.MockRoleManager<TestRole>(); var roleManager = MockHelpers.MockRoleManager<PocoRole>();
var identityOptions = new IdentityOptions(); var identityOptions = new IdentityOptions();
var options = new Mock<IOptions<IdentityOptions>>(); var options = new Mock<IOptions<IdentityOptions>>();
options.Setup(a => a.Value).Returns(identityOptions); options.Setup(a => a.Value).Returns(identityOptions);
var claimsFactory = new UserClaimsPrincipalFactory<TestUser, TestRole>(manager.Object, roleManager.Object, options.Object); var claimsFactory = new UserClaimsPrincipalFactory<PocoUser, PocoRole>(manager.Object, roleManager.Object, options.Object);
var logStore = new StringBuilder(); var logStore = new StringBuilder();
var logger = MockHelpers.MockILogger<SignInManager<TestUser>>(logStore); var logger = MockHelpers.MockILogger<SignInManager<PocoUser>>(logStore);
var helper = new SignInManager<TestUser>(manager.Object, contextAccessor.Object, claimsFactory, options.Object, logger.Object, new Mock<IAuthenticationSchemeProvider>().Object); var helper = new SignInManager<PocoUser>(manager.Object, contextAccessor.Object, claimsFactory, options.Object, logger.Object, new Mock<IAuthenticationSchemeProvider>().Object);
// Act // Act
var result = await helper.CheckPasswordSignInAsync(user, "bogus", false); var result = await helper.CheckPasswordSignInAsync(user, "bogus", false);
@ -166,9 +166,9 @@ namespace Microsoft.AspNetCore.Identity.Test
manager.Verify(); manager.Verify();
} }
private static Mock<UserManager<TestUser>> SetupUserManager(TestUser user) private static Mock<UserManager<PocoUser>> SetupUserManager(PocoUser user)
{ {
var manager = MockHelpers.MockUserManager<TestUser>(); var manager = MockHelpers.MockUserManager<PocoUser>();
manager.Setup(m => m.FindByNameAsync(user.UserName)).ReturnsAsync(user); manager.Setup(m => m.FindByNameAsync(user.UserName)).ReturnsAsync(user);
manager.Setup(m => m.FindByIdAsync(user.Id)).ReturnsAsync(user); manager.Setup(m => m.FindByIdAsync(user.Id)).ReturnsAsync(user);
manager.Setup(m => m.GetUserIdAsync(user)).ReturnsAsync(user.Id.ToString()); manager.Setup(m => m.GetUserIdAsync(user)).ReturnsAsync(user.Id.ToString());
@ -176,17 +176,17 @@ namespace Microsoft.AspNetCore.Identity.Test
return manager; return manager;
} }
private static SignInManager<TestUser> SetupSignInManager(UserManager<TestUser> manager, HttpContext context, StringBuilder logStore = null, IdentityOptions identityOptions = null) private static SignInManager<PocoUser> SetupSignInManager(UserManager<PocoUser> manager, HttpContext context, StringBuilder logStore = null, IdentityOptions identityOptions = null)
{ {
var contextAccessor = new Mock<IHttpContextAccessor>(); var contextAccessor = new Mock<IHttpContextAccessor>();
contextAccessor.Setup(a => a.HttpContext).Returns(context); contextAccessor.Setup(a => a.HttpContext).Returns(context);
var roleManager = MockHelpers.MockRoleManager<TestRole>(); var roleManager = MockHelpers.MockRoleManager<PocoRole>();
identityOptions = identityOptions ?? new IdentityOptions(); identityOptions = identityOptions ?? new IdentityOptions();
var options = new Mock<IOptions<IdentityOptions>>(); var options = new Mock<IOptions<IdentityOptions>>();
options.Setup(a => a.Value).Returns(identityOptions); options.Setup(a => a.Value).Returns(identityOptions);
var claimsFactory = new UserClaimsPrincipalFactory<TestUser, TestRole>(manager, roleManager.Object, options.Object); var claimsFactory = new UserClaimsPrincipalFactory<PocoUser, PocoRole>(manager, roleManager.Object, options.Object);
var sm = new SignInManager<TestUser>(manager, contextAccessor.Object, claimsFactory, options.Object, null, new Mock<IAuthenticationSchemeProvider>().Object); var sm = new SignInManager<PocoUser>(manager, contextAccessor.Object, claimsFactory, options.Object, null, new Mock<IAuthenticationSchemeProvider>().Object);
sm.Logger = MockHelpers.MockILogger<SignInManager<TestUser>>(logStore ?? new StringBuilder()).Object; sm.Logger = MockHelpers.MockILogger<SignInManager<PocoUser>>(logStore ?? new StringBuilder()).Object;
return sm; return sm;
} }
@ -196,7 +196,7 @@ namespace Microsoft.AspNetCore.Identity.Test
public async Task CanPasswordSignIn(bool isPersistent) public async Task CanPasswordSignIn(bool isPersistent)
{ {
// Setup // Setup
var user = new TestUser { UserName = "Foo" }; var user = new PocoUser { UserName = "Foo" };
var manager = SetupUserManager(user); var manager = SetupUserManager(user);
manager.Setup(m => m.SupportsUserLockout).Returns(true).Verifiable(); manager.Setup(m => m.SupportsUserLockout).Returns(true).Verifiable();
manager.Setup(m => m.IsLockedOutAsync(user)).ReturnsAsync(false).Verifiable(); manager.Setup(m => m.IsLockedOutAsync(user)).ReturnsAsync(false).Verifiable();
@ -220,7 +220,7 @@ namespace Microsoft.AspNetCore.Identity.Test
public async Task CanPasswordSignInWithNoLogger() public async Task CanPasswordSignInWithNoLogger()
{ {
// Setup // Setup
var user = new TestUser { UserName = "Foo" }; var user = new PocoUser { UserName = "Foo" };
var manager = SetupUserManager(user); var manager = SetupUserManager(user);
manager.Setup(m => m.SupportsUserLockout).Returns(true).Verifiable(); manager.Setup(m => m.SupportsUserLockout).Returns(true).Verifiable();
manager.Setup(m => m.IsLockedOutAsync(user)).ReturnsAsync(false).Verifiable(); manager.Setup(m => m.IsLockedOutAsync(user)).ReturnsAsync(false).Verifiable();
@ -245,7 +245,7 @@ namespace Microsoft.AspNetCore.Identity.Test
public async Task PasswordSignInWorksWithNonTwoFactorStore() public async Task PasswordSignInWorksWithNonTwoFactorStore()
{ {
// Setup // Setup
var user = new TestUser { UserName = "Foo" }; var user = new PocoUser { UserName = "Foo" };
var manager = SetupUserManager(user); var manager = SetupUserManager(user);
manager.Setup(m => m.SupportsUserLockout).Returns(true).Verifiable(); manager.Setup(m => m.SupportsUserLockout).Returns(true).Verifiable();
manager.Setup(m => m.IsLockedOutAsync(user)).ReturnsAsync(false).Verifiable(); manager.Setup(m => m.IsLockedOutAsync(user)).ReturnsAsync(false).Verifiable();
@ -272,7 +272,7 @@ namespace Microsoft.AspNetCore.Identity.Test
public async Task PasswordSignInRequiresVerification(bool supportsLockout) public async Task PasswordSignInRequiresVerification(bool supportsLockout)
{ {
// Setup // Setup
var user = new TestUser { UserName = "Foo" }; var user = new PocoUser { UserName = "Foo" };
var manager = SetupUserManager(user); var manager = SetupUserManager(user);
manager.Setup(m => m.SupportsUserLockout).Returns(supportsLockout).Verifiable(); manager.Setup(m => m.SupportsUserLockout).Returns(supportsLockout).Verifiable();
if (supportsLockout) if (supportsLockout)
@ -312,7 +312,7 @@ namespace Microsoft.AspNetCore.Identity.Test
public async Task ExternalSignInRequiresVerificationIfNotBypassed(bool bypass) public async Task ExternalSignInRequiresVerificationIfNotBypassed(bool bypass)
{ {
// Setup // Setup
var user = new TestUser { UserName = "Foo" }; var user = new PocoUser { UserName = "Foo" };
const string loginProvider = "login"; const string loginProvider = "login";
const string providerKey = "fookey"; const string providerKey = "fookey";
var manager = SetupUserManager(user); var manager = SetupUserManager(user);
@ -351,9 +351,9 @@ namespace Microsoft.AspNetCore.Identity.Test
auth.Verify(); auth.Verify();
} }
private class GoodTokenProvider : AuthenticatorTokenProvider<TestUser> private class GoodTokenProvider : AuthenticatorTokenProvider<PocoUser>
{ {
public override Task<bool> ValidateAsync(string purpose, string token, UserManager<TestUser> manager, TestUser user) public override Task<bool> ValidateAsync(string purpose, string token, UserManager<PocoUser> manager, PocoUser user)
{ {
return Task.FromResult(true); return Task.FromResult(true);
} }
@ -368,7 +368,7 @@ namespace Microsoft.AspNetCore.Identity.Test
public async Task CanTwoFactorAuthenticatorSignIn(string providerName, bool isPersistent, bool rememberClient) public async Task CanTwoFactorAuthenticatorSignIn(string providerName, bool isPersistent, bool rememberClient)
{ {
// Setup // Setup
var user = new TestUser { UserName = "Foo" }; var user = new PocoUser { UserName = "Foo" };
const string code = "3123"; const string code = "3123";
var manager = SetupUserManager(user); var manager = SetupUserManager(user);
manager.Setup(m => m.SupportsUserLockout).Returns(true).Verifiable(); manager.Setup(m => m.SupportsUserLockout).Returns(true).Verifiable();
@ -378,7 +378,7 @@ namespace Microsoft.AspNetCore.Identity.Test
var context = new DefaultHttpContext(); var context = new DefaultHttpContext();
var auth = MockAuth(context); var auth = MockAuth(context);
var helper = SetupSignInManager(manager.Object, context); var helper = SetupSignInManager(manager.Object, context);
var twoFactorInfo = new SignInManager<TestUser>.TwoFactorAuthenticationInfo { UserId = user.Id }; var twoFactorInfo = new SignInManager<PocoUser>.TwoFactorAuthenticationInfo { UserId = user.Id };
if (providerName != null) if (providerName != null)
{ {
helper.Options.Tokens.AuthenticatorTokenProvider = providerName; helper.Options.Tokens.AuthenticatorTokenProvider = providerName;
@ -413,7 +413,7 @@ namespace Microsoft.AspNetCore.Identity.Test
public async Task CanTwoFactorRecoveryCodeSignIn(bool supportsLockout, bool externalLogin) public async Task CanTwoFactorRecoveryCodeSignIn(bool supportsLockout, bool externalLogin)
{ {
// Setup // Setup
var user = new TestUser { UserName = "Foo" }; var user = new PocoUser { UserName = "Foo" };
const string bypassCode = "someCode"; const string bypassCode = "someCode";
var manager = SetupUserManager(user); var manager = SetupUserManager(user);
manager.Setup(m => m.SupportsUserLockout).Returns(supportsLockout).Verifiable(); manager.Setup(m => m.SupportsUserLockout).Returns(supportsLockout).Verifiable();
@ -425,7 +425,7 @@ namespace Microsoft.AspNetCore.Identity.Test
var context = new DefaultHttpContext(); var context = new DefaultHttpContext();
var auth = MockAuth(context); var auth = MockAuth(context);
var helper = SetupSignInManager(manager.Object, context); var helper = SetupSignInManager(manager.Object, context);
var twoFactorInfo = new SignInManager<TestUser>.TwoFactorAuthenticationInfo { UserId = user.Id }; var twoFactorInfo = new SignInManager<PocoUser>.TwoFactorAuthenticationInfo { UserId = user.Id };
var loginProvider = "loginprovider"; var loginProvider = "loginprovider";
var id = helper.StoreTwoFactorInfo(user.Id, externalLogin ? loginProvider : null); var id = helper.StoreTwoFactorInfo(user.Id, externalLogin ? loginProvider : null);
if (externalLogin) if (externalLogin)
@ -462,7 +462,7 @@ namespace Microsoft.AspNetCore.Identity.Test
public async Task CanExternalSignIn(bool isPersistent, bool supportsLockout) public async Task CanExternalSignIn(bool isPersistent, bool supportsLockout)
{ {
// Setup // Setup
var user = new TestUser { UserName = "Foo" }; var user = new PocoUser { UserName = "Foo" };
const string loginProvider = "login"; const string loginProvider = "login";
const string providerKey = "fookey"; const string providerKey = "fookey";
var manager = SetupUserManager(user); var manager = SetupUserManager(user);
@ -501,7 +501,7 @@ namespace Microsoft.AspNetCore.Identity.Test
bool externalLogin) bool externalLogin)
{ {
// Setup // Setup
var user = new TestUser { UserName = "Foo" }; var user = new PocoUser { UserName = "Foo" };
var context = new DefaultHttpContext(); var context = new DefaultHttpContext();
var auth = MockAuth(context); var auth = MockAuth(context);
var loginProvider = "loginprovider"; var loginProvider = "loginprovider";
@ -516,9 +516,9 @@ namespace Microsoft.AspNetCore.Identity.Test
auth.Setup(a => a.AuthenticateAsync(context, IdentityConstants.ApplicationScheme)) auth.Setup(a => a.AuthenticateAsync(context, IdentityConstants.ApplicationScheme))
.Returns(Task.FromResult(authResult)).Verifiable(); .Returns(Task.FromResult(authResult)).Verifiable();
var manager = SetupUserManager(user); var manager = SetupUserManager(user);
var signInManager = new Mock<SignInManager<TestUser>>(manager.Object, var signInManager = new Mock<SignInManager<PocoUser>>(manager.Object,
new HttpContextAccessor { HttpContext = context }, new HttpContextAccessor { HttpContext = context },
new Mock<IUserClaimsPrincipalFactory<TestUser>>().Object, new Mock<IUserClaimsPrincipalFactory<PocoUser>>().Object,
null, null, new Mock<IAuthenticationSchemeProvider>().Object) null, null, new Mock<IAuthenticationSchemeProvider>().Object)
{ CallBase = true }; { CallBase = true };
//signInManager.Setup(s => s.SignInAsync(user, It.Is<AuthenticationProperties>(p => p.IsPersistent == isPersistent), //signInManager.Setup(s => s.SignInAsync(user, It.Is<AuthenticationProperties>(p => p.IsPersistent == isPersistent),
@ -554,7 +554,7 @@ namespace Microsoft.AspNetCore.Identity.Test
public async Task CanTwoFactorSignIn(bool isPersistent, bool supportsLockout, bool externalLogin, bool rememberClient) public async Task CanTwoFactorSignIn(bool isPersistent, bool supportsLockout, bool externalLogin, bool rememberClient)
{ {
// Setup // Setup
var user = new TestUser { UserName = "Foo" }; var user = new PocoUser { UserName = "Foo" };
var manager = SetupUserManager(user); var manager = SetupUserManager(user);
var provider = "twofactorprovider"; var provider = "twofactorprovider";
var code = "123456"; var code = "123456";
@ -568,7 +568,7 @@ namespace Microsoft.AspNetCore.Identity.Test
var context = new DefaultHttpContext(); var context = new DefaultHttpContext();
var auth = MockAuth(context); var auth = MockAuth(context);
var helper = SetupSignInManager(manager.Object, context); var helper = SetupSignInManager(manager.Object, context);
var twoFactorInfo = new SignInManager<TestUser>.TwoFactorAuthenticationInfo { UserId = user.Id }; var twoFactorInfo = new SignInManager<PocoUser>.TwoFactorAuthenticationInfo { UserId = user.Id };
var loginProvider = "loginprovider"; var loginProvider = "loginprovider";
var id = helper.StoreTwoFactorInfo(user.Id, externalLogin ? loginProvider : null); var id = helper.StoreTwoFactorInfo(user.Id, externalLogin ? loginProvider : null);
if (externalLogin) if (externalLogin)
@ -612,7 +612,7 @@ namespace Microsoft.AspNetCore.Identity.Test
public async Task RememberClientStoresUserId() public async Task RememberClientStoresUserId()
{ {
// Setup // Setup
var user = new TestUser { UserName = "Foo" }; var user = new PocoUser { UserName = "Foo" };
var manager = SetupUserManager(user); var manager = SetupUserManager(user);
var context = new DefaultHttpContext(); var context = new DefaultHttpContext();
var auth = MockAuth(context); var auth = MockAuth(context);
@ -639,7 +639,7 @@ namespace Microsoft.AspNetCore.Identity.Test
public async Task RememberBrowserSkipsTwoFactorVerificationSignIn(bool isPersistent) public async Task RememberBrowserSkipsTwoFactorVerificationSignIn(bool isPersistent)
{ {
// Setup // Setup
var user = new TestUser { UserName = "Foo" }; var user = new PocoUser { UserName = "Foo" };
var manager = SetupUserManager(user); var manager = SetupUserManager(user);
manager.Setup(m => m.GetTwoFactorEnabledAsync(user)).ReturnsAsync(true).Verifiable(); manager.Setup(m => m.GetTwoFactorEnabledAsync(user)).ReturnsAsync(true).Verifiable();
IList<string> providers = new List<string>(); IList<string> providers = new List<string>();
@ -678,7 +678,7 @@ namespace Microsoft.AspNetCore.Identity.Test
public async Task SignOutCallsContextResponseSignOut() public async Task SignOutCallsContextResponseSignOut()
{ {
// Setup // Setup
var manager = MockHelpers.TestUserManager<TestUser>(); var manager = MockHelpers.TestUserManager<PocoUser>();
var context = new DefaultHttpContext(); var context = new DefaultHttpContext();
var auth = MockAuth(context); var auth = MockAuth(context);
auth.Setup(a => a.SignOutAsync(context, IdentityConstants.ApplicationScheme, It.IsAny<AuthenticationProperties>())).Returns(Task.FromResult(0)).Verifiable(); auth.Setup(a => a.SignOutAsync(context, IdentityConstants.ApplicationScheme, It.IsAny<AuthenticationProperties>())).Returns(Task.FromResult(0)).Verifiable();
@ -697,7 +697,7 @@ namespace Microsoft.AspNetCore.Identity.Test
public async Task PasswordSignInFailsWithWrongPassword() public async Task PasswordSignInFailsWithWrongPassword()
{ {
// Setup // Setup
var user = new TestUser { UserName = "Foo" }; var user = new PocoUser { UserName = "Foo" };
var manager = SetupUserManager(user); var manager = SetupUserManager(user);
manager.Setup(m => m.SupportsUserLockout).Returns(true).Verifiable(); manager.Setup(m => m.SupportsUserLockout).Returns(true).Verifiable();
manager.Setup(m => m.IsLockedOutAsync(user)).ReturnsAsync(false).Verifiable(); manager.Setup(m => m.IsLockedOutAsync(user)).ReturnsAsync(false).Verifiable();
@ -721,8 +721,8 @@ namespace Microsoft.AspNetCore.Identity.Test
public async Task PasswordSignInFailsWithUnknownUser() public async Task PasswordSignInFailsWithUnknownUser()
{ {
// Setup // Setup
var manager = MockHelpers.MockUserManager<TestUser>(); var manager = MockHelpers.MockUserManager<PocoUser>();
manager.Setup(m => m.FindByNameAsync("bogus")).ReturnsAsync(default(TestUser)).Verifiable(); manager.Setup(m => m.FindByNameAsync("bogus")).ReturnsAsync(default(PocoUser)).Verifiable();
var context = new Mock<HttpContext>(); var context = new Mock<HttpContext>();
var helper = SetupSignInManager(manager.Object, context.Object); var helper = SetupSignInManager(manager.Object, context.Object);
@ -739,7 +739,7 @@ namespace Microsoft.AspNetCore.Identity.Test
public async Task PasswordSignInFailsWithWrongPasswordCanAccessFailedAndLockout() public async Task PasswordSignInFailsWithWrongPasswordCanAccessFailedAndLockout()
{ {
// Setup // Setup
var user = new TestUser { UserName = "Foo" }; var user = new PocoUser { UserName = "Foo" };
var manager = SetupUserManager(user); var manager = SetupUserManager(user);
var lockedout = false; var lockedout = false;
manager.Setup(m => m.AccessFailedAsync(user)).Returns(() => manager.Setup(m => m.AccessFailedAsync(user)).Returns(() =>
@ -766,7 +766,7 @@ namespace Microsoft.AspNetCore.Identity.Test
public async Task CheckPasswordSignInFailsWithWrongPasswordCanAccessFailedAndLockout() public async Task CheckPasswordSignInFailsWithWrongPasswordCanAccessFailedAndLockout()
{ {
// Setup // Setup
var user = new TestUser { UserName = "Foo" }; var user = new PocoUser { UserName = "Foo" };
var manager = SetupUserManager(user); var manager = SetupUserManager(user);
var lockedout = false; var lockedout = false;
manager.Setup(m => m.AccessFailedAsync(user)).Returns(() => manager.Setup(m => m.AccessFailedAsync(user)).Returns(() =>
@ -795,7 +795,7 @@ namespace Microsoft.AspNetCore.Identity.Test
public async Task CanRequireConfirmedEmailForPasswordSignIn(bool confirmed) public async Task CanRequireConfirmedEmailForPasswordSignIn(bool confirmed)
{ {
// Setup // Setup
var user = new TestUser { UserName = "Foo" }; var user = new PocoUser { UserName = "Foo" };
var manager = SetupUserManager(user); var manager = SetupUserManager(user);
manager.Setup(m => m.IsEmailConfirmedAsync(user)).ReturnsAsync(confirmed).Verifiable(); manager.Setup(m => m.IsEmailConfirmedAsync(user)).ReturnsAsync(confirmed).Verifiable();
if (confirmed) if (confirmed)
@ -843,7 +843,7 @@ namespace Microsoft.AspNetCore.Identity.Test
public async Task CanRequireConfirmedPhoneNumberForPasswordSignIn(bool confirmed) public async Task CanRequireConfirmedPhoneNumberForPasswordSignIn(bool confirmed)
{ {
// Setup // Setup
var user = new TestUser { UserName = "Foo" }; var user = new PocoUser { UserName = "Foo" };
var manager = SetupUserManager(user); var manager = SetupUserManager(user);
manager.Setup(m => m.IsPhoneNumberConfirmedAsync(user)).ReturnsAsync(confirmed).Verifiable(); manager.Setup(m => m.IsPhoneNumberConfirmedAsync(user)).ReturnsAsync(confirmed).Verifiable();
var context = new DefaultHttpContext(); var context = new DefaultHttpContext();

View File

@ -17,14 +17,14 @@ namespace Microsoft.AspNetCore.Identity.Test
[Fact] [Fact]
public async Task CreateIdentityNullChecks() public async Task CreateIdentityNullChecks()
{ {
var userManager = MockHelpers.MockUserManager<TestUser>().Object; var userManager = MockHelpers.MockUserManager<PocoUser>().Object;
var roleManager = MockHelpers.MockRoleManager<TestRole>().Object; var roleManager = MockHelpers.MockRoleManager<PocoRole>().Object;
var options = new Mock<IOptions<IdentityOptions>>(); var options = new Mock<IOptions<IdentityOptions>>();
Assert.Throws<ArgumentNullException>("optionsAccessor", Assert.Throws<ArgumentNullException>("optionsAccessor",
() => new UserClaimsPrincipalFactory<TestUser, TestRole>(userManager, roleManager, options.Object)); () => new UserClaimsPrincipalFactory<PocoUser, PocoRole>(userManager, roleManager, options.Object));
var identityOptions = new IdentityOptions(); var identityOptions = new IdentityOptions();
options.Setup(a => a.Value).Returns(identityOptions); options.Setup(a => a.Value).Returns(identityOptions);
var factory = new UserClaimsPrincipalFactory<TestUser, TestRole>(userManager, roleManager, options.Object); var factory = new UserClaimsPrincipalFactory<PocoUser, PocoRole>(userManager, roleManager, options.Object);
await Assert.ThrowsAsync<ArgumentNullException>("user", await Assert.ThrowsAsync<ArgumentNullException>("user",
async () => await factory.CreateAsync(null)); async () => await factory.CreateAsync(null));
} }
@ -39,9 +39,9 @@ namespace Microsoft.AspNetCore.Identity.Test
public async Task EnsureClaimsIdentityHasExpectedClaims(bool supportRoles, bool supportClaims, bool supportRoleClaims) public async Task EnsureClaimsIdentityHasExpectedClaims(bool supportRoles, bool supportClaims, bool supportRoleClaims)
{ {
// Setup // Setup
var userManager = MockHelpers.MockUserManager<TestUser>(); var userManager = MockHelpers.MockUserManager<PocoUser>();
var roleManager = MockHelpers.MockRoleManager<TestRole>(); var roleManager = MockHelpers.MockRoleManager<PocoRole>();
var user = new TestUser { UserName = "Foo" }; var user = new PocoUser { UserName = "Foo" };
userManager.Setup(m => m.SupportsUserClaim).Returns(supportClaims); userManager.Setup(m => m.SupportsUserClaim).Returns(supportClaims);
userManager.Setup(m => m.SupportsUserRole).Returns(supportRoles); userManager.Setup(m => m.SupportsUserRole).Returns(supportRoles);
userManager.Setup(m => m.GetUserIdAsync(user)).ReturnsAsync(user.Id); userManager.Setup(m => m.GetUserIdAsync(user)).ReturnsAsync(user.Id);
@ -59,8 +59,8 @@ namespace Microsoft.AspNetCore.Identity.Test
} }
userManager.Object.Options = new IdentityOptions(); userManager.Object.Options = new IdentityOptions();
var admin = new TestRole() { Name = "Admin" }; var admin = new PocoRole() { Name = "Admin" };
var local = new TestRole() { Name = "Local" }; var local = new PocoRole() { Name = "Local" };
var adminClaims = new[] { new Claim("AdminClaim1", "Value1"), new Claim("AdminClaim2", "Value2") }; var adminClaims = new[] { new Claim("AdminClaim1", "Value1"), new Claim("AdminClaim2", "Value2") };
var localClaims = new[] { new Claim("LocalClaim1", "Value1"), new Claim("LocalClaim2", "Value2") }; var localClaims = new[] { new Claim("LocalClaim1", "Value1"), new Claim("LocalClaim2", "Value2") };
if (supportRoleClaims) if (supportRoleClaims)
@ -74,7 +74,7 @@ namespace Microsoft.AspNetCore.Identity.Test
var options = new Mock<IOptions<IdentityOptions>>(); var options = new Mock<IOptions<IdentityOptions>>();
var identityOptions = new IdentityOptions(); var identityOptions = new IdentityOptions();
options.Setup(a => a.Value).Returns(identityOptions); options.Setup(a => a.Value).Returns(identityOptions);
var factory = new UserClaimsPrincipalFactory<TestUser, TestRole>(userManager.Object, roleManager.Object, options.Object); var factory = new UserClaimsPrincipalFactory<PocoUser, PocoRole>(userManager.Object, roleManager.Object, options.Object);
// Act // Act
var principal = await factory.CreateAsync(user); var principal = await factory.CreateAsync(user);

File diff suppressed because it is too large Load Diff

View File

@ -14,7 +14,7 @@ namespace Microsoft.AspNetCore.Identity.Test
{ {
// Setup // Setup
var manager = MockHelpers.TestUserManager(new NoopUserStore()); var manager = MockHelpers.TestUserManager(new NoopUserStore());
var validator = new UserValidator<TestUser>(); var validator = new UserValidator<PocoUser>();
// Act // Act
// Assert // Assert
@ -29,8 +29,8 @@ namespace Microsoft.AspNetCore.Identity.Test
{ {
// Setup // Setup
var manager = MockHelpers.TestUserManager(new NoopUserStore()); var manager = MockHelpers.TestUserManager(new NoopUserStore());
var validator = new UserValidator<TestUser>(); var validator = new UserValidator<PocoUser>();
var user = new TestUser {UserName = input}; var user = new PocoUser {UserName = input};
// Act // Act
var result = await validator.ValidateAsync(manager, user); var result = await validator.ValidateAsync(manager, user);
@ -51,8 +51,8 @@ namespace Microsoft.AspNetCore.Identity.Test
{ {
// Setup // Setup
var manager = MockHelpers.TestUserManager(new NoopUserStore()); var manager = MockHelpers.TestUserManager(new NoopUserStore());
var validator = new UserValidator<TestUser>(); var validator = new UserValidator<PocoUser>();
var user = new TestUser {UserName = userName}; var user = new PocoUser {UserName = userName};
// Act // Act
var result = await validator.ValidateAsync(manager, user); var result = await validator.ValidateAsync(manager, user);
@ -79,8 +79,8 @@ namespace Microsoft.AspNetCore.Identity.Test
// Setup // Setup
var manager = MockHelpers.TestUserManager(new NoopUserStore()); var manager = MockHelpers.TestUserManager(new NoopUserStore());
manager.Options.User.AllowedUserNameCharacters = null; manager.Options.User.AllowedUserNameCharacters = null;
var validator = new UserValidator<TestUser>(); var validator = new UserValidator<PocoUser>();
var user = new TestUser {UserName = userName}; var user = new PocoUser {UserName = userName};
// Act // Act
var result = await validator.ValidateAsync(manager, user); var result = await validator.ValidateAsync(manager, user);

View File

@ -35,20 +35,20 @@ namespace Microsoft.AspNetCore.Identity.InMemory.Test
.AddLogging() .AddLogging()
.AddSingleton(contextAccessor.Object); .AddSingleton(contextAccessor.Object);
services.AddIdentity<TestUser, TestRole>(); services.AddIdentity<PocoUser, PocoRole>();
services.AddSingleton<IUserStore<TestUser>, InMemoryStore<TestUser, TestRole>>(); services.AddSingleton<IUserStore<PocoUser>, InMemoryStore<PocoUser, PocoRole>>();
services.AddSingleton<IRoleStore<TestRole>, InMemoryStore<TestUser, TestRole>>(); services.AddSingleton<IRoleStore<PocoRole>, InMemoryStore<PocoUser, PocoRole>>();
var app = new ApplicationBuilder(services.BuildServiceProvider()); var app = new ApplicationBuilder(services.BuildServiceProvider());
// Act // Act
var user = new TestUser var user = new PocoUser
{ {
UserName = "Yolo" UserName = "Yolo"
}; };
const string password = "Yol0Sw@g!"; const string password = "Yol0Sw@g!";
var userManager = app.ApplicationServices.GetRequiredService<UserManager<TestUser>>(); var userManager = app.ApplicationServices.GetRequiredService<UserManager<PocoUser>>();
var signInManager = app.ApplicationServices.GetRequiredService<SignInManager<TestUser>>(); var signInManager = app.ApplicationServices.GetRequiredService<SignInManager<PocoUser>>();
IdentityResultAssert.IsSuccess(await userManager.CreateAsync(user, password)); IdentityResultAssert.IsSuccess(await userManager.CreateAsync(user, password));
@ -86,19 +86,19 @@ namespace Microsoft.AspNetCore.Identity.InMemory.Test
.AddSingleton<IConfiguration>(new ConfigurationBuilder().Build()) .AddSingleton<IConfiguration>(new ConfigurationBuilder().Build())
.AddLogging() .AddLogging()
.AddSingleton(contextAccessor.Object); .AddSingleton(contextAccessor.Object);
services.AddIdentity<TestUser, TestRole>(); services.AddIdentity<PocoUser, PocoRole>();
services.AddSingleton<IUserStore<TestUser>, InMemoryStore<TestUser, TestRole>>(); services.AddSingleton<IUserStore<PocoUser>, InMemoryStore<PocoUser, PocoRole>>();
services.AddSingleton<IRoleStore<TestRole>, InMemoryStore<TestUser, TestRole>>(); services.AddSingleton<IRoleStore<PocoRole>, InMemoryStore<PocoUser, PocoRole>>();
var app = new ApplicationBuilder(services.BuildServiceProvider()); var app = new ApplicationBuilder(services.BuildServiceProvider());
// Act // Act
var user = new TestUser var user = new PocoUser
{ {
UserName = "Yolo" UserName = "Yolo"
}; };
var userManager = app.ApplicationServices.GetRequiredService<UserManager<TestUser>>(); var userManager = app.ApplicationServices.GetRequiredService<UserManager<PocoUser>>();
var signInManager = app.ApplicationServices.GetRequiredService<SignInManager<TestUser>>(); var signInManager = app.ApplicationServices.GetRequiredService<SignInManager<PocoUser>>();
IdentityResultAssert.IsSuccess(await userManager.CreateAsync(user)); IdentityResultAssert.IsSuccess(await userManager.CreateAsync(user));
IdentityResultAssert.IsSuccess(await userManager.AddLoginAsync(user, new UserLoginInfo(authScheme, externalId, "whatever"))); IdentityResultAssert.IsSuccess(await userManager.AddLoginAsync(user, new UserLoginInfo(authScheme, externalId, "whatever")));

View File

@ -273,8 +273,8 @@ namespace Microsoft.AspNetCore.Identity.InMemory
{ {
var req = context.Request; var req = context.Request;
var res = context.Response; var res = context.Response;
var userManager = context.RequestServices.GetRequiredService<UserManager<TestUser>>(); var userManager = context.RequestServices.GetRequiredService<UserManager<PocoUser>>();
var signInManager = context.RequestServices.GetRequiredService<SignInManager<TestUser>>(); var signInManager = context.RequestServices.GetRequiredService<SignInManager<PocoUser>>();
PathString remainder; PathString remainder;
if (req.Path == new PathString("/normal")) if (req.Path == new PathString("/normal"))
{ {
@ -282,12 +282,12 @@ namespace Microsoft.AspNetCore.Identity.InMemory
} }
else if (req.Path == new PathString("/createMe")) else if (req.Path == new PathString("/createMe"))
{ {
var result = await userManager.CreateAsync(new TestUser("hao"), TestPassword); var result = await userManager.CreateAsync(new PocoUser("hao"), TestPassword);
res.StatusCode = result.Succeeded ? 200 : 500; res.StatusCode = result.Succeeded ? 200 : 500;
} }
else if (req.Path == new PathString("/createSimple")) else if (req.Path == new PathString("/createSimple"))
{ {
var result = await userManager.CreateAsync(new TestUser("simple"), "aaaaaa"); var result = await userManager.CreateAsync(new PocoUser("simple"), "aaaaaa");
res.StatusCode = result.Succeeded ? 200 : 500; res.StatusCode = result.Succeeded ? 200 : 500;
} }
else if (req.Path == new PathString("/signoutEverywhere")) else if (req.Path == new PathString("/signoutEverywhere"))
@ -340,9 +340,9 @@ namespace Microsoft.AspNetCore.Identity.InMemory
}) })
.ConfigureServices(services => .ConfigureServices(services =>
{ {
services.AddIdentity<TestUser, TestRole>().AddDefaultTokenProviders(); services.AddIdentity<PocoUser, PocoRole>().AddDefaultTokenProviders();
services.AddSingleton<IUserStore<TestUser>, InMemoryStore<TestUser, TestRole>>(); services.AddSingleton<IUserStore<PocoUser>, InMemoryStore<PocoUser, PocoRole>>();
services.AddSingleton<IRoleStore<TestRole>, InMemoryStore<TestUser, TestRole>>(); services.AddSingleton<IRoleStore<PocoRole>, InMemoryStore<PocoUser, PocoRole>>();
configureServices?.Invoke(services); configureServices?.Invoke(services);
}); });
var server = new TestServer(builder); var server = new TestServer(builder);

View File

@ -16,8 +16,8 @@ namespace Microsoft.AspNetCore.Identity.InMemory
IUserRoleStore<TUser>, IUserRoleStore<TUser>,
IQueryableRoleStore<TRole>, IQueryableRoleStore<TRole>,
IRoleClaimStore<TRole> IRoleClaimStore<TRole>
where TRole : TestRole where TRole : PocoRole
where TUser : TestUser where TUser : PocoUser
{ {
// RoleId == roleName for InMemory // RoleId == roleName for InMemory
public Task AddToRoleAsync(TUser user, string role, CancellationToken cancellationToken = default(CancellationToken)) public Task AddToRoleAsync(TUser user, string role, CancellationToken cancellationToken = default(CancellationToken))
@ -25,7 +25,7 @@ namespace Microsoft.AspNetCore.Identity.InMemory
var roleEntity = _roles.Values.SingleOrDefault(r => r.NormalizedName == role); var roleEntity = _roles.Values.SingleOrDefault(r => r.NormalizedName == role);
if (roleEntity != null) if (roleEntity != null)
{ {
user.Roles.Add(new TestUserRole { RoleId = roleEntity.Id, UserId = user.Id }); user.Roles.Add(new PocoUserRole { RoleId = roleEntity.Id, UserId = user.Id });
} }
return Task.FromResult(0); return Task.FromResult(0);
} }
@ -139,7 +139,7 @@ namespace Microsoft.AspNetCore.Identity.InMemory
public Task AddClaimAsync(TRole role, Claim claim, CancellationToken cancellationToken = default(CancellationToken)) public Task AddClaimAsync(TRole role, Claim claim, CancellationToken cancellationToken = default(CancellationToken))
{ {
role.Claims.Add(new TestRoleClaim<string> { ClaimType = claim.Type, ClaimValue = claim.Value, RoleId = role.Id }); role.Claims.Add(new PocoRoleClaim<string> { ClaimType = claim.Type, ClaimValue = claim.Value, RoleId = role.Id });
return Task.FromResult(0); return Task.FromResult(0);
} }

View File

@ -8,32 +8,32 @@ using Microsoft.Extensions.DependencyInjection;
namespace Microsoft.AspNetCore.Identity.InMemory.Test namespace Microsoft.AspNetCore.Identity.InMemory.Test
{ {
public class InMemoryStoreTest : IdentitySpecificationTestBase<TestUser, TestRole> public class InMemoryStoreTest : IdentitySpecificationTestBase<PocoUser, PocoRole>
{ {
protected override object CreateTestContext() protected override object CreateTestContext()
{ {
return new InMemoryStore<TestUser, TestRole>(); return new InMemoryStore<PocoUser, PocoRole>();
} }
protected override void AddUserStore(IServiceCollection services, object context = null) protected override void AddUserStore(IServiceCollection services, object context = null)
{ {
services.AddSingleton<IUserStore<TestUser>>((InMemoryStore<TestUser, TestRole>)context); services.AddSingleton<IUserStore<PocoUser>>((InMemoryStore<PocoUser, PocoRole>)context);
} }
protected override void AddRoleStore(IServiceCollection services, object context = null) protected override void AddRoleStore(IServiceCollection services, object context = null)
{ {
services.AddSingleton<IRoleStore<TestRole>>((InMemoryStore<TestUser, TestRole>)context); services.AddSingleton<IRoleStore<PocoRole>>((InMemoryStore<PocoUser, PocoRole>)context);
} }
protected override void SetUserPasswordHash(TestUser user, string hashedPassword) protected override void SetUserPasswordHash(PocoUser user, string hashedPassword)
{ {
user.PasswordHash = hashedPassword; user.PasswordHash = hashedPassword;
} }
protected override TestUser CreateTestUser(string namePrefix = "", string email = "", string phoneNumber = "", protected override PocoUser CreateTestUser(string namePrefix = "", string email = "", string phoneNumber = "",
bool lockoutEnabled = false, DateTimeOffset? lockoutEnd = default(DateTimeOffset?), bool useNamePrefixAsUserName = false) bool lockoutEnabled = false, DateTimeOffset? lockoutEnd = default(DateTimeOffset?), bool useNamePrefixAsUserName = false)
{ {
return new TestUser return new PocoUser
{ {
UserName = useNamePrefixAsUserName ? namePrefix : string.Format("{0}{1}", namePrefix, Guid.NewGuid()), UserName = useNamePrefixAsUserName ? namePrefix : string.Format("{0}{1}", namePrefix, Guid.NewGuid()),
Email = email, Email = email,
@ -43,18 +43,18 @@ namespace Microsoft.AspNetCore.Identity.InMemory.Test
}; };
} }
protected override TestRole CreateTestRole(string roleNamePrefix = "", bool useRoleNamePrefixAsRoleName = false) protected override PocoRole CreateTestRole(string roleNamePrefix = "", bool useRoleNamePrefixAsRoleName = false)
{ {
var roleName = useRoleNamePrefixAsRoleName ? roleNamePrefix : string.Format("{0}{1}", roleNamePrefix, Guid.NewGuid()); var roleName = useRoleNamePrefixAsRoleName ? roleNamePrefix : string.Format("{0}{1}", roleNamePrefix, Guid.NewGuid());
return new TestRole(roleName); return new PocoRole(roleName);
} }
protected override Expression<Func<TestUser, bool>> UserNameEqualsPredicate(string userName) => u => u.UserName == userName; protected override Expression<Func<PocoUser, bool>> UserNameEqualsPredicate(string userName) => u => u.UserName == userName;
protected override Expression<Func<TestRole, bool>> RoleNameEqualsPredicate(string roleName) => r => r.Name == roleName; protected override Expression<Func<PocoRole, bool>> RoleNameEqualsPredicate(string roleName) => r => r.Name == roleName;
protected override Expression<Func<TestUser, bool>> UserNameStartsWithPredicate(string userName) => u => u.UserName.StartsWith(userName); protected override Expression<Func<PocoUser, bool>> UserNameStartsWithPredicate(string userName) => u => u.UserName.StartsWith(userName);
protected override Expression<Func<TestRole, bool>> RoleNameStartsWithPredicate(string roleName) => r => r.Name.StartsWith(roleName); protected override Expression<Func<PocoRole, bool>> RoleNameStartsWithPredicate(string roleName) => r => r.Name.StartsWith(roleName);
} }
} }

View File

@ -24,7 +24,7 @@ namespace Microsoft.AspNetCore.Identity.InMemory
IUserAuthenticationTokenStore<TUser>, IUserAuthenticationTokenStore<TUser>,
IUserAuthenticatorKeyStore<TUser>, IUserAuthenticatorKeyStore<TUser>,
IUserTwoFactorRecoveryCodeStore<TUser> IUserTwoFactorRecoveryCodeStore<TUser>
where TUser : TestUser where TUser : PocoUser
{ {
private readonly Dictionary<string, TUser> _logins = new Dictionary<string, TUser>(); private readonly Dictionary<string, TUser> _logins = new Dictionary<string, TUser>();
@ -45,7 +45,7 @@ namespace Microsoft.AspNetCore.Identity.InMemory
{ {
foreach (var claim in claims) foreach (var claim in claims)
{ {
user.Claims.Add(new TestUserClaim { ClaimType = claim.Type, ClaimValue = claim.Value, UserId = user.Id }); user.Claims.Add(new PocoUserClaim { ClaimType = claim.Type, ClaimValue = claim.Value, UserId = user.Id });
} }
return Task.FromResult(0); return Task.FromResult(0);
} }
@ -164,7 +164,7 @@ namespace Microsoft.AspNetCore.Identity.InMemory
public virtual Task AddLoginAsync(TUser user, UserLoginInfo login, public virtual Task AddLoginAsync(TUser user, UserLoginInfo login,
CancellationToken cancellationToken = default(CancellationToken)) CancellationToken cancellationToken = default(CancellationToken))
{ {
user.Logins.Add(new TestUserLogin user.Logins.Add(new PocoUserLogin
{ {
UserId = user.Id, UserId = user.Id,
ProviderKey = login.ProviderKey, ProviderKey = login.ProviderKey,
@ -364,7 +364,7 @@ namespace Microsoft.AspNetCore.Identity.InMemory
} }
else else
{ {
user.Tokens.Add(new TestUserToken user.Tokens.Add(new PocoUserToken
{ {
UserId = user.Id, UserId = user.Id,
LoginProvider = loginProvider, LoginProvider = loginProvider,

View File

@ -8,27 +8,27 @@ using Microsoft.Extensions.DependencyInjection;
namespace Microsoft.AspNetCore.Identity.InMemory.Test namespace Microsoft.AspNetCore.Identity.InMemory.Test
{ {
public class InMemoryUserStoreTest : UserManagerSpecificationTestBase<TestUser, string> public class InMemoryUserStoreTest : UserManagerSpecificationTestBase<PocoUser, string>
{ {
protected override object CreateTestContext() protected override object CreateTestContext()
{ {
return new InMemoryUserStore<TestUser>(); return new InMemoryUserStore<PocoUser>();
} }
protected override void AddUserStore(IServiceCollection services, object context = null) protected override void AddUserStore(IServiceCollection services, object context = null)
{ {
services.AddSingleton<IUserStore<TestUser>>((InMemoryUserStore<TestUser>)context); services.AddSingleton<IUserStore<PocoUser>>((InMemoryUserStore<PocoUser>)context);
} }
protected override void SetUserPasswordHash(TestUser user, string hashedPassword) protected override void SetUserPasswordHash(PocoUser user, string hashedPassword)
{ {
user.PasswordHash = hashedPassword; user.PasswordHash = hashedPassword;
} }
protected override TestUser CreateTestUser(string namePrefix = "", string email = "", string phoneNumber = "", protected override PocoUser CreateTestUser(string namePrefix = "", string email = "", string phoneNumber = "",
bool lockoutEnabled = false, DateTimeOffset? lockoutEnd = default(DateTimeOffset?), bool useNamePrefixAsUserName = false) bool lockoutEnabled = false, DateTimeOffset? lockoutEnd = default(DateTimeOffset?), bool useNamePrefixAsUserName = false)
{ {
return new TestUser return new PocoUser
{ {
UserName = useNamePrefixAsUserName ? namePrefix : string.Format("{0}{1}", namePrefix, Guid.NewGuid()), UserName = useNamePrefixAsUserName ? namePrefix : string.Format("{0}{1}", namePrefix, Guid.NewGuid()),
Email = email, Email = email,
@ -38,8 +38,8 @@ namespace Microsoft.AspNetCore.Identity.InMemory.Test
}; };
} }
protected override Expression<Func<TestUser, bool>> UserNameEqualsPredicate(string userName) => u => u.UserName == userName; protected override Expression<Func<PocoUser, bool>> UserNameEqualsPredicate(string userName) => u => u.UserName == userName;
protected override Expression<Func<TestUser, bool>> UserNameStartsWithPredicate(string userName) => u => u.UserName.StartsWith(userName); protected override Expression<Func<PocoUser, bool>> UserNameStartsWithPredicate(string userName) => u => u.UserName.StartsWith(userName);
} }
} }

View File

@ -9,12 +9,12 @@ namespace Microsoft.AspNetCore.Identity.Test
/// <summary> /// <summary>
/// Represents a Role entity /// Represents a Role entity
/// </summary> /// </summary>
public class TestRole : TestRole<string> public class PocoRole : PocoRole<string>
{ {
/// <summary> /// <summary>
/// Constructor /// Constructor
/// </summary> /// </summary>
public TestRole() public PocoRole()
{ {
Id = Guid.NewGuid().ToString(); Id = Guid.NewGuid().ToString();
} }
@ -23,7 +23,7 @@ namespace Microsoft.AspNetCore.Identity.Test
/// Constructor /// Constructor
/// </summary> /// </summary>
/// <param name="roleName"></param> /// <param name="roleName"></param>
public TestRole(string roleName) : this() public PocoRole(string roleName) : this()
{ {
Name = roleName; Name = roleName;
} }
@ -33,18 +33,18 @@ namespace Microsoft.AspNetCore.Identity.Test
/// Represents a Role entity /// Represents a Role entity
/// </summary> /// </summary>
/// <typeparam name="TKey"></typeparam> /// <typeparam name="TKey"></typeparam>
public class TestRole<TKey> where TKey : IEquatable<TKey> public class PocoRole<TKey> where TKey : IEquatable<TKey>
{ {
/// <summary> /// <summary>
/// Constructor /// Constructor
/// </summary> /// </summary>
public TestRole() { } public PocoRole() { }
/// <summary> /// <summary>
/// Constructor /// Constructor
/// </summary> /// </summary>
/// <param name="roleName"></param> /// <param name="roleName"></param>
public TestRole(string roleName) : this() public PocoRole(string roleName) : this()
{ {
Name = roleName; Name = roleName;
} }
@ -57,7 +57,7 @@ namespace Microsoft.AspNetCore.Identity.Test
/// <summary> /// <summary>
/// Navigation property for claims in the role /// Navigation property for claims in the role
/// </summary> /// </summary>
public virtual ICollection<TestRoleClaim<TKey>> Claims { get; private set; } = new List<TestRoleClaim<TKey>>(); public virtual ICollection<PocoRoleClaim<TKey>> Claims { get; private set; } = new List<PocoRoleClaim<TKey>>();
/// <summary> /// <summary>
/// Role name /// Role name

View File

@ -8,13 +8,13 @@ namespace Microsoft.AspNetCore.Identity.Test
/// <summary> /// <summary>
/// EntityType that represents one specific role claim /// EntityType that represents one specific role claim
/// </summary> /// </summary>
public class TestRoleClaim : TestRoleClaim<string> { } public class PocoRoleClaim : PocoRoleClaim<string> { }
/// <summary> /// <summary>
/// EntityType that represents one specific role claim /// EntityType that represents one specific role claim
/// </summary> /// </summary>
/// <typeparam name="TKey"></typeparam> /// <typeparam name="TKey"></typeparam>
public class TestRoleClaim<TKey> where TKey : IEquatable<TKey> public class PocoRoleClaim<TKey> where TKey : IEquatable<TKey>
{ {
/// <summary> /// <summary>
/// Primary key /// Primary key

View File

@ -9,12 +9,12 @@ namespace Microsoft.AspNetCore.Identity.Test
/// <summary> /// <summary>
/// Test user class /// Test user class
/// </summary> /// </summary>
public class TestUser : TestUser<string> public class PocoUser : PocoUser<string>
{ {
/// <summary> /// <summary>
/// Ctor /// Ctor
/// </summary> /// </summary>
public TestUser() public PocoUser()
{ {
Id = Guid.NewGuid().ToString(); Id = Guid.NewGuid().ToString();
} }
@ -23,7 +23,7 @@ namespace Microsoft.AspNetCore.Identity.Test
/// Ctor /// Ctor
/// </summary> /// </summary>
/// <param name="userName"></param> /// <param name="userName"></param>
public TestUser(string userName) : this() public PocoUser(string userName) : this()
{ {
UserName = userName; UserName = userName;
} }
@ -33,18 +33,18 @@ namespace Microsoft.AspNetCore.Identity.Test
/// Test user /// Test user
/// </summary> /// </summary>
/// <typeparam name="TKey"></typeparam> /// <typeparam name="TKey"></typeparam>
public class TestUser<TKey> where TKey : IEquatable<TKey> public class PocoUser<TKey> where TKey : IEquatable<TKey>
{ {
/// <summary> /// <summary>
/// ctor /// ctor
/// </summary> /// </summary>
public TestUser() { } public PocoUser() { }
/// <summary> /// <summary>
/// ctor /// ctor
/// </summary> /// </summary>
/// <param name="userName"></param> /// <param name="userName"></param>
public TestUser(string userName) : this() public PocoUser(string userName) : this()
{ {
UserName = userName; UserName = userName;
} }
@ -52,11 +52,13 @@ namespace Microsoft.AspNetCore.Identity.Test
/// <summary> /// <summary>
/// Id /// Id
/// </summary> /// </summary>
[PersonalData]
public virtual TKey Id { get; set; } public virtual TKey Id { get; set; }
/// <summary> /// <summary>
/// Name /// Name
/// </summary> /// </summary>
[PersonalData]
public virtual string UserName { get; set; } public virtual string UserName { get; set; }
/// <summary> /// <summary>
@ -67,6 +69,7 @@ namespace Microsoft.AspNetCore.Identity.Test
/// <summary> /// <summary>
/// Email /// Email
/// </summary> /// </summary>
[PersonalData]
public virtual string Email { get; set; } public virtual string Email { get; set; }
/// <summary> /// <summary>
@ -77,6 +80,7 @@ namespace Microsoft.AspNetCore.Identity.Test
/// <summary> /// <summary>
/// True if the email is confirmed, default is false /// True if the email is confirmed, default is false
/// </summary> /// </summary>
[PersonalData]
public virtual bool EmailConfirmed { get; set; } public virtual bool EmailConfirmed { get; set; }
/// <summary> /// <summary>
@ -97,16 +101,19 @@ namespace Microsoft.AspNetCore.Identity.Test
/// <summary> /// <summary>
/// PhoneNumber for the user /// PhoneNumber for the user
/// </summary> /// </summary>
[PersonalData]
public virtual string PhoneNumber { get; set; } public virtual string PhoneNumber { get; set; }
/// <summary> /// <summary>
/// True if the phone number is confirmed, default is false /// True if the phone number is confirmed, default is false
/// </summary> /// </summary>
[PersonalData]
public virtual bool PhoneNumberConfirmed { get; set; } public virtual bool PhoneNumberConfirmed { get; set; }
/// <summary> /// <summary>
/// Is two factor enabled for the user /// Is two factor enabled for the user
/// </summary> /// </summary>
[PersonalData]
public virtual bool TwoFactorEnabled { get; set; } public virtual bool TwoFactorEnabled { get; set; }
/// <summary> /// <summary>
@ -127,18 +134,18 @@ namespace Microsoft.AspNetCore.Identity.Test
/// <summary> /// <summary>
/// Navigation property /// Navigation property
/// </summary> /// </summary>
public virtual ICollection<TestUserRole<TKey>> Roles { get; private set; } = new List<TestUserRole<TKey>>(); public virtual ICollection<PocoUserRole<TKey>> Roles { get; private set; } = new List<PocoUserRole<TKey>>();
/// <summary> /// <summary>
/// Navigation property /// Navigation property
/// </summary> /// </summary>
public virtual ICollection<TestUserClaim<TKey>> Claims { get; private set; } = new List<TestUserClaim<TKey>>(); public virtual ICollection<PocoUserClaim<TKey>> Claims { get; private set; } = new List<PocoUserClaim<TKey>>();
/// <summary> /// <summary>
/// Navigation property /// Navigation property
/// </summary> /// </summary>
public virtual ICollection<TestUserLogin<TKey>> Logins { get; private set; } = new List<TestUserLogin<TKey>>(); public virtual ICollection<PocoUserLogin<TKey>> Logins { get; private set; } = new List<PocoUserLogin<TKey>>();
/// <summary> /// <summary>
/// Navigation property /// Navigation property
/// </summary> /// </summary>
public virtual ICollection<TestUserToken<TKey>> Tokens { get; private set; } = new List<TestUserToken<TKey>>(); public virtual ICollection<PocoUserToken<TKey>> Tokens { get; private set; } = new List<PocoUserToken<TKey>>();
} }
} }

View File

@ -8,13 +8,13 @@ namespace Microsoft.AspNetCore.Identity.Test
/// <summary> /// <summary>
/// EntityType that represents one specific user claim /// EntityType that represents one specific user claim
/// </summary> /// </summary>
public class TestUserClaim : TestUserClaim<string> { } public class PocoUserClaim : PocoUserClaim<string> { }
/// <summary> /// <summary>
/// EntityType that represents one specific user claim /// EntityType that represents one specific user claim
/// </summary> /// </summary>
/// <typeparam name="TKey"></typeparam> /// <typeparam name="TKey"></typeparam>
public class TestUserClaim<TKey> where TKey : IEquatable<TKey> public class PocoUserClaim<TKey> where TKey : IEquatable<TKey>
{ {
/// <summary> /// <summary>
/// Primary key /// Primary key

View File

@ -8,13 +8,13 @@ namespace Microsoft.AspNetCore.Identity.Test
/// <summary> /// <summary>
/// Entity type for a user's login (i.e. facebook, google) /// Entity type for a user's login (i.e. facebook, google)
/// </summary> /// </summary>
public class TestUserLogin : TestUserLogin<string> { } public class PocoUserLogin : PocoUserLogin<string> { }
/// <summary> /// <summary>
/// Entity type for a user's login (i.e. facebook, google) /// Entity type for a user's login (i.e. facebook, google)
/// </summary> /// </summary>
/// <typeparam name="TKey"></typeparam> /// <typeparam name="TKey"></typeparam>
public class TestUserLogin<TKey> where TKey : IEquatable<TKey> public class PocoUserLogin<TKey> where TKey : IEquatable<TKey>
{ {
/// <summary> /// <summary>
/// The login provider for the login (i.e. facebook, google) /// The login provider for the login (i.e. facebook, google)

View File

@ -8,13 +8,13 @@ namespace Microsoft.AspNetCore.Identity.Test
/// <summary> /// <summary>
/// EntityType that represents a user belonging to a role /// EntityType that represents a user belonging to a role
/// </summary> /// </summary>
public class TestUserRole : TestUserRole<string> { } public class PocoUserRole : PocoUserRole<string> { }
/// <summary> /// <summary>
/// EntityType that represents a user belonging to a role /// EntityType that represents a user belonging to a role
/// </summary> /// </summary>
/// <typeparam name="TKey"></typeparam> /// <typeparam name="TKey"></typeparam>
public class TestUserRole<TKey> where TKey : IEquatable<TKey> public class PocoUserRole<TKey> where TKey : IEquatable<TKey>
{ {
/// <summary> /// <summary>
/// UserId for the user that is in the role /// UserId for the user that is in the role

View File

@ -8,13 +8,13 @@ namespace Microsoft.AspNetCore.Identity.Test
/// <summary> /// <summary>
/// Entity type for a user's token /// Entity type for a user's token
/// </summary> /// </summary>
public class TestUserToken : TestUserToken<string> { } public class PocoUserToken : PocoUserToken<string> { }
/// <summary> /// <summary>
/// Entity type for a user's token /// Entity type for a user's token
/// </summary> /// </summary>
/// <typeparam name="TKey"></typeparam> /// <typeparam name="TKey"></typeparam>
public class TestUserToken<TKey> where TKey : IEquatable<TKey> public class PocoUserToken<TKey> where TKey : IEquatable<TKey>
{ {
/// <summary> /// <summary>
/// The login provider for the login (i.e. facebook, google) /// The login provider for the login (i.e. facebook, google)

View File

@ -0,0 +1,15 @@
// 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 Identity.DefaultUI.WebSite.Data;
using Microsoft.Extensions.Configuration;
namespace Identity.DefaultUI.WebSite
{
public class ApplicationUserStartup : StartupBase<ApplicationUser, ApplicationDbContext>
{
public ApplicationUserStartup(IConfiguration configuration) : base(configuration)
{
}
}
}

View File

@ -0,0 +1,15 @@
// 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 Microsoft.AspNetCore.Identity.EntityFrameworkCore;
using Microsoft.EntityFrameworkCore;
namespace Identity.DefaultUI.WebSite.Data
{
public class ApplicationDbContext : IdentityDbContext<ApplicationUser>
{
public ApplicationDbContext(DbContextOptions<ApplicationDbContext> options) : base(options)
{
}
}
}

View File

@ -0,0 +1,11 @@
// 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 Microsoft.AspNetCore.Identity;
namespace Identity.DefaultUI.WebSite
{
public class ApplicationUser : IdentityUser
{
}
}

View File

@ -1,10 +1,15 @@
<Project Sdk="Microsoft.NET.Sdk.Web"> <Project Sdk="Microsoft.NET.Sdk.Web">
<PropertyGroup> <PropertyGroup>
<TargetFrameworks>$(StandardTestWebsiteTfms)</TargetFrameworks> <TargetFrameworks>$(StandardTestWebsiteTfms)</TargetFrameworks>
<UserSecretsId>aspnet-Identity.DefaultUI.WebSite-80C658D8-CED7-467F-9B47-75DA3BC1A16D</UserSecretsId> <UserSecretsId>aspnet-Identity.DefaultUI.WebSite-80C658D8-CED7-467F-9B47-75DA3BC1A16D</UserSecretsId>
</PropertyGroup> </PropertyGroup>
<ItemGroup>
<Compile Include="..\..\InMemory.Test\InMemoryUserStore.cs" Link="Services\InMemoryUserStore.cs" />
<Compile Include="..\..\Shared\Poco*.cs" Link="Data\%(FileName)%(Extension)" />
</ItemGroup>
<ItemGroup> <ItemGroup>
<PackageReference Include="Microsoft.AspNetCore.Authentication.Cookies" Version="$(MicrosoftAspNetCoreAuthenticationCookiesPackageVersion)" /> <PackageReference Include="Microsoft.AspNetCore.Authentication.Cookies" Version="$(MicrosoftAspNetCoreAuthenticationCookiesPackageVersion)" />
<PackageReference Include="Microsoft.AspNetCore.Authentication.Facebook" Version="$(MicrosoftAspNetCoreAuthenticationFacebookPackageVersion)" /> <PackageReference Include="Microsoft.AspNetCore.Authentication.Facebook" Version="$(MicrosoftAspNetCoreAuthenticationFacebookPackageVersion)" />

View File

@ -0,0 +1,63 @@
// 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 Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.Identity;
using Microsoft.AspNetCore.Identity.EntityFrameworkCore;
using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
namespace Identity.DefaultUI.WebSite
{
public class NoIdentityStartup
{
public NoIdentityStartup(IConfiguration configuration)
{
Configuration = configuration;
}
public IConfiguration Configuration { get; }
// This method gets called by the runtime. Use this method to add services to the container.
public void ConfigureServices(IServiceCollection services)
{
services.Configure<CookiePolicyOptions>(options =>
{
// This lambda determines whether user consent for non-essential cookies is needed for a given request.
options.CheckConsentNeeded = context => true;
});
services.AddMvc()
.AddRazorPagesOptions(options =>
{
options.Conventions.AuthorizeFolder("/Areas/Identity/Pages/Account/Manage");
options.Conventions.AuthorizePage("/Areas/Identity/Pages/Account/Logout");
});
}
// This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
public void Configure(IApplicationBuilder app, IHostingEnvironment env)
{
if (env.IsDevelopment())
{
app.UseDeveloperExceptionPage();
app.UseDatabaseErrorPage();
}
else
{
app.UseExceptionHandler("/Error");
app.UseHsts();
}
app.UseHttpsRedirection();
app.UseStaticFiles();
app.UseCookiePolicy();
app.UseAuthentication();
app.UseMvc();
}
}
}

View File

@ -1,14 +1,11 @@
@using Microsoft.AspNetCore.Identity @using Microsoft.AspNetCore.Identity
@inject SignInManager<IdentityUser> SignInManager @if (User.Identity.IsAuthenticated)
@inject UserManager<IdentityUser> UserManager
@if (SignInManager.IsSignedIn(User))
{ {
<form asp-area="Identity" asp-page="/Account/Logout" asp-route-returnUrl="@Url.Page("/Index", new { area = "" })" method="post" id="logoutForm" class="navbar-right"> <form asp-area="Identity" asp-page="/Account/Logout" asp-route-returnUrl="@Url.Page("/Index", new { area = "" })" method="post" id="logoutForm" class="navbar-right">
<ul class="nav navbar-nav navbar-right"> <ul class="nav navbar-nav navbar-right">
<li> <li>
<a id="manage" asp-area="Identity" asp-page="/Account/Manage/Index" title="Manage">Hello @UserManager.GetUserName(User)!</a> <a id="manage" asp-area="Identity" asp-page="/Account/Manage/Index" title="Manage">Hello @User.Identity.Name!</a>
</li> </li>
<li> <li>
<button id="logout" type="submit" class="btn btn-link navbar-btn navbar-link">Logout</button> <button id="logout" type="submit" class="btn btn-link navbar-btn navbar-link">Logout</button>

View File

@ -0,0 +1,9 @@
// 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.
namespace Identity.DefaultUI.WebSite
{
public class PocoUser
{
}
}

View File

@ -0,0 +1,36 @@
// 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 Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Identity;
using Microsoft.AspNetCore.Identity.EntityFrameworkCore;
using Microsoft.AspNetCore.Identity.InMemory;
using Microsoft.AspNetCore.Identity.Test;
using Microsoft.AspNetCore.Identity.UI;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
namespace Identity.DefaultUI.WebSite
{
public class PocoUserStartup : StartupBase<PocoUser, IdentityDbContext>
{
public PocoUserStartup(IConfiguration configuration) : base(configuration)
{
}
public override void ConfigureServices(IServiceCollection services)
{
services.Configure<CookiePolicyOptions>(options =>
{
// This lambda determines whether user consent for non-essential cookies is needed for a given request.
options.CheckConsentNeeded = context => true;
});
services.AddDefaultIdentity<Microsoft.AspNetCore.Identity.Test.PocoUser>()
.AddUserManager<UserManager<Microsoft.AspNetCore.Identity.Test.PocoUser>>();
services.AddSingleton<IUserStore<Microsoft.AspNetCore.Identity.Test.PocoUser>, InMemoryUserStore<Microsoft.AspNetCore.Identity.Test.PocoUser>>();
services.AddMvc();
}
}
}

View File

@ -1,73 +1,16 @@
// Copyright (c) .NET Foundation. All rights reserved. // 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. // Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.Identity; using Microsoft.AspNetCore.Identity;
using Microsoft.AspNetCore.Identity.EntityFrameworkCore; using Microsoft.AspNetCore.Identity.EntityFrameworkCore;
using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.Configuration; using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
namespace Identity.DefaultUI.WebSite namespace Identity.DefaultUI.WebSite
{ {
public class Startup public class Startup : StartupBase<IdentityUser, IdentityDbContext>
{ {
public Startup(IConfiguration configuration) public Startup(IConfiguration configuration) : base(configuration)
{ {
Configuration = configuration;
}
public IConfiguration Configuration { get; }
// This method gets called by the runtime. Use this method to add services to the container.
public void ConfigureServices(IServiceCollection services)
{
services.Configure<CookiePolicyOptions>(options =>
{
// This lambda determines whether user consent for non-essential cookies is needed for a given request.
options.CheckConsentNeeded = context => true;
});
services.AddDbContext<IdentityDbContext>(options =>
options.UseSqlServer(
Configuration.GetConnectionString("DefaultConnection"),
sqlOptions => sqlOptions.MigrationsAssembly("Identity.DefaultUI.WebSite")
));
services.AddDefaultIdentity<IdentityUser>()
.AddRoles<IdentityRole>()
.AddEntityFrameworkStores<IdentityDbContext>();
services.AddMvc()
.AddRazorPagesOptions(options =>
{
options.Conventions.AuthorizeFolder("/Areas/Identity/Pages/Account/Manage");
options.Conventions.AuthorizePage("/Areas/Identity/Pages/Account/Logout");
});
}
// This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
public void Configure(IApplicationBuilder app, IHostingEnvironment env)
{
if (env.IsDevelopment())
{
app.UseDeveloperExceptionPage();
app.UseDatabaseErrorPage();
}
else
{
app.UseExceptionHandler("/Error");
app.UseHsts();
}
app.UseHttpsRedirection();
app.UseStaticFiles();
app.UseCookiePolicy();
app.UseAuthentication();
app.UseMvc();
} }
} }
} }

View File

@ -0,0 +1,70 @@
// 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 Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.Identity;
using Microsoft.AspNetCore.Identity.EntityFrameworkCore;
using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
namespace Identity.DefaultUI.WebSite
{
public class StartupBase<TUser,TContext>
where TUser : class
where TContext : DbContext
{
public StartupBase(IConfiguration configuration)
{
Configuration = configuration;
}
public IConfiguration Configuration { get; }
// This method gets called by the runtime. Use this method to add services to the container.
public virtual void ConfigureServices(IServiceCollection services)
{
services.Configure<CookiePolicyOptions>(options =>
{
// This lambda determines whether user consent for non-essential cookies is needed for a given request.
options.CheckConsentNeeded = context => true;
});
services.AddDbContext<TContext>(options =>
options.UseSqlServer(
Configuration.GetConnectionString("DefaultConnection"),
sqlOptions => sqlOptions.MigrationsAssembly("Identity.DefaultUI.WebSite")
));
services.AddDefaultIdentity<TUser>()
.AddRoles<IdentityRole>()
.AddEntityFrameworkStores<TContext>();
services.AddMvc();
}
// This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
public void Configure(IApplicationBuilder app, IHostingEnvironment env)
{
if (env.IsDevelopment())
{
app.UseDeveloperExceptionPage();
app.UseDatabaseErrorPage();
}
else
{
app.UseExceptionHandler("/Error");
app.UseHsts();
}
app.UseHttpsRedirection();
app.UseStaticFiles();
app.UseCookiePolicy();
app.UseAuthentication();
app.UseMvc();
}
}
}