public async Task AddUserToUnknownRoleFails() { var manager = CreateManager(); var u = CreateTestUser(); IdentityResultAssert.IsSuccess(await manager.CreateAsync(u)); await Assert.ThrowsAsync <InvalidOperationException>( async() => await manager.AddToRoleAsync(u, "bogus")); }
public async Task VerifyAccountControllerExternalLoginWithTokensFlow() { // Setup the external cookie like it would look from a real OAuth2 var externalId = "<externalId>"; var authScheme = "<authScheme>"; var externalIdentity = new ClaimsIdentity(); externalIdentity.AddClaim(new Claim(ClaimTypes.NameIdentifier, externalId)); var externalPrincipal = new ClaimsPrincipal(externalIdentity); var externalLogin = new ExternalLoginInfo(externalPrincipal, authScheme, externalId, "displayname") { AuthenticationTokens = new[] { new AuthenticationToken { Name = "refresh_token", Value = "refresh" }, new AuthenticationToken { Name = "access_token", Value = "access" } } }; var auth = new Mock <AuthenticationManager>(); auth.Setup(a => a.AuthenticateAsync(It.IsAny <AuthenticateContext>())).Returns(Task.FromResult(0)); var context = new Mock <HttpContext>(); context.Setup(c => c.Authentication).Returns(auth.Object).Verifiable(); var contextAccessor = new Mock <IHttpContextAccessor>(); contextAccessor.Setup(a => a.HttpContext).Returns(context.Object); var services = new ServiceCollection(); services.AddLogging(); services.AddSingleton(contextAccessor.Object); services.AddIdentity <TestUser, TestRole>(); services.AddSingleton <IUserStore <TestUser>, InMemoryStore <TestUser, TestRole> >(); services.AddSingleton <IRoleStore <TestRole>, InMemoryStore <TestUser, TestRole> >(); var app = new ApplicationBuilder(services.BuildServiceProvider()); app.UseCookieAuthentication(); // Act var user = new TestUser { UserName = "******" }; var userManager = app.ApplicationServices.GetRequiredService <UserManager <TestUser> >(); var signInManager = app.ApplicationServices.GetRequiredService <SignInManager <TestUser> >(); IdentityResultAssert.IsSuccess(await userManager.CreateAsync(user)); IdentityResultAssert.IsSuccess(await userManager.AddLoginAsync(user, new UserLoginInfo(authScheme, externalId, "whatever"))); IdentityResultAssert.IsSuccess(await signInManager.UpdateExternalAuthenticationTokensAsync(externalLogin)); Assert.Equal("refresh", await userManager.GetAuthenticationTokenAsync(user, authScheme, "refresh_token")); Assert.Equal("access", await userManager.GetAuthenticationTokenAsync(user, authScheme, "access_token")); }
public async Task SuccessIfDifferent(string email, string password) { var manager = MockHelpers.TestUserManager <IdentityUser>(); var validator = new EmailAsPasswordValidator <IdentityUser>(); var user = new IdentityUser { Email = email }; IdentityResultAssert.IsSuccess(await validator.ValidateAsync(manager, user, password)); }
public async Task SucceedsIfZeroLengthPassword() { var client = new Mock <IPwnedPasswordsClient>(); var input = string.Empty; var manager = MockHelpers.TestUserManager <TestUser>(); var validator = new PwnedPasswordValidator <TestUser>(client.Object, Describer); IdentityResultAssert.IsSuccess(await validator.ValidateAsync(manager, null, input)); }
public async Task SuccessIfLessCommonThan500(string input) { var passwordLists = new PasswordLists( MockHelpers.MockOptions().Object, MockHelpers.MockILogger <PasswordLists>().Object); var manager = MockHelpers.TestUserManager <TestUser>(); var valid = new Top500PasswordValidator <TestUser>(passwordLists); IdentityResultAssert.IsSuccess(await valid.ValidateAsync(manager, null, input)); }
public async Task SucceedsIfNullPassword() { var client = new Mock <IPwnedPasswordsClient>(); string input = null; var manager = MockHelpers.TestUserManager <TestUser>(); var validator = new PwnedPasswordValidator <TestUser>(client.Object, Settings); IdentityResultAssert.IsSuccess(await validator.ValidateAsync(manager, null, input)); }
public async Task ValidateDoesNotThrowWithNullUserTest() { // Setup var validator = new EmailAsPasswordValidator <IdentityUser>(); var manager = MockHelpers.TestUserManager <IdentityUser>(); var password = "******"; // Act // Assert IdentityResultAssert.IsSuccess(await validator.ValidateAsync(manager, null, password)); }
public async Task CanCreateUsingManager() { var manager = CreateManager(); var guid = Guid.NewGuid().ToString(); var user = new IdentityUser { UserName = "******" + guid }; IdentityResultAssert.IsSuccess(await manager.CreateAsync(user)); IdentityResultAssert.IsSuccess(await manager.DeleteAsync(user)); }
public async Task SuccessIfLongEnoughTests(string input) { 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; manager.Options.Password.RequireDigit = false; IdentityResultAssert.IsSuccess(await valid.ValidateAsync(manager, null, input)); }
public async Task CanSetUserName() { var manager = TestIdentityFactory.CreateRoleManager(); var role = new IdentityRole("UpdateRoleName"); IdentityResultAssert.IsSuccess(await manager.CreateAsync(role)); Assert.Null(await manager.FindByNameAsync("New")); IdentityResultAssert.IsSuccess(await manager.SetRoleNameAsync(role, "New")); Assert.NotNull(await manager.FindByNameAsync("New")); Assert.Null(await manager.FindByNameAsync("UpdateAsync")); }
public async Task SuccessIfUserWithDefaultId() { var manager = MockHelpers.TestUserManager <IdentityUser>(); var validator = new PreventPasswordChangeValidator <IdentityUser>(); var user = new IdentityUser { UserName = "******", Id = default(string) }; var password = "******"; IdentityResultAssert.IsSuccess(await validator.ValidateAsync(manager, user, password)); }
public async Task SuccessIfNullUser() { // Setup var validator = new PreventPasswordChangeValidator <IdentityUser>(); var manager = MockHelpers.TestUserManager <IdentityUser>(); var password = "******"; // Act // Assert IdentityResultAssert.IsSuccess(await validator.ValidateAsync(manager, null, password)); }
public async Task CanFindByName() { var name = Guid.NewGuid().ToString(); var manager = CreateManager(); var user = CreateTestUser(namePrefix: name, useNamePrefixAsUserName: true); IdentityResultAssert.IsSuccess(await manager.CreateAsync(user)); var fetch = await manager.FindByNameAsync(name); Assert.Equal(user, fetch); }
public async Task SuccessIfServiceIndicatesPasswordIsNotPwned() { var service = new Mock <IPwnedPasswordService>(); service.Setup(x => x.HasPasswordBeenPwned(It.IsAny <string>())).ReturnsAsync(false); var input = "password"; var manager = MockHelpers.TestUserManager <TestUser>(); var validator = new PwnedPasswordValidator <TestUser>(service.Object); IdentityResultAssert.IsSuccess(await validator.ValidateAsync(manager, null, input)); }
public async Task EnsureRoleClaimNavigationProperty() { var context = CreateContext(); var roleManager = CreateRoleManager(context); var r = new IdentityRole("EnsureRoleClaimNavigationProperty"); IdentityResultAssert.IsSuccess(await roleManager.CreateAsync(r)); var c = new Claim("a", "b"); IdentityResultAssert.IsSuccess(await roleManager.AddClaimAsync(r, c)); Assert.NotNull(r.Claims.Single(cl => cl.ClaimValue == c.Value && cl.ClaimType == c.Type)); }
public async Task TwoUsersSamePasswordDifferentHash() { var manager = CreateManager(); var userA = new IdentityUser(Guid.NewGuid().ToString()); IdentityResultAssert.IsSuccess(await manager.CreateAsync(userA, "password")); var userB = new IdentityUser(Guid.NewGuid().ToString()); IdentityResultAssert.IsSuccess(await manager.CreateAsync(userB, "password")); Assert.NotEqual(userA.PasswordHash, userB.PasswordHash); }
public async Task SuccessIfclientIndicatesPasswordIsNotPwned() { var client = new Mock <IPwnedPasswordsClient>(); client.Setup(x => x.HasPasswordBeenPwned(It.IsAny <string>(), It.IsAny <CancellationToken>())) .ReturnsAsync(false); var input = "password"; var manager = MockHelpers.TestUserManager <TestUser>(); var validator = new PwnedPasswordValidator <TestUser>(client.Object, Describer); IdentityResultAssert.IsSuccess(await validator.ValidateAsync(manager, null, input)); }
public async Task FindByEmailThrowsWithTwoUsersWithSameEmail() { var manager = CreateManager(); var userA = new IdentityUser(Guid.NewGuid().ToString()); userA.Email = "*****@*****.**"; IdentityResultAssert.IsSuccess(await manager.CreateAsync(userA, "password")); var userB = new IdentityUser(Guid.NewGuid().ToString()); userB.Email = "*****@*****.**"; IdentityResultAssert.IsSuccess(await manager.CreateAsync(userB, "password")); await Assert.ThrowsAsync <InvalidOperationException>(async() => await manager.FindByEmailAsync("*****@*****.**")); }
public async Task FindByLogin() { var user = CreateTestUser(); var manager = CreateManager(); IdentityResultAssert.IsSuccess(await manager.CreateAsync(user)); var createdUser = await manager.FindByIdAsync(await manager.GetUserIdAsync(user)); IdentityResultAssert.IsSuccess(await manager.AddLoginAsync(user, new UserLoginInfo("provider", createdUser.Id.ToString(), "display"))); var userByLogin = await manager.FindByLoginAsync("provider", user.Id.ToString()); Assert.NotNull(userByLogin); }
public async Task SucceedsWithRequiredUniqueCharsTests(string input, int uniqueChars) { 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; manager.Options.Password.RequireDigit = false; manager.Options.Password.RequiredLength = 0; manager.Options.Password.RequiredUniqueChars = uniqueChars; IdentityResultAssert.IsSuccess(await valid.ValidateAsync(manager, null, input)); }
public async Task CanUpdateUserMultipleTime() { var manager = CreateManager(); var user = CreateTestUser(); IdentityResultAssert.IsSuccess(await manager.CreateAsync(user)); user = await manager.FindByNameAsync(user.UserName); user.PhoneNumber = "+41123456789"; IdentityResultAssert.IsSuccess(await manager.UpdateAsync(user)); user.PhoneNumber = "+33123456789"; IdentityResultAssert.IsSuccess(await manager.UpdateAsync(user)); }
public async Task CanCreateRoleWithSingletonManager() { var services = TestIdentityFactory.CreateTestServices(); //services.AddEntityFrameworkInMemoryDatabase(); services.AddSingleton(GetConnectionFactory()); services.AddTransient <IRoleStore <LinqToDB.Identity.IdentityRole>, RoleStore <LinqToDB.Identity.IdentityRole> >(); services.AddSingleton <RoleManager <LinqToDB.Identity.IdentityRole> >(); var provider = services.BuildServiceProvider(); var manager = provider.GetRequiredService <RoleManager <LinqToDB.Identity.IdentityRole> >(); Assert.NotNull(manager); IdentityResultAssert.IsSuccess(await manager.CreateAsync(new IdentityRole("someRole"))); }
public async Task CanCreateUsingAddRoleManager() { var services = new ServiceCollection(); services.AddEntityFramework().AddInMemoryStore(); var store = new RoleStore <IdentityRole>(new InMemoryContext()); services.AddIdentity <InMemoryUser, IdentityRole>().AddRoleStore(() => store); var provider = services.BuildServiceProvider(); var manager = provider.GetService <RoleManager <IdentityRole> >(); Assert.NotNull(manager); IdentityResultAssert.IsSuccess(await manager.CreateAsync(new IdentityRole("arole"))); }
public async Task EnsureStartupUsageWorks() { var userStore = _builder.ApplicationServices.GetRequiredService<IUserStore<IdentityUser>>(); var userManager = _builder.ApplicationServices.GetRequiredService<UserManager<IdentityUser>>(); Assert.NotNull(userStore); Assert.NotNull(userManager); const string userName = "******"; const string password = "******"; var user = new IdentityUser { UserName = userName }; IdentityResultAssert.IsSuccess(await userManager.CreateAsync(user, password)); IdentityResultAssert.IsSuccess(await userManager.DeleteAsync(user)); }
public async Task DeleteUserRemovesTokens() { var userMgr = CreateManager(); var user = CreateTestUser(); IdentityResultAssert.IsSuccess(await userMgr.CreateAsync(user)); IdentityResultAssert.IsSuccess(await userMgr.SetAuthenticationTokenAsync(user, "provider", "test", "value")); Assert.Equal("value", await userMgr.GetAuthenticationTokenAsync(user, "provider", "test")); IdentityResultAssert.IsSuccess(await userMgr.DeleteAsync(user)); Assert.Null(await userMgr.GetAuthenticationTokenAsync(user, "provider", "test")); }
public async Task CanCreateRoleWithSingletonManager() { var services = TestIdentityFactory.CreateTestServices(); services.AddEntityFramework().AddInMemoryStore(); services.AddTransient <InMemoryContext>(); services.AddTransient <IRoleStore <IdentityRole>, RoleStore <IdentityRole, InMemoryContext> >(); services.AddSingleton <RoleManager <IdentityRole> >(); var provider = services.BuildServiceProvider(); var manager = provider.GetRequiredService <RoleManager <IdentityRole> >(); Assert.NotNull(manager); IdentityResultAssert.IsSuccess(await manager.CreateAsync(new IdentityRole("someRole"))); }
public async Task VerifyAccountControllerSignIn(bool isPersistent) { var app = new ApplicationBuilder(CallContextServiceLocator.Locator.ServiceProvider); app.UseCookieAuthentication(); var context = new Mock <HttpContext>(); var auth = new Mock <AuthenticationManager>(); context.Setup(c => c.Authentication).Returns(auth.Object).Verifiable(); auth.Setup(a => a.SignInAsync(new IdentityCookieOptions().ApplicationCookieAuthenticationScheme, It.IsAny <ClaimsPrincipal>(), It.IsAny <AuthenticationProperties>())).Returns(Task.FromResult(0)).Verifiable(); // REVIEW: is persistant mocking broken //It.Is<AuthenticationProperties>(v => v.IsPersistent == isPersistent))).Returns(Task.FromResult(0)).Verifiable(); var contextAccessor = new Mock <IHttpContextAccessor>(); contextAccessor.Setup(a => a.HttpContext).Returns(context.Object); var services = new ServiceCollection(); services.AddLogging(); services.AddInstance(contextAccessor.Object); services.AddIdentity <TestUser, TestRole>(); services.AddSingleton <IUserStore <TestUser>, InMemoryUserStore <TestUser> >(); services.AddSingleton <IRoleStore <TestRole>, InMemoryRoleStore <TestRole> >(); app.ApplicationServices = services.BuildServiceProvider(); // Act var user = new TestUser { UserName = "******" }; const string password = "******"; var userManager = app.ApplicationServices.GetRequiredService <UserManager <TestUser> >(); var signInManager = app.ApplicationServices.GetRequiredService <SignInManager <TestUser> >(); IdentityResultAssert.IsSuccess(await userManager.CreateAsync(user, password)); var result = await signInManager.PasswordSignInAsync(user, password, isPersistent, false); // Assert Assert.True(result.Succeeded); context.VerifyAll(); auth.VerifyAll(); contextAccessor.VerifyAll(); }
public async Task UberMixedRequiredTests(string input, Errors errorMask) { const string alphaError = "Passwords must have at least one non alphanumeric character."; const string upperError = "Passwords must have at least one uppercase ('A'-'Z')."; const string lowerError = "Passwords must have at least one lowercase ('a'-'z')."; const string digitError = "Passwords must have at least one digit ('0'-'9')."; const string lengthError = "Passwords must be at least 6 characters."; var manager = MockHelpers.TestUserManager <PocoUser>(); var valid = new PasswordValidator <PocoUser>(); var errors = new List <string>(); if ((errorMask & Errors.Length) != Errors.None) { errors.Add(lengthError); } if ((errorMask & Errors.Alpha) != Errors.None) { errors.Add(alphaError); } if ((errorMask & Errors.Digit) != Errors.None) { errors.Add(digitError); } if ((errorMask & Errors.Lower) != Errors.None) { errors.Add(lowerError); } if ((errorMask & Errors.Upper) != Errors.None) { errors.Add(upperError); } var result = await valid.ValidateAsync(manager, null, input); if (errors.Count == 0) { IdentityResultAssert.IsSuccess(result); } else { IdentityResultAssert.IsFailure(result); foreach (var error in errors) { Assert.Contains(result.Errors, e => e.Description == error); } } }
public async Task ConcurrentUpdatesWillFailWithDetachedUser() { var user = CreateTestUser(); var manager = CreateManager(); IdentityResultAssert.IsSuccess(await manager.CreateAsync(user)); var manager1 = CreateManager(); var manager2 = CreateManager(); var user2 = await manager2.FindByIdAsync(user.Id); Assert.NotNull(user2); Assert.NotSame(user, user2); user.UserName = Guid.NewGuid().ToString(); user2.UserName = Guid.NewGuid().ToString(); IdentityResultAssert.IsSuccess(await manager1.UpdateAsync(user)); IdentityResultAssert.IsFailure(await manager2.UpdateAsync(user2), new IdentityErrorDescriber().ConcurrencyFailure()); }
private async Task LazyLoadTestSetup(TestUserDbContext db, TUser user) { var context = CreateContext(); var manager = CreateManager(context); IdentityResultAssert.IsSuccess(await manager.CreateAsync(user)); IdentityResultAssert.IsSuccess(await manager.AddLoginAsync(user, new UserLoginInfo("provider", user.Id.ToString(), "display"))); Claim[] userClaims = { new Claim("Whatever", "Value"), new Claim("Whatever2", "Value2") }; foreach (var c in userClaims) { IdentityResultAssert.IsSuccess(await manager.AddClaimAsync(user, c)); } }