* 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
Родитель a273e349ee
Коммит f51af820a5
68 изменённых файлов: 1596 добавлений и 1172 удалений

Просмотреть файл

@ -1,6 +1,6 @@
{
"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": {
"IncludeScopes": false,

Просмотреть файл

@ -4,6 +4,7 @@
using System;
using System.ComponentModel.DataAnnotations;
using System.Security.Claims;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.RazorPages;
@ -44,18 +45,20 @@ namespace Microsoft.AspNetCore.Identity.UI.Pages.Account.Internal
{
private readonly SignInManager<TUser> _signInManager;
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;
public ExternalLoginModel(
SignInManager<TUser> signInManager,
UserManager<TUser> userManager,
IUserFactory<TUser> userFactory,
IUserStore<TUser> userStore,
ILogger<ExternalLoginModel> logger)
{
_signInManager = signInManager;
_userManager = userManager;
_userFactory = userFactory;
_userStore = userStore;
_emailStore = GetEmailStore();
_logger = logger;
}
@ -127,7 +130,11 @@ namespace Microsoft.AspNetCore.Identity.UI.Pages.Account.Internal
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);
if (result.Succeeded)
{
@ -149,5 +156,28 @@ namespace Microsoft.AspNetCore.Identity.UI.Pages.Account.Internal
ReturnUrl = returnUrl;
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;
}
}
}

Просмотреть файл

@ -42,7 +42,9 @@ namespace Microsoft.AspNetCore.Identity.UI.Pages.Account.Internal
}
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();
}
}
}

Просмотреть файл

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

Просмотреть файл

@ -104,6 +104,15 @@ namespace Microsoft.AspNetCore.Identity.UI.Pages.Account.Manage.Internal
var userId = await _userManager.GetUserIdAsync(user);
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);

Просмотреть файл

@ -4,6 +4,7 @@
using System;
using System.ComponentModel.DataAnnotations;
using System.Text.Encodings.Web;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Authorization;
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
{
private readonly SignInManager<TUser> _signInManager;
private readonly IUserFactory<TUser> _userFactory;
private readonly UserManager<TUser> _userManager;
private readonly IUserStore<TUser> _userStore;
private readonly IUserEmailStore<TUser> _emailStore;
private readonly ILogger<LoginModel> _logger;
private readonly IEmailSender _emailSender;
public RegisterModel(
UserManager<TUser> userManager,
IUserStore<TUser> userStore,
SignInManager<TUser> signInManager,
IUserFactory<TUser> userFactory,
ILogger<LoginModel> logger,
IEmailSender emailSender)
{
_userManager = userManager;
_userStore = userStore;
_emailStore = GetEmailStore();
_signInManager = signInManager;
_userFactory = userFactory;
_logger = logger;
_emailSender = emailSender;
}
@ -78,8 +81,12 @@ namespace Microsoft.AspNetCore.Identity.UI.Pages.Account.Internal
returnUrl = returnUrl ?? Url.Content("~/");
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);
if (result.Succeeded)
{
_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
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;
}
}
}

Просмотреть файл

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

Просмотреть файл

@ -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);
}
}

Просмотреть файл

@ -37,13 +37,6 @@ namespace Microsoft.AspNetCore.Identity
.MakeGenericType(builder.UserType));
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;
}
@ -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;
}
}
}

Просмотреть файл

@ -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 };
}
}
}

Просмотреть файл

@ -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)
{
}
}
}

Просмотреть файл

@ -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)
{
}
}
}

Просмотреть файл

@ -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)
{
}
}
}

Просмотреть файл

@ -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)
{
}
}
}

Просмотреть файл

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

Просмотреть файл

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

Просмотреть файл

@ -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)
{
}
}
}

Просмотреть файл

@ -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)
{
}
}
}

Просмотреть файл

@ -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)
{
}
}
}

Просмотреть файл

@ -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)
{
}
}
}

Просмотреть файл

@ -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;
}
}
}

Просмотреть файл

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

Просмотреть файл

@ -2,81 +2,33 @@
// 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.IO;
using System.Net.Http;
using System.Runtime.CompilerServices;
using Identity.DefaultUI.WebSite;
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.Logging;
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;
private IList<IDisposable> _disposableServers = new List<IDisposable>();
public TestServer CreateServer(
ILoggerFactory loggerFactory,
Action<IWebHostBuilder> configureBuilder,
[CallerMemberName] string isolationKey = "")
public ServerFactory()
{
var builder = WebHostBuilderFactory
.CreateFromTypesAssemblyEntryPoint<Startup>(new string[] { })
.UseSolutionRelativeContentRoot(Path.Combine("test", "WebSites", "Identity.DefaultUI.WebSite"))
.ConfigureServices(collection => collection.AddSingleton(loggerFactory))
.ConfigureServices(sc => sc.SetupTestDatabase(isolationKey)
ClientOptions.AllowAutoRedirect = false;
ClientOptions.BaseAddress = new Uri("https://localhost");
}
protected override void ConfigureWebHost(IWebHostBuilder builder)
{
base.ConfigureWebHost(builder);
builder.UseStartup<TStartup>();
builder.ConfigureServices(sc => sc.SetupTestDatabase<TContext>(Guid.NewGuid().ToString())
.AddMvc()
// Mark the cookie as essential for right now, as Identity uses it on
// several places to pass important data in post-redirect-get flows.
.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);
}
}
}

Просмотреть файл

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

Просмотреть файл

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

Просмотреть файл

@ -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",
};
}
}

Просмотреть файл

@ -1,6 +1,8 @@
// 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;
using System.Collections.Generic;
using System.Net.Http;
using System.Threading.Tasks;
using AngleSharp.Dom.Html;
@ -16,6 +18,9 @@ namespace Microsoft.AspNetCore.Identity.FunctionalTests.Account.Manage
private readonly IHtmlAnchorElement _externalLoginLink;
private readonly IHtmlAnchorElement _personalDataLink;
private readonly IHtmlFormElement _updateProfileForm;
private readonly IHtmlElement _emailInput;
private readonly IHtmlElement _userNameInput;
private readonly IHtmlElement _updateProfileButton;
private readonly IHtmlElement _confirmEmailButton;
public static readonly string Path = "/";
@ -33,6 +38,9 @@ namespace Microsoft.AspNetCore.Identity.FunctionalTests.Account.Manage
}
_personalDataLink = HtmlAssert.HasLink("#personal-data", 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)
{
_confirmEmailButton = HtmlAssert.HasElement("button#email-verification", manage);
@ -67,6 +75,19 @@ namespace Microsoft.AspNetCore.Identity.FunctionalTests.Account.Manage
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()
{
var goToChangePassword = await Client.GetAsync(_changePasswordLink.Href);
@ -74,6 +95,10 @@ namespace Microsoft.AspNetCore.Identity.FunctionalTests.Account.Manage
return new ChangePassword(Client, changePasswordDocument, Context);
}
internal string GetEmail() => _emailInput.GetAttribute("value");
internal object GetUserName() => _userNameInput.GetAttribute("value");
public async Task<SetPassword> ClickChangePasswordLinkExternalLoginAsync()
{
var response = await Client.GetAsync(_changePasswordLink.Href);

Просмотреть файл

@ -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)
{
}
}
}

Просмотреть файл

@ -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)
{
}
}
}

Просмотреть файл

@ -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)
{
}
}
}

Просмотреть файл

@ -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)
{
}
}
}

Просмотреть файл

@ -3,54 +3,58 @@
using System;
using System.Threading.Tasks;
using Microsoft.Extensions.Logging.Testing;
using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.DependencyInjection;
using Xunit;
using Xunit.Abstractions;
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;
}
public ServerFactory ServerFactory { get; }
public ServerFactory<TStartup, TContext> ServerFactory { get; }
[Fact]
public async Task CanRegisterAUser()
{
using (StartLog(out var loggerFactory))
{
// Arrange
var client = ServerFactory.CreateDefaultClient(loggerFactory);
// Arrange
void ConfigureTestServices(IServiceCollection services) { return; };
var userName = $"{Guid.NewGuid()}@example.com";
var password = $"!Test.Password1$";
var client = ServerFactory
.WithWebHostBuilder(whb => whb.ConfigureServices(ConfigureTestServices))
.CreateClient();
// Act & Assert
await UserStories.RegisterNewUserAsync(client, userName, password);
}
var userName = $"{Guid.NewGuid()}@example.com";
var password = $"!Test.Password1$";
// Act & Assert
await UserStories.RegisterNewUserAsync(client, userName, password);
}
[Fact]
public async Task CanRegisterWithASocialLoginProvider()
{
using (StartLog(out var loggerFactory))
{
// Arrange
var server = ServerFactory.CreateServer(loggerFactory, builder =>
builder.ConfigureServices(services => services.SetupTestThirdPartyLogin()));
var client = ServerFactory.CreateDefaultClient(server);
// Arrange
void ConfigureTestServices(IServiceCollection services) =>
services
.SetupTestThirdPartyLogin();
var guid = Guid.NewGuid();
var userName = $"{guid}";
var email = $"{guid}@example.com";
var client = ServerFactory
.WithWebHostBuilder(whb => whb.ConfigureServices(ConfigureTestServices))
.CreateClient();
// Act & Assert
await UserStories.RegisterNewUserWithSocialLoginAsync(client, userName, email);
}
var guid = Guid.NewGuid();
var userName = $"{guid}";
var email = $"{guid}@example.com";
// Act & Assert
await UserStories.RegisterNewUserWithSocialLoginAsync(client, userName, email);
}
}
}

Просмотреть файл

@ -8,6 +8,8 @@ using AngleSharp.Dom.Html;
using Identity.DefaultUI.WebSite;
using Microsoft.AspNetCore.Identity.FunctionalTests.Account;
using Microsoft.AspNetCore.Identity.FunctionalTests.Account.Manage;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
using Xunit;
namespace Microsoft.AspNetCore.Identity.FunctionalTests
@ -53,6 +55,12 @@ namespace Microsoft.AspNetCore.Identity.FunctionalTests
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)
{
var index = await Index.CreateAsync(
@ -185,12 +193,13 @@ namespace Microsoft.AspNetCore.Identity.FunctionalTests
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 personalData = await manage.ClickPersonalDataLinkAsync();
var download = await personalData.SubmitDownloadForm();
return await download.Content.ReadAsStringAsync();
ResponseAssert.IsOK(download);
return JsonConvert.DeserializeObject<JObject>(await download.Content.ReadAsStringAsync());
}
}
}

Просмотреть файл

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

Просмотреть файл

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

Просмотреть файл

@ -6,58 +6,58 @@ using System.Threading.Tasks;
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);
}
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);
}
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);
}
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);
}
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 Task<IdentityResult> DeleteAsync(TestRole user, CancellationToken cancellationToken = default(CancellationToken))
public Task<IdentityResult> DeleteAsync(PocoRole user, CancellationToken cancellationToken = default(CancellationToken))
{
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);
}
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);
}
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);
}

Просмотреть файл

@ -7,58 +7,58 @@ using System.Threading.Tasks;
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);
}
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);
}
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);
}
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);
}
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);
}
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 Task<IdentityResult> DeleteAsync(TestUser user, CancellationToken cancellationToken = default(CancellationToken))
public Task<IdentityResult> DeleteAsync(PocoUser user, CancellationToken cancellationToken = default(CancellationToken))
{
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);
}
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);
}

Просмотреть файл

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

Просмотреть файл

@ -17,8 +17,8 @@ namespace Microsoft.AspNetCore.Identity.Test
public async Task CreateCallsStore()
{
// Setup
var store = new Mock<IRoleStore<TestRole>>();
var role = new TestRole { Name = "Foo" };
var store = new Mock<IRoleStore<PocoRole>>();
var role = new PocoRole { Name = "Foo" };
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.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()
{
// Setup
var store = new Mock<IRoleStore<TestRole>>();
var role = new TestRole { Name = "Foo" };
var store = new Mock<IRoleStore<PocoRole>>();
var role = new PocoRole { Name = "Foo" };
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.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()
{
// Setup
var store = new Mock<IRoleStore<TestRole>>();
var role = new TestRole { Name = "Foo" };
var store = new Mock<IRoleStore<PocoRole>>();
var role = new PocoRole { Name = "Foo" };
store.Setup(s => s.FindByNameAsync("FOO", CancellationToken.None)).Returns(Task.FromResult(role)).Verifiable();
var manager = MockHelpers.TestRoleManager(store.Object);
@ -80,8 +80,8 @@ namespace Microsoft.AspNetCore.Identity.Test
public async Task CanFindByNameCallsStoreWithoutNormalizedName()
{
// Setup
var store = new Mock<IRoleStore<TestRole>>();
var role = new TestRole { Name = "Foo" };
var store = new Mock<IRoleStore<PocoRole>>();
var role = new PocoRole { Name = "Foo" };
store.Setup(s => s.FindByNameAsync(role.Name, CancellationToken.None)).Returns(Task.FromResult(role)).Verifiable();
var manager = MockHelpers.TestRoleManager(store.Object);
manager.KeyNormalizer = null;
@ -98,8 +98,8 @@ namespace Microsoft.AspNetCore.Identity.Test
public async Task RoleExistsCallsStoreWithNormalizedName()
{
// Setup
var store = new Mock<IRoleStore<TestRole>>();
var role = new TestRole { Name = "Foo" };
var store = new Mock<IRoleStore<PocoRole>>();
var role = new PocoRole { Name = "Foo" };
store.Setup(s => s.FindByNameAsync("FOO", CancellationToken.None)).Returns(Task.FromResult(role)).Verifiable();
var manager = MockHelpers.TestRoleManager(store.Object);
@ -124,7 +124,7 @@ namespace Microsoft.AspNetCore.Identity.Test
public async Task RoleManagerPublicNullChecks()
{
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());
await Assert.ThrowsAsync<ArgumentNullException>("role", async () => await manager.CreateAsync(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));
}
private static RoleManager<TestRole> CreateRoleManager(IRoleStore<TestRole> roleStore)
private static RoleManager<PocoRole> CreateRoleManager(IRoleStore<PocoRole> 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();
}
public Task<IdentityResult> UpdateAsync(TestRole role, CancellationToken cancellationToken = default(CancellationToken))
public Task<IdentityResult> UpdateAsync(PocoRole role, CancellationToken cancellationToken = default(CancellationToken))
{
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();
}
public Task<string> GetRoleIdAsync(TestRole role, CancellationToken cancellationToken = default(CancellationToken))
public Task<string> GetRoleIdAsync(PocoRole role, CancellationToken cancellationToken = default(CancellationToken))
{
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();
}
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();
}
public Task<TestRole> FindByIdAsync(string roleId, CancellationToken cancellationToken = default(CancellationToken))
public Task<PocoRole> FindByIdAsync(string roleId, CancellationToken cancellationToken = default(CancellationToken))
{
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();
}
@ -198,12 +198,12 @@ namespace Microsoft.AspNetCore.Identity.Test
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();
}
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();
}

Просмотреть файл

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

Просмотреть файл

@ -70,7 +70,7 @@ namespace Microsoft.AspNetCore.Identity.Test
[InlineData(false)]
public async Task OnValidatePrincipalTestSuccess(bool isPersistent)
{
var user = new TestUser("test");
var user = new PocoUser("test");
var httpContext = new Mock<HttpContext>();
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 claimsManager = new Mock<IUserClaimsPrincipalFactory<TestUser>>();
var userManager = MockHelpers.MockUserManager<PocoUser>();
var claimsManager = new Mock<IUserClaimsPrincipalFactory<PocoUser>>();
var identityOptions = new Mock<IOptions<IdentityOptions>>();
identityOptions.Setup(a => a.Value).Returns(new IdentityOptions());
var options = new Mock<IOptions<SecurityStampValidatorOptions>>();
options.Setup(a => a.Value).Returns(new SecurityStampValidatorOptions { ValidationInterval = TimeSpan.Zero });
var contextAccessor = new Mock<IHttpContextAccessor>();
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);
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)
{
@ -117,7 +117,7 @@ namespace Microsoft.AspNetCore.Identity.Test
var services = new ServiceCollection();
services.AddSingleton(options.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());
await testCode.Invoke();
@ -127,7 +127,7 @@ namespace Microsoft.AspNetCore.Identity.Test
[Fact]
public async Task OnValidateIdentityRejectsWhenValidateSecurityStampFails()
{
var user = new TestUser("test");
var user = new PocoUser("test");
var httpContext = new Mock<HttpContext>();
await RunApplicationCookieTest(user, httpContext, /*shouldStampValidate*/false, async () =>
@ -150,23 +150,23 @@ namespace Microsoft.AspNetCore.Identity.Test
[Fact]
public async Task OnValidateIdentityRejectsWhenNoIssuedUtc()
{
var user = new TestUser("test");
var user = new PocoUser("test");
var httpContext = new Mock<HttpContext>();
var userManager = MockHelpers.MockUserManager<TestUser>();
var userManager = MockHelpers.MockUserManager<PocoUser>();
var identityOptions = new Mock<IOptions<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>>();
options.Setup(a => a.Value).Returns(new SecurityStampValidatorOptions { ValidationInterval = TimeSpan.Zero });
var contextAccessor = new Mock<IHttpContextAccessor>();
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);
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();
services.AddSingleton(options.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());
var id = new ClaimsIdentity(IdentityConstants.ApplicationScheme);
id.AddClaim(new Claim(ClaimTypes.NameIdentifier, user.Id));
@ -186,24 +186,24 @@ namespace Microsoft.AspNetCore.Identity.Test
[Fact]
public async Task OnValidateIdentityDoesNotRejectsWhenNotExpired()
{
var user = new TestUser("test");
var user = new PocoUser("test");
var httpContext = new Mock<HttpContext>();
var userManager = MockHelpers.MockUserManager<TestUser>();
var userManager = MockHelpers.MockUserManager<PocoUser>();
var identityOptions = new Mock<IOptions<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>>();
options.Setup(a => a.Value).Returns(new SecurityStampValidatorOptions { ValidationInterval = TimeSpan.FromDays(1) });
var contextAccessor = new Mock<IHttpContextAccessor>();
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);
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"));
var services = new ServiceCollection();
services.AddSingleton(options.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());
var id = new ClaimsIdentity(IdentityConstants.ApplicationScheme);
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)
{
var user = new TestUser("test");
var user = new PocoUser("test");
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();
var claimsManager = new Mock<IUserClaimsPrincipalFactory<TestUser>>();
var claimsManager = new Mock<IUserClaimsPrincipalFactory<PocoUser>>();
var identityOptions = new Mock<IOptions<IdentityOptions>>();
identityOptions.Setup(a => a.Value).Returns(new IdentityOptions());
var options = new Mock<IOptions<SecurityStampValidatorOptions>>();
options.Setup(a => a.Value).Returns(new SecurityStampValidatorOptions { ValidationInterval = TimeSpan.Zero });
var contextAccessor = new Mock<IHttpContextAccessor>();
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);
signInManager.Setup(s => s.ValidateTwoFactorSecurityStampAsync(It.IsAny<ClaimsPrincipal>())).ReturnsAsync(shouldStampValidate ? user : default).Verifiable();
var services = new ServiceCollection();
services.AddSingleton(options.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());
var principal = await signInManager.Object.StoreRememberClient(user);

Просмотреть файл

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

Просмотреть файл

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

Разница между файлами не показана из-за своего большого размера Загрузить разницу

Просмотреть файл

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

Просмотреть файл

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

Просмотреть файл

@ -273,8 +273,8 @@ namespace Microsoft.AspNetCore.Identity.InMemory
{
var req = context.Request;
var res = context.Response;
var userManager = context.RequestServices.GetRequiredService<UserManager<TestUser>>();
var signInManager = context.RequestServices.GetRequiredService<SignInManager<TestUser>>();
var userManager = context.RequestServices.GetRequiredService<UserManager<PocoUser>>();
var signInManager = context.RequestServices.GetRequiredService<SignInManager<PocoUser>>();
PathString remainder;
if (req.Path == new PathString("/normal"))
{
@ -282,12 +282,12 @@ namespace Microsoft.AspNetCore.Identity.InMemory
}
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;
}
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;
}
else if (req.Path == new PathString("/signoutEverywhere"))
@ -340,9 +340,9 @@ namespace Microsoft.AspNetCore.Identity.InMemory
})
.ConfigureServices(services =>
{
services.AddIdentity<TestUser, TestRole>().AddDefaultTokenProviders();
services.AddSingleton<IUserStore<TestUser>, InMemoryStore<TestUser, TestRole>>();
services.AddSingleton<IRoleStore<TestRole>, InMemoryStore<TestUser, TestRole>>();
services.AddIdentity<PocoUser, PocoRole>().AddDefaultTokenProviders();
services.AddSingleton<IUserStore<PocoUser>, InMemoryStore<PocoUser, PocoRole>>();
services.AddSingleton<IRoleStore<PocoRole>, InMemoryStore<PocoUser, PocoRole>>();
configureServices?.Invoke(services);
});
var server = new TestServer(builder);

Просмотреть файл

@ -16,8 +16,8 @@ namespace Microsoft.AspNetCore.Identity.InMemory
IUserRoleStore<TUser>,
IQueryableRoleStore<TRole>,
IRoleClaimStore<TRole>
where TRole : TestRole
where TUser : TestUser
where TRole : PocoRole
where TUser : PocoUser
{
// RoleId == roleName for InMemory
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);
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);
}
@ -139,7 +139,7 @@ namespace Microsoft.AspNetCore.Identity.InMemory
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);
}

Просмотреть файл

@ -8,32 +8,32 @@ using Microsoft.Extensions.DependencyInjection;
namespace Microsoft.AspNetCore.Identity.InMemory.Test
{
public class InMemoryStoreTest : IdentitySpecificationTestBase<TestUser, TestRole>
public class InMemoryStoreTest : IdentitySpecificationTestBase<PocoUser, PocoRole>
{
protected override object CreateTestContext()
{
return new InMemoryStore<TestUser, TestRole>();
return new InMemoryStore<PocoUser, PocoRole>();
}
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)
{
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;
}
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)
{
return new TestUser
return new PocoUser
{
UserName = useNamePrefixAsUserName ? namePrefix : string.Format("{0}{1}", namePrefix, Guid.NewGuid()),
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());
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);
}
}

Просмотреть файл

@ -24,7 +24,7 @@ namespace Microsoft.AspNetCore.Identity.InMemory
IUserAuthenticationTokenStore<TUser>,
IUserAuthenticatorKeyStore<TUser>,
IUserTwoFactorRecoveryCodeStore<TUser>
where TUser : TestUser
where TUser : PocoUser
{
private readonly Dictionary<string, TUser> _logins = new Dictionary<string, TUser>();
@ -45,7 +45,7 @@ namespace Microsoft.AspNetCore.Identity.InMemory
{
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);
}
@ -164,7 +164,7 @@ namespace Microsoft.AspNetCore.Identity.InMemory
public virtual Task AddLoginAsync(TUser user, UserLoginInfo login,
CancellationToken cancellationToken = default(CancellationToken))
{
user.Logins.Add(new TestUserLogin
user.Logins.Add(new PocoUserLogin
{
UserId = user.Id,
ProviderKey = login.ProviderKey,
@ -364,7 +364,7 @@ namespace Microsoft.AspNetCore.Identity.InMemory
}
else
{
user.Tokens.Add(new TestUserToken
user.Tokens.Add(new PocoUserToken
{
UserId = user.Id,
LoginProvider = loginProvider,

Просмотреть файл

@ -8,27 +8,27 @@ using Microsoft.Extensions.DependencyInjection;
namespace Microsoft.AspNetCore.Identity.InMemory.Test
{
public class InMemoryUserStoreTest : UserManagerSpecificationTestBase<TestUser, string>
public class InMemoryUserStoreTest : UserManagerSpecificationTestBase<PocoUser, string>
{
protected override object CreateTestContext()
{
return new InMemoryUserStore<TestUser>();
return new InMemoryUserStore<PocoUser>();
}
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;
}
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)
{
return new TestUser
return new PocoUser
{
UserName = useNamePrefixAsUserName ? namePrefix : string.Format("{0}{1}", namePrefix, Guid.NewGuid()),
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);
}
}

Просмотреть файл

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

Просмотреть файл

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

Просмотреть файл

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

Просмотреть файл

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

Просмотреть файл

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

Просмотреть файл

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

Просмотреть файл

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

Просмотреть файл

@ -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)
{
}
}
}

Просмотреть файл

@ -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)
{
}
}
}

Просмотреть файл

@ -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
{
}
}

Просмотреть файл

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

Просмотреть файл

@ -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();
}
}
}

Просмотреть файл

@ -1,14 +1,11 @@
@using Microsoft.AspNetCore.Identity
@inject SignInManager<IdentityUser> SignInManager
@inject UserManager<IdentityUser> UserManager
@if (SignInManager.IsSignedIn(User))
@if (User.Identity.IsAuthenticated)
{
<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">
<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>
<button id="logout" type="submit" class="btn btn-link navbar-btn navbar-link">Logout</button>

Просмотреть файл

@ -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
{
}
}

Просмотреть файл

@ -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();
}
}
}

Просмотреть файл

@ -1,73 +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 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 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();
}
}
}

Просмотреть файл

@ -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();
}
}
}