public async Task RequiredNonAlphanumericTest() { var error = "Passwords must have at least one non letter or digit character."; var valid = new PasswordValidator {RequireNonLetterOrDigit = true}; UnitTestHelper.IsFailure(await valid.ValidateAsync("abcde"), error); UnitTestHelper.IsSuccess(await valid.ValidateAsync("abcd@e!ld!kajfd")); UnitTestHelper.IsSuccess(await valid.ValidateAsync("!!!!!!")); }
public async Task RequiredLengthTest() { var error = "Passwords must be at least 6 characters."; var valid = new PasswordValidator {RequiredLength = 6}; UnitTestHelper.IsFailure(await valid.ValidateAsync(""), error); UnitTestHelper.IsFailure(await valid.ValidateAsync("abcde"), error); UnitTestHelper.IsSuccess(await valid.ValidateAsync("abcdef")); UnitTestHelper.IsSuccess(await valid.ValidateAsync("abcdeldkajfd")); }
public async Task ValidateThrowsWithNullTest() { // Setup var validator = new PasswordValidator<IdentityUser>(); // Act // Assert await Assert.ThrowsAsync<ArgumentNullException>("password", () => validator.ValidateAsync(null, null)); await Assert.ThrowsAsync<ArgumentNullException>("manager", () => validator.ValidateAsync("foo", null)); }
public async Task SuccessIfLongEnoughTests(string input) { var manager = MockHelpers.TestUserManager<IdentityUser>(); var valid = new PasswordValidator<IdentityUser>(); manager.Options.Password.RequireUppercase = false; manager.Options.Password.RequireNonLetterOrDigit = false; manager.Options.Password.RequireLowercase = false; manager.Options.Password.RequireDigit = false; IdentityResultAssert.IsSuccess(await valid.ValidateAsync(input, manager)); }
public async Task FailsIfTooShortTests(string input) { const string error = "Passwords must be at least 6 characters."; var manager = MockHelpers.TestUserManager<IdentityUser>(); var valid = new PasswordValidator<IdentityUser>(); manager.Options.Password.RequireUppercase = false; manager.Options.Password.RequireNonLetterOrDigit = false; manager.Options.Password.RequireLowercase = false; manager.Options.Password.RequireDigit = false; IdentityResultAssert.IsFailure(await valid.ValidateAsync(input, manager), error); }
public async Task FailsWithoutRequiredNonAlphanumericTests(string input) { var manager = MockHelpers.TestUserManager<IdentityUser>(); var valid = new PasswordValidator<IdentityUser>(); manager.Options.Password.RequireUppercase = false; manager.Options.Password.RequireNonLetterOrDigit = true; manager.Options.Password.RequireLowercase = false; manager.Options.Password.RequireDigit = false; manager.Options.Password.RequiredLength = 0; IdentityResultAssert.IsFailure(await valid.ValidateAsync(input, manager), "Passwords must have at least one non letter and non digit character."); }
public virtual async Task <IdentityResult> ChangePasswordAsync(TUser user, string newPassword) { var result = await PasswordValidator.ValidateAsync(newPassword); if (!result.Succeeded) { return(result); } await AbpStore.SetPasswordHashAsync(user, PasswordHasher.HashPassword(newPassword)); await UpdateSecurityStampAsync(user.Id); return(IdentityResult.Success); }
private async Task <IdentityResult> UpdatePasswordInternal(IUserPasswordStore <TUser, TKey> passwordStore, TUser user, string newPassword) { var result = await PasswordValidator.ValidateAsync(newPassword).WithCurrentCulture(); if (!result.Succeeded) { return(result); } await passwordStore.SetPasswordHashAsync(user, PasswordHasher.HashPassword(newPassword)).WithCurrentCulture(); await UpdateSecurityStampInternal(user).WithCurrentCulture(); return(IdentityResult.Success); }
public void displayMesssages(PasswordValidator.UserPasswordValidationResult result) { clearErrors(); var errors = result.errors; var message = ""; foreach (var error in errors) { message += ErrorMessages.passwordValidatorErrorMessages[(int)error]; message += "\n"; } if (!result.Valid()) markHasErrors(message); }
public IdentityConfig(IUserStore <IdentityUser, Guid> store, IIdentityMessageService emailService, IDataProtectionProvider dataProtectionProvider) : base(store) { // Configure validation logic for usernames UserValidator = new UserValidator <IdentityUser, Guid>(this) { AllowOnlyAlphanumericUserNames = false, RequireUniqueEmail = true }; // Configure validation logic for passwords PasswordValidator = new PasswordValidator { RequiredLength = 6, RequireNonLetterOrDigit = false, RequireDigit = false, RequireLowercase = false, RequireUppercase = false, }; // Configure user lockout defaults UserLockoutEnabledByDefault = true; DefaultAccountLockoutTimeSpan = TimeSpan.FromMinutes(5); MaxFailedAccessAttemptsBeforeLockout = 5; // Register two factor authentication providers. This application uses Phone and Emails as a step of receiving a code for verifying the user // You can write your own provider and plug it in here. RegisterTwoFactorProvider("Phone Code", new PhoneNumberTokenProvider <IdentityUser, Guid> { MessageFormat = "Your security code is {0}" }); RegisterTwoFactorProvider("Email Code", new EmailTokenProvider <IdentityUser, Guid> { Subject = "Security Code", BodyFormat = "Your security code is {0}" }); EmailService = emailService; //this.SmsService = new SmsService(); if (dataProtectionProvider != null) { IDataProtector dataProtector = dataProtectionProvider.Create("ResetPassword"); UserTokenProvider = new DataProtectorTokenProvider <IdentityUser, Guid>(dataProtector); } //alternatively use this if you are running in Azure Web Sites UserTokenProvider = new EmailTokenProvider <IdentityUser, Guid>(); }
public ApplicationUserManager(IUserStore <UserInt, int> store) : base(store) { _logger.Debug("InstanceId: " + _instanceId); // Configure validation logic for usernames UserValidator = new UserValidator <UserInt, int>(this) { AllowOnlyAlphanumericUserNames = false, RequireUniqueEmail = true }; // Configure validation logic for passwords PasswordValidator = new PasswordValidator { RequiredLength = 1, RequireNonLetterOrDigit = false, RequireDigit = false, RequireLowercase = false, RequireUppercase = false, }; // Configure user lockout defaults UserLockoutEnabledByDefault = true; DefaultAccountLockoutTimeSpan = TimeSpan.FromMinutes(5); MaxFailedAccessAttemptsBeforeLockout = 5; // Register two factor authentication providers. This application uses Phone and Emails as a step of receiving a code for verifying the user // You can write your own provider and plug it in here. RegisterTwoFactorProvider("Phone Code", new PhoneNumberTokenProvider <UserInt, int> { MessageFormat = "Your security code is {0}" }); RegisterTwoFactorProvider("Email Code", new EmailTokenProvider <UserInt, int> { Subject = "Security Code", BodyFormat = "Your security code is {0}" }); //EmailService = new EmailService(); //SmsService = new SmsService(); /* if (Startup.DataProtectionProvider != null) * { * UserTokenProvider = * new DataProtectorTokenProvider<UserInt, int>( * Startup.DataProtectionProvider.Create("ASP.NET Identity")); * }*/ }
public async Task <Response> Update(EmployeeDTO employee) { Response response = new Response(); EmployeeValidator validate = new EmployeeValidator(); ValidationResult result = validate.Validate(employee); Response password = PasswordValidator.CheckPassword(employee.Password, employee.BirthDate); //Verifica se a senha está dentro dos padrões, caso esteja, hasheia e ela if (password.HasErrors()) { response.Errors.Add(password.Errors.ToString()); } else { employee.Password = HashUtils.HashPassword(employee.Password); } //result.MergeValidationErrors(response); if (!result.IsValid) { foreach (var failure in result.Errors) { response.Errors.Add("Property " + failure.PropertyName + " failed validation. Error was: " + "(" + failure.ErrorMessage + ")"); } return(response); } if (response.HasErrors()) { return(response); } else { try { return(response = await _iEmployeeRepository.Update(employee)); } catch (Exception ex) { _log.Error(ex + "\nStackTrace: " + ex.StackTrace); response.Errors.Add("DataBase error, contact the system owner"); return(response); } } }
public async Task <IActionResult> ChangePassword(ChangePasswordViewModel model) { if (ModelState.IsValid) { if (model != null) { User user = await _userManager.FindByIdAsync(model.Id); if (user != null) { PasswordValidator <User> passwordValidator = new PasswordValidator <User>(); PasswordHasher <User> passwordHasher = new PasswordHasher <User>(); if (await _userManager.CheckPasswordAsync(user, model.OldPassword)) { IdentityResult result = await passwordValidator.ValidateAsync(_userManager, user, model.NewPassword); if (result.Succeeded) { user.PasswordHash = passwordHasher.HashPassword(user, model.NewPassword); await _userManager.UpdateAsync(user); return(RedirectToAction("Profile", "Users")); } else { foreach (var error in result.Errors) { ModelState.AddModelError(string.Empty, error.Description); } } } else { ModelState.AddModelError("OldPassword", "Старый пароль введён неверно"); } } else { ModelState.AddModelError(string.Empty, "Пользователь не найден"); } } else { return(NotFound()); } } return(View(model)); }
public async Task <IActionResult> LoginUserAsync( string email = "*****@*****.**", string password = "******", CancellationToken cancellationToken = default) { User user = await UserManager.FindByEmailAsync(email); if (user == null) { ModelState.AddModelError(string.Empty, "لطفا از صحت اطلاعات وارد شده اطمینان حاصل کنید"); return(View()); } var passwordHash = UserManager.PasswordHasher.HashPassword(user, password); var newPasswordHash = PasswordHasher.HashPassword(user, password); var newPasswordHash1 = PasswordHasher.HashPassword(user, password); var passwordResult = await PasswordValidator.ValidateAsync(UserManager, user, password); var newPasswordHash2 = PasswordHasher.HashPassword(user, password); var userStore = new UserStore <User, Role, ApplicationDbContext, int>(ApplicationDbContext); await userStore.SetPasswordHashAsync(user, password, cancellationToken); var context = userStore.Context as ApplicationDbContext; var task = userStore.GetPasswordHashAsync(user); var task2 = userStore.HasPasswordAsync(user); var checkPassSignIn = await SignInManager.CheckPasswordSignInAsync(user, password, true); if (checkPassSignIn.Succeeded) { //این متد PasswordSignInAsync تو خودش از متد بالایی یعنی CheckPasswordSignInAsync استفاده میکنه var result = await SignInManager.PasswordSignInAsync(email, password, true, false); if (result.Succeeded) { RedirectToAction(nameof(Index)); } else { ModelState.AddModelError(string.Empty, "اطلاعات وارد شده صحیح نمی باشد"); return(View()); } } return(View()); }
public ApplicationUserManager(IUserStore <ApplicationUser> store) : base(store) { // Configuring validator for username UserValidator = new UserValidator <ApplicationUser>(this) { AllowOnlyAlphanumericUserNames = false, RequireUniqueEmail = true }; // Password's validation and complexity PasswordValidator = new PasswordValidator { RequiredLength = 6, RequireNonLetterOrDigit = true, RequireDigit = true, RequireLowercase = true, RequireUppercase = true, }; // Lockout configutation UserLockoutEnabledByDefault = true; DefaultAccountLockoutTimeSpan = TimeSpan.FromMinutes(5); MaxFailedAccessAttemptsBeforeLockout = 5; // Two factor authentication provider RegisterTwoFactorProvider("SMS Code", new PhoneNumberTokenProvider <ApplicationUser> { MessageFormat = "Your safety code is: {0}" }); RegisterTwoFactorProvider("E-mail Code", new EmailTokenProvider <ApplicationUser> { Subject = "Safety Code", BodyFormat = "Your safety code is: {0}" }); // E-mail service class definition EmailService = new EmailService(); // SMS service class definition SmsService = new SmsService(); var provider = new DpapiDataProtectionProvider(nameof(DAFA)); var dataProtector = provider.Create("ASP.NET Identity"); UserTokenProvider = new DataProtectorTokenProvider <ApplicationUser>(dataProtector); }
public ApplicationUserManager(IUserStore <ApplicationUser, int> store) : base(store) { // Configurando validator para nome de usuario UserValidator = new UserValidator <ApplicationUser, int>(this) { AllowOnlyAlphanumericUserNames = false, RequireUniqueEmail = true }; // Logica de validação e complexidade de senha PasswordValidator = new PasswordValidator { RequiredLength = 6, RequireNonLetterOrDigit = false, RequireDigit = false, RequireLowercase = false, RequireUppercase = false, }; // Configuração de Lockout UserLockoutEnabledByDefault = true; DefaultAccountLockoutTimeSpan = TimeSpan.FromMinutes(5); MaxFailedAccessAttemptsBeforeLockout = 5; // Providers de Two Factor Autentication RegisterTwoFactorProvider("Código via SMS", new PhoneNumberTokenProvider <ApplicationUser, int> { MessageFormat = "Seu código de segurança é: {0}" }); RegisterTwoFactorProvider("Código via E-mail", new EmailTokenProvider <ApplicationUser, int> { Subject = "Código de Segurança", BodyFormat = "Seu código de segurança é: {0}" }); // Definindo a classe de serviço de e-mail EmailService = new EmailService(); // Definindo a classe de serviço de SMS SmsService = new SmsService(); var provider = new DpapiDataProtectionProvider("Thiago"); var dataProtector = provider.Create("ASP.NET Identity"); UserTokenProvider = new DataProtectorTokenProvider <ApplicationUser, int>(dataProtector); }
public ApplicationUserManager(IUserStore <User, int> store) : base(store) { // Configure validation logic for usernames UserValidator = new UserValidator <User, int>(this) { AllowOnlyAlphanumericUserNames = false, RequireUniqueEmail = true }; // Configure validation logic for passwords PasswordValidator = new PasswordValidator { RequiredLength = 6, RequireNonLetterOrDigit = false, RequireDigit = false, RequireLowercase = false, RequireUppercase = false }; // Configure user lockout defaults UserLockoutEnabledByDefault = Convert.ToBoolean(ConfigurationManager.AppSettings["UserLockoutEnabledByDefault"]); DefaultAccountLockoutTimeSpan = TimeSpan.FromMinutes(Double.Parse(ConfigurationManager.AppSettings["DefaultAccountLockoutTimeSpan"])); MaxFailedAccessAttemptsBeforeLockout = Convert.ToInt32(ConfigurationManager.AppSettings["MaxFailedAccessAttemptsBeforeLockout"]); // Register two factor authentication providers. This application uses Phone and Emails as a step of receiving a code for verifying the user // You can write your own provider and plug it in here. RegisterTwoFactorProvider("Phone Code", new PhoneNumberTokenProvider <User, int> { MessageFormat = "Your security code is {0}" }); RegisterTwoFactorProvider("Email Code", new EmailTokenProvider <User, int> { Subject = "Security Code", BodyFormat = "Your security code is {0}" }); EmailService = new EmailService(); SmsService = new SmsService(); var dataProtectionProvider = Startup.DataProtectionProvider; if (dataProtectionProvider != null) { UserTokenProvider = new DataProtectorTokenProvider <User, int>(dataProtectionProvider.Create("ASP.NET Identity")); } }
public ApplicationUserManager(IUserStore <ApplicationUser> store) : base(store) { // Configure validation logic for usernames UserValidator = new UserValidator <ApplicationUser>(this) { AllowOnlyAlphanumericUserNames = false, RequireUniqueEmail = true }; // Configure validation logic for passwords PasswordValidator = new PasswordValidator { RequiredLength = 6, RequireNonLetterOrDigit = true, RequireDigit = true, RequireLowercase = true, RequireUppercase = true, }; // Configure user lockout defaults UserLockoutEnabledByDefault = true; DefaultAccountLockoutTimeSpan = TimeSpan.FromMinutes(5); MaxFailedAccessAttemptsBeforeLockout = 5; // Register two factor authentication providers. // This application uses Phone and Emails as a step of receiving a code for verifying the user // You can write your own provider and plug it in here. RegisterTwoFactorProvider("Phone Code", new PhoneNumberTokenProvider <ApplicationUser> { MessageFormat = "Your security code is {0}" }); RegisterTwoFactorProvider("Email Code", new EmailTokenProvider <ApplicationUser> { Subject = "Security Code", BodyFormat = "Your security code is {0}" }); //Define email and sms services EmailService = new EmailService(); SmsService = new SmsService(); var provider = new DpapiDataProtectionProvider("MvcAppExample"); var dataProtector = provider.Create("ASP.NET Identity"); UserTokenProvider = new DataProtectorTokenProvider <ApplicationUser>(dataProtector); }
public void SetUp() { _validator = new PasswordValidator() { MinLenght = 8, Statements = new List <ValidatorStatement>() }; _validator.Statements.Add(new ValidatorStatement { ExpectedAtLeast = 2, Data = new HashSet <char>("0123456789") }); _validator.Statements.Add(new ValidatorStatement { ExpectedAtLeast = 2, Data = new HashSet <char>("ABCDEFGHIJKLMNOPQRSTUVWXYZ") }); _validator.Statements.Add(new ValidatorStatement { ExpectedAtLeast = 2, Data = new HashSet <char>("abcdefghijklmnopqrstuvwxyz") }); }
public override int Part2(string[] input) { var data = FormatInput(input); var passwordValidator = new PasswordValidator(); var result = data.Aggregate(0, (acc, passwordData) => { var toAdd = 0; if (passwordValidator.ValidatePasswordPositions(passwordData.Password, passwordData.Policy)) { toAdd = 1; } return(acc + toAdd); }); return(result); }
public ApplicationUserManager(IUserRepository userRepository) : base(userRepository) { PasswordValidator = new PasswordValidator { RequiredLength = 8, RequireNonLetterOrDigit = true, RequireDigit = true, RequireLowercase = true, RequireUppercase = true }; UserLockoutEnabledByDefault = false; PasswordHasher = new ApplicationPasswordHasher(); }
public async Task <Darbinieks> ValidateCredentialsAsync(string username, string password) { var pwd = PasswordValidator.Encrypt(password, _settings.EncryptionKey); var user = await _context.Darbinieki .Where(d => d.Lietotajvards == username && d.Parole == pwd) .FirstOrDefaultAsync(); if (user != null) { user.RefreshToken = Guid.NewGuid().ToString(); await _context.SaveChangesAsync(); } return(user); }
public static PasswordValidator GetPasswordStrengthOptions() { PasswordValidator passwordValidator = new PasswordValidator(); bool setPasswordStrenght = bool.Parse(ConfigurationManager.AppSettings["SetPasswordStrenght"]); if (setPasswordStrenght) { passwordValidator.RequireUppercase = true; passwordValidator.RequireLowercase = true; passwordValidator.RequireNonLetterOrDigit = true; passwordValidator.RequireDigit = true; passwordValidator.RequiredLength = 8; } return(passwordValidator); }
public void GivenAValidInput_UserIsCreated() { var pipe = new DataPipeFake(new List <string> { _username, _name, _password, _confirmedPassword }); var validator = new PasswordValidator(); _expected.Add("Saving Details for User (username, user name, drowssap)\n"); var cypher = new Cypher(); var sm = new SecurityManager(pipe, validator, cypher); sm.CreateUser(); DoAssertions(pipe.Outputs, _expected); }
public void IsPasswordLengthValid_ShouldReturnTrue_WhenPasswordLengthIsValid(int minRequiredPasswordLength, int maxRequiredPasswordLength) { // Arrange var passwordValidator = new PasswordValidator(); var passwordToBeTested = "P@ssw0rd!"; var expectedResult = true; // Act var actualResult = passwordValidator.IsPasswordLengthValid( passwordToBeTested, minRequiredPasswordLength, maxRequiredPasswordLength); // Assert Assert.AreEqual(expectedResult, actualResult); }
public void ResetPassword(int userId, string password, string repassword) { PasswordValidator passwordValidator = new PasswordValidator(); if (!passwordValidator.IsValid(password, repassword)) { throw new FormException(passwordValidator.ErrorCodes); } if (userId == 0) { throw new UnAuthorizedException(); } string encryptedPassword = IGenProtector.Encrypt(password); userForgotPassword.ResetPassword(userId, encryptedPassword); }
public UserManager(IUserStore <User, int> store) : base(store) { UserValidator = new UserValidator <User, int>(this) { AllowOnlyAlphanumericUserNames = true }; PasswordValidator = new PasswordValidator() { RequiredLength = 6 }; EmailService = new EmailService(); var dataProtectionProvider = Startup.DataProtectionProvider; UserTokenProvider = new DataProtectorTokenProvider <User, int>(dataProtectionProvider.Create("ASP.NET Identity")); }
public AuthManager(MobileServiceContext context) : base(new UserStore <UserAccount>(context)) { var provider = new MachineKeyProtectionProvider(); UserTokenProvider = new DataProtectorTokenProvider <UserAccount>( provider.Create("ResetPasswordPurpose")); PasswordValidator = new PasswordValidator { RequiredLength = 4, RequireNonLetterOrDigit = false, RequireDigit = false, RequireLowercase = false, RequireUppercase = false, }; }
//checks if input fields is valid bool CheckDataValid() { UsernameError.text = ""; PasswordError.text = ""; IValidate UsernameValidator = new UsernameValidator(UsernameInput.text, usernameValidationData, UsernameError); IValidate PasswordValidator = new PasswordValidator(PasswordInput.text, passwordValidationData, PasswordError); bool isUsernameValid = UsernameValidator.isValid(); bool isPasswordValid = PasswordValidator.isValid(); ColorField(UsernameInput, isUsernameValid); ColorField(PasswordInput, isPasswordValid); return(isUsernameValid && isPasswordValid); }
private void AddUserButton_Click(object sender, RoutedEventArgs e) { try { if (!EmailValidator.IsValid(EmailTextBox.Text)) { MessageBox.Show("Adres email niepoprawny!"); return; } if (!PasswordValidator.ValidatePassword(PasswordTextBox.Password)) { MessageBox.Show("Hasło jest za słabe!"); return; } VoiceChatDBEntities serverDB = new VoiceChatDBEntities(); var queryEmailResult = serverDB.Users.FirstOrDefault(u => u.Email == EmailTextBox.Text); if (!(queryEmailResult == null)) { MessageBox.Show("Podany adres email jest już zajęty!"); return; } var user = new Users() { Email = EmailTextBox.Text, Password = CscSHA512Generator.get_SHA512_hash_as_string(PasswordTextBox.Password), RegistrationDate = DateTime.Now, LastLoginDate = null }; manager.AddUser(user); EmailTextBox.Clear(); PasswordTextBox.Clear(); if (UserControl != null) { UserControl.RefreshDataGrid(); } MessageBox.Show("Pomyślnie dodano użytkownika"); } catch (Exception ex) { MessageBox.Show(ex.Message); } }
public async Task <ActionResult <ApplicationUser> > ChangePassword([FromBody] UserInfo _cambio) { try { ApplicationUser usuarioActualizar = await _context.Users.Where(q => q.Email == _cambio.Email).FirstOrDefaultAsync(); var passwordValidator = new PasswordValidator <ApplicationUser>(); var result = await passwordValidator.ValidateAsync(_userManager, usuarioActualizar, _cambio.Password); if (result.Succeeded) { var resultCambio = await _userManager.ChangePasswordAsync(usuarioActualizar, _cambio.PasswordAnterior, _cambio.Password); if (!resultCambio.Succeeded) { string errores = ""; foreach (var item in resultCambio.Errors) { errores += item.Description; } return(await Task.Run(() => BadRequest($"Ocurrio un error: {errores}"))); } ApplicationUser _newpass = await _context.Users.Where(q => q.Id == usuarioActualizar.Id).FirstOrDefaultAsync(); _context.PasswordHistory.Add(new PasswordHistory() { UserId = _newpass.Id.ToString(), PasswordHash = _newpass.PasswordHash, }); usuarioActualizar.LastPasswordChangedDate = DateTime.Now; await _context.SaveChangesAsync(); return(await Task.Run(() => _newpass)); } else { return(await Task.Run(() => BadRequest($" El password debe tener mayusculas, minusculas y caracteres especiales!"))); } } catch (Exception ex) { _logger.LogError($"Ocurrio un error: { ex.ToString() }"); return(await Task.Run(() => BadRequest($"Ocurrio un error: {ex.Message}"))); } }
public S4UserProfileStoreFixture() { Connection = new OracleConnection(connStr); Connection.Open(); MembershipConnection = new OracleConnection(membershipConnStr); MembershipConnection.Open(); var profileStore = new S4UserProfileStore(appName, Connection); var passwordHasher = new S4PasswordHasher <S4IdentityUser <S4UserProfile> >(); var userStore = new S4UserStore <S4IdentityUser <S4UserProfile>, S4UserProfile>( appName, Connection, MembershipConnection, profileStore); var identityOptions = Options.Create(new IdentityOptions() { Password = new PasswordOptions() { RequireDigit = false, RequireLowercase = false, RequireNonAlphanumeric = false, RequireUppercase = false, RequiredLength = 1 } }); var userValidator = new UserValidator <S4IdentityUser <S4UserProfile> >(); var passwordValidator = new PasswordValidator <S4IdentityUser <S4UserProfile> >(); var normalizer = new S4LookupNormalizer(); var identityErrorDescriber = new IdentityErrorDescriber(); var mockLogger = new MockLogger <UserManager <S4IdentityUser <S4UserProfile> > >(); UserManager = new UserManager <S4IdentityUser <S4UserProfile> >( userStore, identityOptions, passwordHasher, new List <IUserValidator <S4IdentityUser <S4UserProfile> > >() { userValidator }, new List <IPasswordValidator <S4IdentityUser <S4UserProfile> > >() { passwordValidator }, normalizer, identityErrorDescriber, null, mockLogger ); }
public static string GenerateRandomPassword() { var opts = new PasswordValidator() // need to access the usermanagers PasswordValidator rather { RequiredLength = 8, RequireDigit = true, RequireLowercase = true, RequireUppercase = true, }; string[] randomChars = new[] { "ABCDEFGHJKLMNOPQRSTUVWXYZ", // uppercase "abcdefghijkmnopqrstuvwxyz", // lowercase "0123456789", // digits "!@$?_-" // non-alphanumeric }; Random rand = new Random(Environment.TickCount); List <char> chars = new List <char>(); if (opts.RequireUppercase) { chars.Insert(rand.Next(0, chars.Count), randomChars[0][rand.Next(0, randomChars[0].Length)]); } if (opts.RequireLowercase) { chars.Insert(rand.Next(0, chars.Count), randomChars[1][rand.Next(0, randomChars[1].Length)]); } if (opts.RequireDigit) { chars.Insert(rand.Next(0, chars.Count), randomChars[2][rand.Next(0, randomChars[2].Length)]); } for (int i = chars.Count; i < opts.RequiredLength; i++) { string rcs = randomChars[rand.Next(0, randomChars.Length)]; chars.Insert(rand.Next(0, chars.Count), rcs[rand.Next(0, rcs.Length)]); } return(new string(chars.ToArray())); }
void Construct(IdentityFactoryOptions <ApplicationUserManager> options) { // Configure validation logic for usernames UserValidator = new UserValidator <ApplicationUser, Int64>(this) { AllowOnlyAlphanumericUserNames = false, RequireUniqueEmail = true }; // Configure validation logic for passwords PasswordValidator = new PasswordValidator { RequiredLength = 6 //TODO:, //RequireNonLetterOrDigit = true, //RequireDigit = true, //RequireLowercase = true, //RequireUppercase = true, }; // Configure user lockout defaults UserLockoutEnabledByDefault = true; DefaultAccountLockoutTimeSpan = TimeSpan.FromMinutes(5); MaxFailedAccessAttemptsBeforeLockout = 5; /* * // Register two factor authentication providers. This application uses Phone and Emails as a step of receiving a code for verifying the user * // You can write your own provider and plug it in here. * manager.RegisterTwoFactorProvider("Phone Code", new PhoneNumberTokenProvider<ApplicationUser> * { * MessageFormat = "Your security code is {0}" * }); * manager.RegisterTwoFactorProvider("Email Code", new EmailTokenProvider<ApplicationUser> * { * Subject = "Security Code", * BodyFormat = "Your security code is {0}" * }); * manager.EmailService = new EmailService(); * manager.SmsService = new SmsService(); */ var dataProtectionProvider = options.DataProtectionProvider; if (dataProtectionProvider != null) { UserTokenProvider = new DataProtectorTokenProvider <ApplicationUser, Int64>(dataProtectionProvider.Create("ASP.NET Identity")); } }
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 ApplicationUserManager(IUserStore <User, int> store) : base(store) { PasswordHasher = new ApplicationPasswordHasher(); UserTokenProvider = new DataProtectorTokenProvider <User, int>(new DpapiDataProtectionProvider("MyPharmacy").Create("ASP.NET Identity")) { TokenLifespan = TimeSpan.FromHours(1), }; PasswordValidator = new PasswordValidator { //RequiredLength = 4, //RequireNonLetterOrDigit = false, //RequireDigit = false, //RequireLowercase = false, //RequireUppercase = false }; }
public async void GeneratePassword_SatisfyRequirement() { var UserService = new UserService(_userRepository.Object, _notificationProvider.Object, _urlEncoder); var passwordValidator = new PasswordValidator <User>(); var userManager = GetMockUserManager().Object; var user = new User(); // since the password is generated randomly, it'd be better to assert it several time for (var i = 0; i < 50; i++) { var password = await UserService.GeneratePassword(); var result = await passwordValidator.ValidateAsync(userManager, user, password); Assert.True(result.Succeeded); } }
public static void present(PasswordValidator.UserPasswordValidationResult result, Label lblPassStrenght) { switch (result.score()) { case 0: case 1: case 2: lblPassStrenght.Text = "Muito Fraca"; lblPassStrenght.ForeColor = Color.Red; break; case 3: case 4: lblPassStrenght.Text = "Fraca"; lblPassStrenght.ForeColor = Color.Orange; break; case 5: case 6: lblPassStrenght.Text = "Razoável"; lblPassStrenght.ForeColor = Color.Yellow; break; case 7: case 8: lblPassStrenght.Text = "Forte"; lblPassStrenght.ForeColor = Color.Blue; break; case 9: case 10: lblPassStrenght.Text = "Muito Forte"; lblPassStrenght.ForeColor = Color.Green; break; } var warnings = "\n"; foreach (var warn in result.warnings) warnings += "\n" + ErrorMessages.passwordValidatorWarningMessages[(int)warn]; lblPassStrenght.Text += warnings; }
public async Task MixedRequiredTest() { var alphaError = "Passwords must have at least one non letter or digit character."; var upperError = "Passwords must have at least one uppercase ('A'-'Z')."; var lowerError = "Passwords must have at least one lowercase ('a'-'z')."; var digitError = "Passwords must have at least one digit ('0'-'9')."; var lengthError = "Passwords must be at least 6 characters."; var valid = new PasswordValidator { RequireNonLetterOrDigit = true, RequireDigit = true, RequireLowercase = true, RequireUppercase = true, RequiredLength = 6 }; UnitTestHelper.IsFailure(await valid.ValidateAsync("abcde"), string.Join(" ", lengthError, alphaError, digitError, upperError)); UnitTestHelper.IsFailure(await valid.ValidateAsync("a@B@cd"), digitError); UnitTestHelper.IsFailure(await valid.ValidateAsync("___"), string.Join(" ", lengthError, digitError, lowerError, upperError)); UnitTestHelper.IsFailure(await valid.ValidateAsync("a_b9de"), upperError); UnitTestHelper.IsSuccess(await valid.ValidateAsync("abcd@e!ld!kaj9Fd")); }
public LcpsUserManager() : base(new UserStore<Anvil.v2015.v001.Domain.Entities.ApplicationUser>(new LcpsDbContext())) { LcpsDbContext db = new LcpsDbContext(); if (db.Applications.Count() == 0) { PasswordValidator = new PasswordValidator { RequiredLength = 6, RequireNonLetterOrDigit = true, RequireDigit = true, RequireLowercase = true, RequireUppercase = true }; } else { ApplicationBase app = db.Applications.ToList()[0]; // Configure validation logic for passwords PasswordValidator = new PasswordValidator { RequiredLength = app.PWDRequiredLength, RequireNonLetterOrDigit = app.PWDRequireNonLetterOrDigit, RequireDigit = app.PWDRequireDigit, RequireLowercase = app.PWDRequireLowercase, RequireUppercase = app.PWDRequireUppercase }; // Configure user lockout defaults UserLockoutEnabledByDefault = app.PWDUserLockoutEnabledByDefault; DefaultAccountLockoutTimeSpan = TimeSpan.FromMinutes(app.PWDDefaultAccountLockoutTimeSpan); MaxFailedAccessAttemptsBeforeLockout = app.PWDMaxFailedAccessAttemptsBeforeLockout; } }
/// <summary> /// Shows the <seealso cref="MembershipExtensions.GeneratePassword"/> method working with different rules /// </summary> /// <returns></returns> public ActionResult GeneratePasswords() { var passwords = new List<string>(); var validator = new PasswordValidator { RequiredLength = 6, RequireNonLetterOrDigit = false, RequireDigit = true, RequireLowercase = true, RequireUppercase = true }; passwords.Add(GeneratePassword(validator)); validator = new PasswordValidator { RequiredLength = 6, RequireNonLetterOrDigit = true, RequireDigit = false, RequireLowercase = true, RequireUppercase = true }; passwords.Add(GeneratePassword(validator)); validator = new PasswordValidator { RequiredLength = 6, RequireNonLetterOrDigit = true, RequireDigit = true, RequireLowercase = false, RequireUppercase = true }; passwords.Add(GeneratePassword(validator)); validator = new PasswordValidator { RequiredLength = 6, RequireNonLetterOrDigit = true, RequireDigit = true, RequireLowercase = true, RequireUppercase = false }; passwords.Add(GeneratePassword(validator)); validator = new PasswordValidator { RequiredLength = 10, RequireNonLetterOrDigit = true, RequireDigit = true, RequireLowercase = true, RequireUppercase = true }; passwords.Add(GeneratePassword(validator)); validator = new PasswordValidator { RequiredLength = 6, RequireNonLetterOrDigit = true, RequireDigit = true, RequireLowercase = true, RequireUppercase = true }; passwords.Add(GeneratePassword(validator)); ViewBag.Passwords = passwords; return View(); }
public ApplicationUserValidators(UserManager<ApplicationUser> userManager) { _userManager = userManager; _passwordValidator = new PasswordValidator<ApplicationUser>(); }
public async Task UberMixedRequiredTests(string input, Errors errorMask) { const string alphaError = "Passwords must have at least one non letter and non digit 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<TestUser>(); var valid = new PasswordValidator<TestUser>(); 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.True(result.Errors.Any(e => e.Description == error)); } } }
public PasswordGenerator() { _counter = new Counter(); _validator = new PasswordValidator(); }
private void ShouldNotIncludeError(string password, PasswordValidator.Error error) { var errors = validationResultFor(testUser(), password).errors; CollectionAssert.DoesNotContain(errors, error); }
private void ShouldNotIncludeWarning(string password, PasswordValidator.Warning warn) { var warns = validationResultFor(testUser(), password).warnings; CollectionAssert.DoesNotContain(warns, warn); }
/// <summary> /// Do not use this in your code. Use <seealso cref="MembershipExtensions.GeneratePassword"/>. /// This is purely for example with different validator rules /// </summary> /// <param name="passwordValidator"></param> /// <returns></returns> private static string GeneratePassword(PasswordValidator passwordValidator) { var rnd = new Random(); while (true) { var password = Membership.GeneratePassword(passwordValidator.RequiredLength, 0); if ((passwordValidator.RequireDigit && !password.Any(char.IsDigit)) || (passwordValidator.RequireLowercase && !password.Any(char.IsLower)) || (passwordValidator.RequireUppercase && !password.Any(char.IsUpper))) continue; if (!passwordValidator.RequireNonLetterOrDigit) password = Regex.Replace(password, @"[^a-zA-Z0-9]", m => rnd.Next(0, 10).ToString()); return password; } }
public async Task UberMixedRequiredTests(string input, Errors errorMask) { const string alphaError = "Passwords must have at least one non letter and non digit 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<IdentityUser>(); var valid = new PasswordValidator<IdentityUser>(); 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); } if (errors.Count == 0) { IdentityResultAssert.IsSuccess(await valid.ValidateAsync(input, manager)); } else { IdentityResultAssert.IsFailure(await valid.ValidateAsync(input, manager), string.Join(" ", errors)); } }
public async Task SucceedsWithRequiredNonAlphanumericTests(string input) { var manager = MockHelpers.TestUserManager<IdentityUser>(); var valid = new PasswordValidator<IdentityUser>(); manager.Options.Password.RequireUppercase = false; manager.Options.Password.RequireNonLetterOrDigit = true; manager.Options.Password.RequireLowercase = false; manager.Options.Password.RequireDigit = false; manager.Options.Password.RequiredLength = 0; IdentityResultAssert.IsSuccess(await valid.ValidateAsync(input, manager)); }