protected void CreateUser_Click(object sender, EventArgs e) { // Default UserStore constructor uses the default connection string named: DefaultConnection var userStore = new UserStore<IdentityUser>(); var manager = new UserManager<IdentityUser>(userStore); //IdentityResult IdUserResult; var user = new IdentityUser() { UserName = UserName.Text }; IdentityResult result = manager.Create(user, Password.Text); if (result.Succeeded) { var authenticationManager = HttpContext.Current.GetOwinContext().Authentication; var userIdentity = manager.CreateIdentity(user, DefaultAuthenticationTypes.ApplicationCookie); authenticationManager.SignIn(new AuthenticationProperties() { }, userIdentity); // IdUserResult = manager.AddToRole(manager.FindByName(user.UserName).Id, "member"); Session["uPass"] = Password.Text; Response.Redirect("~/WebForm2.aspx"); // StatusMessage.Text = string.Format("User {0} was created successfully!", user.UserName); } else { StatusMessage.Text = result.Errors.FirstOrDefault(); } }
protected void btnSave_Click(object sender, EventArgs e) { try { // Default UserStore constructor uses the default connection string named: DefaultConnection var userStore = new UserStore<IdentityUser>(); var manager = new UserManager<IdentityUser>(userStore); var user = new IdentityUser() { UserName = txtUsername.Text }; IdentityResult result = manager.Create(user, txtPassword.Text); if (result.Succeeded) { var authenticationManager = HttpContext.Current.GetOwinContext().Authentication; var userIdentity = manager.CreateIdentity(user, DefaultAuthenticationTypes.ApplicationCookie); authenticationManager.SignIn(new AuthenticationProperties() { }, userIdentity); Response.Redirect("/user/index.aspx"); } else { lblStatus.Text = result.Errors.FirstOrDefault(); } } catch (Exception d) { Response.Redirect("/error.aspx"); } }
protected void btnRegister_Click(object sender, EventArgs e) { try { // Default UserStore constructor uses the default connection string named: DefaultConnection var userStore = new UserStore<IdentityUser>(); var manager = new UserManager<IdentityUser>(userStore); var user = new IdentityUser() { UserName = txtUsername.Text }; IdentityResult result = manager.Create(user, txtPassword.Text); if (result.Succeeded) { //lblStatus.Text = string.Format("User {0} was created successfully!", user.UserName); //lblStatus.CssClass = "label label-success"; var authenticationManager = HttpContext.Current.GetOwinContext().Authentication; var userIdentity = manager.CreateIdentity(user, DefaultAuthenticationTypes.ApplicationCookie); authenticationManager.SignIn(new AuthenticationProperties() { }, userIdentity); Response.Redirect("admin/main-menu.aspx"); } else { lblStatus.Text = result.Errors.FirstOrDefault(); lblStatus.CssClass = "label label-danger"; } } catch (Exception q) { Response.Redirect("/error.aspx"); } }
public async Task OnValidateIdentityRejectsWhenValidateSecurityStampFails() { var user = new IdentityUser("test"); var httpContext = new Mock<HttpContext>(); var userManager = MockHelpers.MockUserManager<IdentityUser>(); var authManager = new Mock<IAuthenticationManager>(); var claimsManager = new Mock<IClaimsIdentityFactory<IdentityUser>>(); var signInManager = new Mock<SignInManager<IdentityUser>>(userManager.Object, authManager.Object, claimsManager.Object); signInManager.Setup(s => s.ValidateSecurityStamp(It.IsAny<ClaimsIdentity>(), user.Id)).ReturnsAsync(null).Verifiable(); var services = new ServiceCollection(); services.AddInstance(signInManager.Object); httpContext.Setup(c => c.ApplicationServices).Returns(services.BuildServiceProvider()); var id = new ClaimsIdentity(ClaimsIdentityOptions.DefaultAuthenticationType); id.AddClaim(new Claim(ClaimTypes.NameIdentifier, user.Id)); var ticket = new AuthenticationTicket(id, new AuthenticationProperties { IssuedUtc = DateTimeOffset.UtcNow }); var context = new CookieValidateIdentityContext(httpContext.Object, ticket, new CookieAuthenticationOptions()); Assert.NotNull(context.Properties); Assert.NotNull(context.Options); Assert.NotNull(context.Identity); await SecurityStampValidator.OnValidateIdentity<IdentityUser>(TimeSpan.Zero).Invoke(context); Assert.Null(context.Identity); signInManager.VerifyAll(); }
public async Task<int> DeleteAsync(IdentityUser user) { if (user == null) throw new ArgumentNullException(nameof(user)); return await DeleteAsync(user.Id); }
public async Task AddRemoveUserClaimTest() { var db = UnitTestHelper.CreateDefaultDb(); var store = new UserStore<IdentityUser>(db); ; var user = new IdentityUser("ClaimsAddRemove"); await store.CreateAsync(user); Claim[] claims = {new Claim("c", "v"), new Claim("c2", "v2"), new Claim("c2", "v3")}; foreach (Claim c in claims) { await store.AddClaimAsync(user, c); } await store.UpdateAsync(user); var userClaims = await store.GetClaimsAsync(user); Assert.Equal(3, userClaims.Count); await store.RemoveClaimAsync(user, claims[0]); Assert.Equal(3, userClaims.Count); // No effect until save changes db.SaveChanges(); userClaims = await store.GetClaimsAsync(user); Assert.Equal(2, userClaims.Count); await store.RemoveClaimAsync(user, claims[1]); Assert.Equal(2, userClaims.Count); // No effect until save changes db.SaveChanges(); userClaims = await store.GetClaimsAsync(user); Assert.Equal(1, userClaims.Count); await store.RemoveClaimAsync(user, claims[2]); Assert.Equal(1, userClaims.Count); // No effect until save changes db.SaveChanges(); userClaims = await store.GetClaimsAsync(user); Assert.Equal(0, userClaims.Count); //Assert.Equal(0, user.Claims.Count); }
public async Task EnsureStartupUsageWorks() { var context = CreateContext(true); IBuilder builder = new Builder.Builder(new ServiceCollection().BuildServiceProvider()); builder.UseServices(services => { services.AddEntityFramework().AddSqlServer(); services.AddIdentitySqlServer(); services.SetupOptions<DbContextOptions>(options => options.UseSqlServer(ConnectionString)); // todo: constructor resolution doesn't work well with IdentityDbContext since it has 4 constructors services.AddInstance(context); }); var userStore = builder.ApplicationServices.GetService<IUserStore<IdentityUser>>(); var userManager = builder.ApplicationServices.GetService<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 override async Task GrantResourceOwnerCredentials(OAuthGrantResourceOwnerCredentialsContext context) { context.OwinContext.Response.Headers.Add("Access-Control-Allow-Origin", new[] { "*" }); List<string> roles = new List<string>(); IdentityUser user = new IdentityUser(); using (AuthRepository _repo = new AuthRepository()) { user = await _repo.FindUser(context.UserName, context.Password); if (user == null) { context.SetError("invalid_grant", "Потребителското име или паролата не са верни."); return; } else { roles = await _repo.GetRolesForUser(user.Id); } } var identity = new ClaimsIdentity(context.Options.AuthenticationType); identity.AddClaim(new Claim("sub", context.UserName)); foreach (var item in roles) { identity.AddClaim(new Claim(ClaimTypes.Role, item)); } context.Validated(identity); context.Response.Headers.Add("UserRoles", roles.ToArray()); }
public void AddLogin(IdentityUser user, UserLoginInfo login) { _db[_tables.UsersLogins].Insert( LoginProvider: login.LoginProvider, ProviderKey: login.ProviderKey, UserId: user.Id); }
private static void SetPassword(IdentityUser user, string password, int passwordExpirationInMinutes, DateTime currentDate) { user.Password.Hash = password; user.Password.ExpirationDateUtc = passwordExpirationInMinutes > 0 ? currentDate.AddMinutes(passwordExpirationInMinutes) : default(DateTime?); }
public static IdentityUser UserWithTestRole() { var user = new IdentityUser(); user.AddRole("test"); return user; }
public async Task CanIncludeUserClaimsTest() { // Arrange CreateContext(true); var builder = new ApplicationBuilder(CallContextServiceLocator.Locator.ServiceProvider); var services = new ServiceCollection(); DbUtil.ConfigureDbServices<IdentityDbContext>(ConnectionString, services); services.AddIdentity<IdentityUser, IdentityRole>().AddEntityFrameworkStores<IdentityDbContext>(); builder.ApplicationServices = services.BuildServiceProvider(); var userManager = builder.ApplicationServices.GetRequiredService<UserManager<IdentityUser>>(); var dbContext = builder.ApplicationServices.GetRequiredService<IdentityDbContext>(); var username = "******" + new Random().Next(); var user = new IdentityUser() { UserName = username }; IdentityResultAssert.IsSuccess(await userManager.CreateAsync(user)); for (var i = 0; i < 10; i++) { IdentityResultAssert.IsSuccess(await userManager.AddClaimAsync(user, new Claim(i.ToString(), "foo"))); } user = dbContext.Users.Include(x => x.Claims).FirstOrDefault(x => x.UserName == username); // Assert Assert.NotNull(user); Assert.NotNull(user.Claims); Assert.Equal(10, user.Claims.Count()); }
public static IdentityUser UserWithLogin() { var user = new IdentityUser(); user.AddLogin(new UserLoginInfo("test", "testing")); return user; }
public override async Task GrantResourceOwnerCredentials(OAuthGrantResourceOwnerCredentialsContext context) { using (MyUserManager userManager = new MyUserManager()) { IdentityUser user = new IdentityUser(); if (FindUser(context.UserName, context.Password) != null) { user = userManager.FindByName(context.UserName); } //IdentityUser user2 = await userManager.FindAsync(context.UserName, context.Password); if (user == null) { context.SetError("invalid_grant", "The user name or password is incorrect."); return; } ClaimsIdentity oAuthIdentity = await userManager.CreateIdentityAsync(user, context.Options.AuthenticationType); ClaimsIdentity cookiesIdentity = await userManager.CreateIdentityAsync(user, CookieAuthenticationDefaults.AuthenticationType); AuthenticationProperties properties = CreateProperties(user); AuthenticationTicket ticket = new AuthenticationTicket(oAuthIdentity, properties); context.Validated(ticket); context.Request.Context.Authentication.SignIn(cookiesIdentity); } }
public async Task<IdentityResult> RegisterCustomerAsync(UserModel userModel, AppRole appRole = AppRole.customer) { var addToRoleResult = new IdentityResult(); // Add generate username to the model IdentityUser user = new IdentityUser { UserName = userModel.UserName, Email = userModel.EmailAddress, EmailConfirmed = true, PhoneNumber = userModel.PhoneNumber, PhoneNumberConfirmed = true, }; var result = await _userManager.CreateAsync(user, userModel.Password); //Role-user combination is managed as Contact-Role combination in ContactRole table //Create Role Admin if it does not exist var _role = await _roleManager.FindByNameAsync(appRole.ToString()); if (_role == null) { _role = new IdentityRole(appRole.ToString()); var roleresult = await _roleManager.CreateAsync(_role); } var rolesForUser = await _userManager.GetRolesAsync(user.Id); if (!rolesForUser.Contains(_role.Name)) { addToRoleResult = await _userManager.AddToRoleAsync(user.Id, _role.Name); } return addToRoleResult; }
public void Dont_add_duplicate_no_named_users() { var newUser = new IdentityUser(); CreateUser(newUser); var nextUser = new IdentityUser(); CreateUser(nextUser); }
public void RemoveLogin(IdentityUser user, UserLoginInfo login) { _db[_tables.UsersLogins].Delete( UserId: user.Id, LoginProvider: login.LoginProvider, ProviderKey: login.ProviderKey); }
protected void CreateUser_Click(object sender, EventArgs e) { // Default UserStore constructor uses the default connection string named: DefaultConnectionEF var userStore = new UserStore<IdentityUser>(); var manager = new UserManager<IdentityUser>(userStore); var user = new IdentityUser() { UserName = txtUName.Text }; user.Email = txtEmail.Text; user.PhoneNumber = txtPhone.Text; IdentityResult result = manager.Create(user, txtPass.Text); if (result.Succeeded) { lblStatus.Text = string.Format("User {0} was created successfully!", user.UserName); var authenticationManager = HttpContext.Current.GetOwinContext().Authentication; var userIdentity = manager.CreateIdentity(user, DefaultAuthenticationTypes.ApplicationCookie); authenticationManager.SignIn(new AuthenticationProperties() { }, userIdentity); Response.Redirect("/admin/main.aspx"); } else { lblStatus.Text = result.Errors.FirstOrDefault(); } }
public async Task<HttpResponseMessage> Create() { HttpResponseMessage response; try { var usuario = new IdentityUser { UserName = "******" }; var userManager = Request.GetOwinContext().GetUserManager<AppUserManager>(); IdentityResult result = await userManager.CreateAsync(usuario, "123Tr0car@@"); string resultado; if (result.Succeeded) { resultado = "Usuario Criado com sucesso"; } else { resultado = string.Join(",", result.Errors); } response = Request.CreateResponse(HttpStatusCode.OK, resultado); } catch (Exception ex) { response = Request.CreateResponse(HttpStatusCode.BadRequest, ex.Message); } return await Task.FromResult(response); }
public void IdentityMapperAppUserRelationsAreMapped() { IdentityUser dbUser = new IdentityUser { Logins = new List<IdentityUserLogin> { new IdentityUserLogin(), new IdentityUserLogin(), new IdentityUserLogin() }, Roles = new List<IdentityUserRole> { new IdentityUserRole(), new IdentityUserRole() }, Claims = new List<IdentityUserClaim> { new IdentityUserClaim() } }; ApplicationUser result = IdentityMapper.MapAppUserFromDbUser(dbUser); result.Should().NotBeNull(); result.Logins.Should().NotBeNull(); result.Logins.Count.Should().Be(3); result.Roles.Should().NotBeNull(); result.Roles.Count.Should().Be(2); result.Claims.Should().NotBeNull(); result.Claims.Count.Should().Be(1); }
public void InsertUser(IdentityUser user) { if (user == null) { throw new ArgumentNullException("user"); } var i = _database.As<IUserRepository>(); _database.Execute("InsertUser", new { email = user.Email, emailConfirmed = user.EmailConfirmed, passwordHash = user.PasswordHash, securityStamp = user.SecurityStamp, phoneNumber = user.PhoneNumber, phoneNumberConfirmed = user.PhoneNumberConfirmed, twoFactorEnabled = user.TwoFactorEnabled, lockoutEndDate = user.LockoutEndDate, lockoutEnabled = user.LockoutEnabled, accessFailedCount = user.AccessFailedCount, id = user.Id, userName = user.UserName }); i.InsertUser(user); }
public async Task<IdentityResult> RegisterUser(PlayerModel userModel) { Player user = new Player { UserName = userModel.UserName, FirstName = userModel.FirstName, LastName = userModel.LastName, ContactNumber = userModel.ContactNumber, Address1 = userModel.Address1, Address2 = userModel.Address2, Location = userModel.Location, BirthDate = userModel.BirthDate, Gender = userModel.Gender, Email = userModel.Email }; IdentityUser identityUser = new IdentityUser { UserName = userModel.UserName }; var result = await _userManager.CreateAsync(user,userModel.Password); return result; }
public ActionResult Register(User user) { string temp = user.Password; var userStore = new UserStore<IdentityUser>(); var manager = new UserManager<IdentityUser>(userStore); var user2 = new IdentityUser() { UserName = user.Username }; IdentityResult result = manager.Create(user2, user.Password); if (result.Succeeded) { TempData["message"] = "Identity user create worked"; //var temp2 = this.ControllerContext.HttpContext; var authenticationManager = HttpContext.GetOwinContext().Authentication; //var authenticationManager = HttpContext.Current.GetOwinContext().Authentication; var userIdentity = manager.CreateIdentity(user2, DefaultAuthenticationTypes.ApplicationCookie); authenticationManager.SignIn(new AuthenticationProperties() { }, userIdentity); //Response.Redirect("~/Login.aspx"); //return View("Login"); if (User.Identity.IsAuthenticated) { TempData["message"] += "/n User.Identity.IsAuthenticate working"; } return View("Index"); } else { TempData["message"] = "Failed: " + result.Errors.FirstOrDefault(); } return View("Index"); }
public async Task<int> UpdateAsync(IdentityUser user) { if (user == null) throw new ArgumentNullException(nameof(user)); const string UPDATE = @"UPDATE users SET username = :UserName, passwordhash = :PasswordHash, securitystamp = :SecurityStamp, firstname = :Firstname, lastname = :Lastname, email = :Email, emailconfirmed = :EmailConfirmedAsInt, phonenumber = :PhoneNumber, phonenumberconfirmed = :PhoneNumberConfirmedAsInt, twofactorenabled = :TwoFactorEnabledAsInt, lockoutenddateutc = :LockoutEndDateUtc, lockoutenabled = :LockoutEnabledAsInt, accessfailedcount = :AccessFailedCount WHERE Id = :Id"; using (var connection = ConnectionFactory.Create()) return await connection.ExecuteAsync(UPDATE, user).ConfigureAwait(false); }
public void AddLoginVerificationTests() { var newUser = new IdentityUser(GetNewRandomName()); var googleLoginProvider = "Google"; var googleLoginProviderKey = "http://www.google.com/fake/user/identifier"; var yahooLoginProvider = "Yahoo"; var yahooLoginProviderKey = "http://www.yahoo.com/fake/user/identifier"; var userCreationResult = _userManager.Create(newUser, _password); Assert.IsTrue(userCreationResult.Succeeded); Assert.IsNotNull(newUser.Id); var googleLoginResult = _userManager.AddLogin(newUser.Id, new UserLoginInfo(googleLoginProvider, googleLoginProviderKey)); var yahooLoginResult = _userManager.AddLogin(newUser.Id, new UserLoginInfo(yahooLoginProvider, yahooLoginProviderKey)); Assert.IsTrue(googleLoginResult.Succeeded); Assert.IsTrue(yahooLoginResult.Succeeded); var newUserLogins = _userManager.GetLogins(newUser.Id); Assert.AreEqual(newUserLogins.Count, 2); Assert.IsTrue(newUserLogins.Any(l => l.LoginProvider == googleLoginProvider && l.ProviderKey == googleLoginProviderKey)); Assert.IsTrue(newUserLogins.Any(l => l.LoginProvider == yahooLoginProvider && l.ProviderKey == yahooLoginProviderKey)); var userByName = _userManager.Find(newUser.UserName, _password); var userByGoogle = _userManager.Find(new UserLoginInfo(googleLoginProvider, googleLoginProviderKey)); var userByYahoo = _userManager.Find(new UserLoginInfo(yahooLoginProvider, yahooLoginProviderKey)); Assert.IsNotNull(userByName); Assert.IsNotNull(userByGoogle); Assert.IsNotNull(userByYahoo); Assert.AreEqual(userByName.UserName, newUser.UserName); }
protected void RegisterButton_Click(object sender, EventArgs e) { //crete new userStore and userManager objects var userStore = new UserStore<IdentityUser>(); var userManager = new UserManager<IdentityUser>(userStore); var user = new IdentityUser() { UserName = UserNameTextBox.Text, PhoneNumber = PhoneNumberTextBox.Text, Email = EmailTextBox.Text }; //create new user in the dbb and store the resukt IdentityResult result = userManager.Create(user, PasswordTextBox.Text); //check if succesfully registered if (result.Succeeded) { //authenticate and login new user var authenticationManager = HttpContext.Current.GetOwinContext().Authentication; var userIdentity = userManager.CreateIdentity(user, DefaultAuthenticationTypes.ApplicationCookie);//store info in session //sign in authenticationManager.SignIn(new AuthenticationProperties() { }, userIdentity); //redirect to main menu Response.Redirect("~/Secured/TodoList.aspx"); } else { //display error in the AlertFlash div StatusLabel.Text = result.Errors.FirstOrDefault(); AlertFlash.Visible = true; } }
public void IdentityUserSet_Id() { var u = new IdentityUser(); u.Id = Guid.NewGuid().ToString(); u.Id = null; }
public void GetUserClaimSyncTest() { var db = UnitTestHelper.CreateDefaultDb(); var manager = new UserManager<IdentityUser>(new UserStore<IdentityUser>(db)); var user = new IdentityUser("u1"); var result = manager.Create(user); UnitTestHelper.IsSuccess(result); Assert.NotNull(user); var claims = new[] { new Claim("c1", "v1"), new Claim("c2", "v2"), new Claim("c3", "v3") }; foreach (Claim c in claims) { UnitTestHelper.IsSuccess(manager.AddClaim(user.Id, c)); } var userClaims = new List<Claim>(manager.GetClaims(user.Id)); Assert.Equal(3, userClaims.Count); foreach (Claim c in claims) { Assert.True(userClaims.Exists(u => u.Type == c.Type && u.Value == c.Value)); } }
public void When_Not_Success_CreateAsync_Throws_CouchbaseException() { var mockBucket = new Mock<IBucket>(); mockBucket.SetupGet(e => e.Name).Returns("default"); var mockResult = new Mock<IOperationResult<IdentityUser>>(); mockResult.SetupGet(x => x.Success).Returns(false); mockResult.SetupGet(x => x.Status).Returns(ResponseStatus.KeyExists); mockBucket.Setup(x => x.InsertAsync(It.IsAny<string>(), It.IsAny<IdentityUser>())) .ReturnsAsync(mockResult.Object); var mockResult2 = new Mock<IOperationResult<string>>(); mockResult2.SetupGet(x => x.Success).Returns(false); mockResult2.SetupGet(x => x.Status).Returns(ResponseStatus.KeyExists); mockBucket.Setup(x => x.InsertAsync(It.IsAny<string>(), It.IsAny<string>())) .ReturnsAsync(mockResult2.Object); var mockResult3 = new Mock<IOperationResult<string>>(); mockResult3.SetupGet(x => x.Success).Returns(false); mockResult3.SetupGet(x => x.Status).Returns(ResponseStatus.KeyExists); mockBucket.Setup(x => x.InsertAsync(It.IsAny<string>(), It.IsAny<string>())) .ReturnsAsync(mockResult3.Object); var user = new IdentityUser("foo") { Email = "*****@*****.**" }; var store = new UserStore<IdentityUser>(new ThrowableBucket(mockBucket.Object)); Assert.Throws<CouchbaseException>(async () => await store.CreateAsync(user)); }
public async Task <IdentityUser> FindUser(string userName, string password) { IdentityUser user = await _userManager.FindAsync(userName, password); return(user); }
public async Task<IdentityResult> RegisterUser(UserModel userModel, string roleName) { IdentityUser user = new IdentityUser { UserName = userModel.UserName, Email = userModel.UserName }; var result = await _userManager.CreateAsync(user, userModel.Password); if (result == IdentityResult.Success) { var role = await _roleManager.FindByNameAsync(roleName); if (role == null) { role = new IdentityRole(roleName); var roleresult = await _roleManager.CreateAsync(role); } var userFromDb = await _userManager.FindByNameAsync(user.UserName); if (userFromDb != null) { await _userManager.AddToRoleAsync(userFromDb.Id, roleName); } } return result; }