public string Authenticate([FromBody] LoginModel model) { var username = model.UserName; var password = model.Password; var salt = _context.User.SingleOrDefault(x => x.UserName == username)?.PasswordSalt; var hashedPassword = PasswordHashGenerator.ComputeHash(password, new SHA256CryptoServiceProvider(), PasswordHashGenerator.StringToByteArray(salt)); var user = _context.User.SingleOrDefault(x => x.UserName == username && x.PasswordHash == hashedPassword); // return null if user not found if (user == null) { return(null); } // authentication successful so generate jwt token var tokenHandler = new JwtSecurityTokenHandler(); var key = Encoding.ASCII.GetBytes(this._appSettings.Secret); var tokenDescriptor = new SecurityTokenDescriptor { Subject = new ClaimsIdentity(new Claim[] { new Claim(ClaimTypes.Name, user.UserId.ToString()) }), Expires = DateTime.UtcNow.AddDays(7), SigningCredentials = new SigningCredentials(new SymmetricSecurityKey(key), SecurityAlgorithms.HmacSha256Signature) }; var token = tokenHandler.CreateToken(tokenDescriptor); var stringToken = tokenHandler.WriteToken(token); return(stringToken); }
public ResultadoOperacionDto VerificaPasswordEncriptado(Usuario usuarioDTO, string password) { var resultado = new ResultadoOperacionDto(); try { var valido = false; if (usuarioDTO != null && !String.IsNullOrEmpty(usuarioDTO.Password)) { var salt = usuarioDTO.Password.Substring(usuarioDTO.Password.Length - PasswordHashGenerator.TAMANIO_B64_NUMERO_SALT); var hashedPassword = PasswordHashGenerator.CreatePasswordHash(password, salt); valido = hashedPassword.Equals(usuarioDTO.Password); } resultado.InformacionExtra = valido; resultado.Resultado = valido; } catch (Exception exception) { LogUtil.Error(exception); resultado.Resultado = false; resultado.Mensaje = exception.Message; resultado.InformacionExtra = exception; } return(resultado); }
// To protect from overposting attacks, enable the specific properties you want to bind to, for // more details, see https://aka.ms/RazorPagesCRUD. public async Task <IActionResult> OnPostAsync() { if (!ModelState.IsValid) { return(Page()); } // not really used, but i hate the idea of storing passwords in plain text User.PasswordHash = PasswordHashGenerator.GenerateHash(User.PasswordHash); if (User.ProfilePicture == null) { User.ProfilePicture = "./img/user.png"; } _context.Attach(User).State = EntityState.Modified; try { await _context.SaveChangesAsync(); } catch (DbUpdateConcurrencyException) { if (!UserExists(User.UserID)) { return(NotFound()); } else { throw; } } return(RedirectToPage("./Index")); }
public string RegisterNewBankClient(BankClientDto bankClientDto) { bankClientDto.Id = ApplicationUserIdGenerator.GenerateUniqueId( bankClientDto.FirstName, bankClientDto.LastName, ApplicationClientType.BankClient); bankClientDto.PasswordHash = PasswordHashGenerator.GetMd5Hash(bankClientDto.PasswordHash); return(_bankClientDao.Create(bankClientDto)); }
public bool SignInToApplication(string email, string password) { string userId = ""; CurrentSessionDto sessionToWorkWith = null; List <BankClientDto> allUsers = _bankClientDao.Read() .ToList(); List <CurrentSessionDto> allSessions = _currentSessionsDao.Read() .ToList(); foreach (var item in allUsers) { if (item.Email == email && PasswordHashGenerator.GetMd5Hash(password) == item.PasswordHash) { userId = item.Id; break; } } foreach (var item in allSessions) { if (item.UserId == userId) { sessionToWorkWith = item; break; } } if (sessionToWorkWith == null) { _currentSessionsDao.Create(new CurrentSessionDto() { LastOperationTime = DateTime.Now, UserId = userId, Id = Guid.NewGuid().ToString() }); return(true); } if ((DateTime.Now - sessionToWorkWith.LastOperationTime).TotalMinutes > 60D) { _currentSessionsDao.Remove(sessionToWorkWith.Id); _currentSessionsDao.Create(new CurrentSessionDto() { LastOperationTime = DateTime.Now, UserId = userId, Id = Guid.NewGuid().ToString() }); return(true); } return(false); }
public LocalAccountService(IIdentityAccessor identityAccessor, ILocalAccountStorage localAccountStorage, IdentityOptions options, PasswordHashGenerator passwordHashGenerator, ILogger<LocalAccountService> log) { _localAccountStorage = localAccountStorage; _identityAccessor = identityAccessor; _options = options; _passwordHashGenerator = passwordHashGenerator; _identityAccessor = identityAccessor; _log = log; }
public void ShouldGenerateIdempotentHash_WhenHashGenerateExecuteTwice() { var request = new SecurityRequest { ServiceName = "test", CommonName = "user", MasterPassword = "******" }; var hashGenerator = new PasswordHashGenerator(); var firstResult = hashGenerator.GenerateHash(request).GetAwaiter().GetResult(); var secondResult = hashGenerator.GenerateHash(request).GetAwaiter().GetResult(); Assert.Equal(firstResult, secondResult); }
public bool VerificaPasswordEncriptado(Usuario usuario, string password) { var valido = false; if (usuario != null && !String.IsNullOrEmpty(usuario.Password)) { var salt = usuario.Password.Substring(usuario.Password.Length - PasswordHashGenerator.TAMANIO_B64_NUMERO_SALT); var hashedPassword = PasswordHashGenerator.CreatePasswordHash(password, salt); valido = hashedPassword.Equals(usuario.Password); } return(valido); }
public void ShouldNotGenerateIdempotentHash_WhenDifferentVersion() { var request = new SecurityRequest { ServiceName = "test", CommonName = "user", MasterPassword = "******", Version = 1 }; var request2 = new SecurityRequest { ServiceName = "test", CommonName = "user", MasterPassword = "******", Version = 2 }; var hashGenerator = new PasswordHashGenerator(); var firstResult = hashGenerator.GenerateHash(request).GetAwaiter().GetResult(); var secondResult = hashGenerator.GenerateHash(request2).GetAwaiter().GetResult(); Assert.NotEqual(firstResult, secondResult); }
// To protect from overposting attacks, enable the specific properties you want to bind to, for // more details, see https://aka.ms/RazorPagesCRUD. public async Task <IActionResult> OnPostAsync() { if (!ModelState.IsValid) { return(Page()); } // not really used, but i hate the idea of storing passwords in plain text User.PasswordHash = PasswordHashGenerator.GenerateHash(User.PasswordHash); if (User.ProfilePicture == null) { User.ProfilePicture = "./img/user.png"; } _context.Users.Add(User); await _context.SaveChangesAsync(); return(RedirectToPage("./Index")); }
public bool EnvioCorreoOlvidoContrasena(long idUsuario, string url) { Usuario usuario = GetById(idUsuario); var pass = PasswordHashGenerator.GenerarPassword(); var salt = pass.Substring(pass.Length - PasswordHashGenerator.TAMANIO_B64_NUMERO_SALT); var hashedPassword = PasswordHashGenerator.CreatePasswordHash(pass, salt); usuario.Password = hashedPassword; usuario.Bloqueado = false; usuario.IntentosErroneosLogin = 0; usuario.VigenciaPassword = DateTime.Today.AddDays(-1); Update(usuario); var usuarioMail = new UsuarioMailDto { Nombre = usuario.Nombre + " " + usuario.ApellidoPaterno + " " + usuario.ApellidoMaterno, CorreoElectronico = usuario.CorreoElectronico, Password = pass }; var html = TemplateMail.GenerateHtmlCorreoUsuario(usuarioMail, url); var logo = TemplateMail.GeneraLogoAbaxAttachment(); return(MailUtil.EnviarEmail(usuario.CorreoElectronico, "Envio de Nueva Contraseña", html, logo)); }
/// <summary> /// Genera la cadena encriptada /// </summary> /// <param name="password"></param> /// <returns></returns> public static String EncriptarPassword(String password) { string salt = PasswordHashGenerator.CreateSalt(PasswordHashGenerator.TAMANIO_NUMERO_SALT); return(PasswordHashGenerator.CreatePasswordHash(password, salt)); }
public ResultadoOperacionDto GuardarUsuario(Usuario usuario, long idUsuarioExec, String url, String correoElectronico) { var esLoginActiveDirectory = bool.Parse(ConfigurationManager.AppSettings.Get("LoginActiveDirectory")); var resultado = new ResultadoOperacionDto(); try { bool envio = false; var pass = String.Empty; if (usuario.IdUsuario == 0) { usuario.Activo = true; if (esLoginActiveDirectory) { usuario.VigenciaPassword = DateTime.Now.AddYears(50); } else { usuario.VigenciaPassword = DateTime.Now.AddDays(-1); } usuario.Bloqueado = false; usuario.HistoricoPassword = String.Empty; usuario.IntentosErroneosLogin = 0; pass = UtilAbax.GenerarCodigo(); usuario.Password = pass; var salt = usuario.Password.Substring(usuario.Password.Length - PasswordHashGenerator.TAMANIO_B64_NUMERO_SALT); usuario.Password = PasswordHashGenerator.CreatePasswordHash(usuario.Password, salt); envio = true; } var param = new List <object>() { usuario.CorreoElectronico }; var informacionAuditoria = new InformacionAuditoriaDto(idUsuarioExec, usuario.IdUsuario == 0 ? ConstantsAccionAuditable.Insertar : ConstantsAccionAuditable.Actualizar, ConstantsModulo.Usuarios, usuario.IdUsuario == 0 ? MensajesServicios.InsertarUsuario : MensajesServicios.Actualizarusuario, param); resultado = Repository.GuardarUsuario(usuario); resultado.InformacionAuditoria = informacionAuditoria; if (resultado.Resultado && envio && (!esLoginActiveDirectory || UtilAbax.esCorreoValido(usuario.CorreoElectronico))) { Repository.EnvioCorreoRegistro(usuario, pass, url); } else if (resultado.Resultado && envio && esLoginActiveDirectory && correoElectronico != null) { Repository.EnvioCorreoRegistroLDAP(usuario, url, correoElectronico); } } catch (Exception exception) { resultado.Resultado = false; resultado.Mensaje = exception.Message; resultado.InformacionExtra = exception; } return(resultado); }
public void Setup() { passwordHashGenerator = new PasswordHashGenerator(); }
public static void Seed(IServiceProvider serviceProvider) { using (var context = new CityVisitTrackerAPIContext(serviceProvider .GetRequiredService <DbContextOptions <CityVisitTrackerAPIContext> >())) { // If there is a state that assuming that we have already seeded some data and we will skip this on startup // Seed State, Cities, Users and UserVisits if (context.State.Any()) { return; } var alabama = new State { Abbreviation = "AL", DateAdded = DateTime.Today, LastUpdated = DateTime.Today, Name = "Alabama", Cities = new List <City>() }; var alaska = new State { Abbreviation = "AK", DateAdded = DateTime.Today, LastUpdated = DateTime.Today, Name = "Alaska", Cities = new List <City>() }; var arizona = new State { Abbreviation = "AZ", DateAdded = DateTime.Today, LastUpdated = DateTime.Today, Name = "Arizona", Cities = new List <City>() }; var seedStates = new[] { alabama, alaska, arizona }; context.State.AddRange(seedStates); context.SaveChanges(); var alabamaStateId = context.State.FirstOrDefaultAsync(x => x.Name == "Alabama").Id; var alaskaStateId = context.State.FirstOrDefaultAsync(x => x.Name == "Alaska").Id; var arizonaStateId = context.State.FirstOrDefaultAsync(x => x.Name == "Arizona").Id; var seedCities = new[] { AddCity("Akron", alabamaStateId, 32.87802m, -87.743989m), AddCity("Huntsville", alabamaStateId, 34.729135m, -86.584979m), AddCity("Addison", alabamaStateId, 32.87802m, -87.181384m), AddCity("Montgomery", alabamaStateId, 34.202175m, -86.300629m), AddCity("Birmingham", alabamaStateId, 32.38012m, -86.811504m), AddCity("Adak", alaskaStateId, 51.88001m, -176.657569m), AddCity("Akhiok", alaskaStateId, 56.945599m, -154.169998m), AddCity("Akiak", alaskaStateId, 60.909659m, -161.223451m), AddCity("Kasigluk", alaskaStateId, 60.895273m, -162.517124m), AddCity("Akutan", alaskaStateId, 54.134725m, -165.770554m), AddCity("Mesa", arizonaStateId, 33.417045m, -111.831459m), AddCity("Phoenix", arizonaStateId, 33.44826m, -112.075774m), AddCity("Avondale", arizonaStateId, 33.4405m, -112.349664m), AddCity("Mohave Valley", arizonaStateId, 34.92384m, -114.597859m), AddCity("Whiteriver", arizonaStateId, 33.834865m, -109.964934m), }; context.City.AddRange(seedCities); context.SaveChanges(); var salt = PasswordHashGenerator.GetSalt(); var hashedPassword = PasswordHashGenerator.ComputeHash("TestPassword", new SHA256CryptoServiceProvider(), salt); var user = new User { FirstName = "Sachin", LastName = "Patel", DateAdded = DateTime.Today, LastUpdated = DateTime.Today, UserName = "******", PasswordSalt = PasswordHashGenerator.GetSaltString(salt), PasswordHash = hashedPassword }; context.User.Add(user); context.SaveChanges(); } }