/// <summary> /// Check login /// </summary> public OUser checkLogin(string username, string password) { OUser login = null; HashingOptions hashingOptions = new HashingOptions(); hashingOptions.Iterations = 1000; IOptions <HashingOptions> options = Options.Create(hashingOptions); PasswordHasher hasher = new PasswordHasher(options); User user = context.Users.AsNoTracking() .FirstOrDefault(u => u.uLogin == username); if (user == null) { throw new Exception("User not found"); } var check = hasher.Check(user.uPassword, password); if (!check.Verified) { throw new Exception("Incorrect password"); } else { UserManager userManager = new UserManager(context); login = userManager.convert(user); } return(login); }
public async Task <IActionResult> Login(User user) { if (ModelState["Email"].Errors.Count == 0 && ModelState["Password"].Errors.Count == 0) { User login = await _context.User.FirstOrDefaultAsync(b => b.Email == user.Email); if (login != null) { //Check password PasswordHasher ph = new PasswordHasher(); bool check = ph.Check(login.Password, user.Password); if (check) { string userId = login.Id.ToString(); await Authenticate(userId); return(RedirectToAction("Index", "User")); } else { ViewBag.Error = "Wrong email or password"; } } else { ViewBag.Error = "Wrong email or password"; } } return(View(user)); }
public async Task <User> Authenticate(LoginRequestDTO loginRequest) { var user = await _context.User.FirstOrDefaultAsync(u => u.Email == loginRequest.Username); if (user == null) { throw new HttpResponseException("User does not exist! Create account before login"); } var passwordHasher = new PasswordHasher(new HashingOptions() { }); var passwordVerified = passwordHasher.Check(user.Password, loginRequest.Password); if (passwordVerified == false) { throw new HttpResponseException("Password is wrong. Please fill the correct password!"); } else { return(user); } /*var user = await _context.User.FirstOrDefaultAsync(u => u.Email == loginRequest.Username && u.Password == loginRequest.Password); * if(user == null) * return null;*/ }
public async Task <Result <SignResponse> > Login(SignDto dto) { return(await ValidateDto(dto) .Bind(RecaptchaVerify) .Bind(FindUser) .Bind(CheckUserPassword) .Bind(GenerateToken) .OnFailure(LogError)); async Task <Result <User> > FindUser() { var user = await FindUserByEmail(dto.Email); return(user.HasValue && user.Value.EmailConfirmed ? Result.Ok(user.Value) : Result.Failure <User>($"The user with this email was not found or not activated: {dto.Email}")); } Result <User> CheckUserPassword(User user) { var(verified, needsUpgrade) = passwordHasher.Check(user.PasswordHash, dto.Password); return((!verified && !needsUpgrade) ? Result.Failure <User>($"Incorrect email or password: {dto.Email}") : Result.Ok(user)); } }
public async Task <IActionResult> Login(LoginM model) { if (!ModelState.IsValid) { return(View(model)); } //istifadecini tap var user = await Context.Users.Where(c => c.Username == model.Username).FirstOrDefaultAsync(); if (user == null) { ModelState.AddModelError("", "Belə bir istifadəçi yoxdur."); return(View(model)); } //parolu yoxla byte[] salt = Encoding.UTF8.GetBytes(user.Salt); bool result = PasswordHasher.Check(model.Password, salt, user.PasswordHash); if (result) { await Identity.SignInAsync(user, HttpContext); return(RedirectToAction("Index", "Home")); } else { ModelState.AddModelError("", "Istifadəçi adı və ya şifrə yanlışdır."); return(View(model)); } }
public async Task <Account> AddClientToAccount(Guid id, Client client, string password) { var result = await _repository.SelectAsync(id); if (result == null) { throw new ArgumentException("Account not Found"); } PasswordHasher passHash = new PasswordHasher(); bool verified; bool needsUpdate; (verified, needsUpdate) = passHash.Check(result.Password, password); if (!needsUpdate) { throw new ArgumentException("Password Needs Update"); } if (!verified) { throw new ArgumentException("Password Incorrect"); } AccountClient accountClient = new AccountClient { Account = result, Client = client }; result.AccountClients.Add(accountClient); return(await _repository.UpdateAsync(result)); }
public ActionResult <AuthView> Authenticate( [FromServices] DataContext context, [FromBody] AuthRequest model) { // Recupera o usuário var userQuery = context.users.AsQueryable(); User user = userQuery .Where(x => x.Email.ToLower().Contains(model.Email)).First(); var option = new HashingOptions(); var password = new PasswordHasher(Options.Create(option)); var(verified, _) = (password.Check(user.Password, model.Password)); if (verified) { // Gera o Token var token = TokenService.GenerateToken(user, Configuration.GetConnectionString("Secret")); // Retorna os dados return(new AuthView() { user = new UserView(user), token = token }); } var e = new Exception("Login inválido"); return(BadRequest(e.Message)); }
public IActionResult LoginUser([FromQuery][Required] string email, [FromQuery][Required] string password) { PasswordHasher hasher = new PasswordHasher(); User user = Models.User.FromEmail(email); if (user == null) { return(Problem(detail: "invalid email or password")); } else if (hasher.Check(user.Password, password).Verified) { var tokenHandler = new JwtSecurityTokenHandler(); var token = new JwtSecurityToken( issuer: "stonks-api", audience: "stonks-client", claims: user.ToClaims(), expires: DateTime.Now.AddHours(6), signingCredentials: new SigningCredentials(new SymmetricSecurityKey(Convert.FromBase64String(Startup.JWTSecret)), SecurityAlgorithms.HmacSha256Signature) ); return(Ok(new Dictionary <string, string> { { "token", tokenHandler.WriteToken(token) } })); } else { return(Problem(detail: "invalid email or password")); } }
public static async Task <User> Get(DataContext context, PasswordHasher passwordHasher, string username, string password) { var user = await context.Users.FirstOrDefaultAsync(x => x.Username == username); (bool verified, bool needsUpgrade) = passwordHasher.Check(user.Password, password); return(verified ? user : null); }
public void HasherTest_01() { IPasswordHasher passHasherService = new PasswordHasher(); var passHash = passHasherService.CreateHash("admin"); Assert.True(passHasherService.Check(passHash, "admin")); }
public User LogIn(LogInForm logInForm) { var user = _context.User.FromSqlRaw($"SELECT * FROM [dbo].[user] WHERE [user].email = '{logInForm.Email}'") .FirstOrDefault(); if (user == null) { return(null); } var role = _context.Role.FromSqlRaw($"SELECT * FROM role WHERE role.id = {user.RoleId}").First(); role.User = null; user.Role = role; return(PasswordHasher.Check(user.Password, logInForm.Password).Verified ? user : null); }
public Response Authenticate(string username, string password) { var _passwordHasher = new PasswordHasher(); var user = _context.Users.Include(User => User.Role).FirstOrDefault(x => x.Email == username); // return null if user not found if (user == null) { return(null); } if (!_passwordHasher.Check(user.Password, password)) { return(null); } // authentication successful so generate jwt token var tokenHandler = new JwtSecurityTokenHandler(); var key = Encoding.ASCII.GetBytes(_appSettings.Secret); var tokenDescriptor = new SecurityTokenDescriptor { Subject = new ClaimsIdentity(new Claim[] { new Claim(ClaimTypes.PrimarySid, user.Id.ToString()), new Claim(ClaimTypes.Name, user.FirstName + " " + user.LastName), new Claim(ClaimTypes.Role, user.Role.Name), new Claim(ClaimTypes.Email, user.Email), }), Expires = DateTime.UtcNow.AddDays(7), SigningCredentials = new SigningCredentials(new SymmetricSecurityKey(key), SecurityAlgorithms.HmacSha256Signature) }; var authtoken = tokenHandler.CreateToken(tokenDescriptor); // remove password before returning user.Password = null; var respone = new Response { token = tokenHandler.WriteToken(authtoken), user = user }; return(respone); }
public async Task <AuthenticateResponse> Authenticate(AuthenticateRequest request) { var user = await _dbRepository.Get <UserEntity>(x => x.Username == request.Username) .AsNoTracking() .FirstOrDefaultAsync(); if (user == null) { return(null); } if (!PasswordHasher.Check(user.Password, request.Password)) { return(null); } var token = GenerateJwtToken(user); return(new AuthenticateResponse(user, token)); }
public async Task <IActionResult> Login(LoginModel model) { if (ModelState.IsValid) { ProUser user = await _context.Users .Include(u => u.Role) .FirstOrDefaultAsync(u => u.Login == model.Login); if (user != null && hasher.Check(user.Password, model.Password)) { await Authenticate(user); return(RedirectToAction("Index", "Home")); } ModelState.AddModelError("", "Некорректные логин и(или) пароль"); } return(View(model)); }
public Task <TokenResponseDTO> Authenticate(RegistrationRequestDTO data) { var user = _userRepository .FindByPredicate(u => u.Email == data.Email && _hasher.Check(u.Password, data.Password)) .FirstOrDefault(); if (user == null) { throw new InvalidAuthenticateException("Wrong login or password"); } var tokenDescriptor = GetTokenDescriptor(user); var token = tokenHandler.CreateToken(tokenDescriptor); return(Task.Run(() => new TokenResponseDTO { Token = tokenHandler.WriteToken(token) })); }
public async Task <string> LoginUser(User user) { var userToFind = await SingleOrDefaultAsync(u => u.Name == user.Name); if (userToFind == null) { return(null); } var(isPasswordCorrect, _) = PasswordHasher.Check(userToFind.Password, user.Password); if (!isPasswordCorrect) { return(null); } var token = auth.GenerateToken(userToFind.Id.ToString(), userToFind.IsAdmin); //We should instead store isAdmin In the Database return(token); }
/// <summary> /// Authenticate user and generate JWT /// </summary> /// <param name="simpleUser">Simple user object</param> /// <returns>Result object</returns> public BLResult <SimpleUser> Authenticate(SimpleUser simpleUser) { BLResult <SimpleUser> result = new BLResult <SimpleUser>(); // Validating input data if (simpleUser == null) { result.Message = "Invalid data"; return(result); } // Getting user from database DBResult <User> dbResult = userDataAccess.GetUser(simpleUser.Email); if (dbResult.Success == true) { // Valdiating user password bool verified, needsUpgrade; (verified, needsUpgrade) = passwordHasher.Check(dbResult.Item.Password, simpleUser.Password); if (verified && needsUpgrade == false) { // Generate Token simpleUser.Token = userService.GenerateToken(dbResult.Item.IdUser, dbResult.Item.Profile); // We should not return the password simpleUser.Password = string.Empty; simpleUser.Profile = dbResult.Item.Profile; simpleUser.IdUser = dbResult.Item.IdUser; result.Success = true; result.Item = simpleUser; } else { result.Message = "Invalid Password"; } } else { result.Message = dbResult.Message; } return(result); }
public bool Authenticate(string username, string password) { bool retVal = false; PasswordHasher Hasher = new PasswordHasher(); Utenti utente = this.alphaShopDbContext.Utenti .Include(r => r.Profili) .Where(c => c.UserId == username) .FirstOrDefault(); if (utente != null) { string EncryptPwd = utente.Password; retVal = Hasher.Check(EncryptPwd, password).Verified; } return(retVal); }
public async Task <IActionResult> Login(LoginUserDto model) { if (ModelState.IsValid) { var user = await _userManager.FindByNameAsync(model.Email); if (user != null) { if (PasswordHasher.Check(user.Password, model.Password).Verified) { await _signInManager.SignInAsync(user, isPersistent : model.RememberMe); return(RedirectToAction("Index", "MainPanel")); } } } ModelState.AddModelError("", "Invalid login attempt"); return(View(model)); }
public AuthenticateResponse Authenticate(AuthenticateRequest model) { User user = _repository.GetUserByCredentials(model.Username); if (user == null) { return(null); } var verified = _passwordHasher.Check(user.Password, model.Password).Verified; if (!verified) { return(null); } // authentication successful so generate jwt token var token = generateJwtToken(user); return(new AuthenticateResponse(user, token)); }
public AuthenticateResponse Authenticate(AuthenticateRequest model) { var user = _context.Users.FirstOrDefault(x => x.Username == model.Username); if (user == null) { return(null); } var verified = _passwordHasher.Check(user.Password, model.Password).Verified; if (!verified) { return(null); } // authentication successful so generate jwt token var token = GenerateJwtToken(user); return(new AuthenticateResponse(user, token)); }
public string Post([FromBody] UserDto userDto) { PasswordHasher ph = new PasswordHasher(); UserDto user = _database.GetInstance.QuerySingleOrDefault <UserDto>("SELECT username, pass FROM users WHERE username = @user", new { user = userDto.Username }); if (user == null) { HttpContext.Response.StatusCode = 401; return(null); } (bool Verified, bool NeedsUpgrade)checkResult = ph.Check(user.Pass, userDto.Password); if (checkResult.Verified) { return(JWT.GenerateToken(userDto.Username)); } else { HttpContext.Response.StatusCode = 401; return(null); } }
public OperationResult <User> GetUserWithRole(string email, string password) { var result = new OperationResult <User>(); var data = _users .Include(option => option.Role) .FirstOrDefault(option => option.Email.Equals(email)); var isEmailCorrect = data != null; var isPasswordCorrect = isEmailCorrect ? PasswordHasher.Check(data.Salt, data.Password, password) : false; if (isPasswordCorrect) { result.Data = data; result.Type = ResultType.Success; } else { result.Type = ResultType.BadRequest; } return(result); }
public Usuario Authenticate(string cedula, string password) { IPasswordHasher passwordHasher = new PasswordHasher(_hashingOptions); var user = _context.Usuario.Where(x => x.cedula == cedula).FirstOrDefault(); // return null if user not found if (user == null) { return(null); } var(check, _) = passwordHasher.Check(user.password, password); if (!check) { return(null); } // authentication successful so generate jwt token var tokenHandler = new JwtSecurityTokenHandler(); var key = Encoding.ASCII.GetBytes(_appSettings.Secret); var tokenDescriptor = new SecurityTokenDescriptor { Subject = new ClaimsIdentity(new Claim[] { new Claim(ClaimTypes.Name, user.cedula.ToString()), new Claim(ClaimTypes.Role, user.role) }), Expires = DateTime.UtcNow.AddDays(7), SigningCredentials = new SigningCredentials(new SymmetricSecurityKey(key), SecurityAlgorithms.HmacSha256Signature) }; var token = tokenHandler.CreateToken(tokenDescriptor); user.token = tokenHandler.WriteToken(token); // remove password before returning user.password = null; return(user); }
public async Task <Account> Get(int agenciaCode, int accountCode, string password) { var result = await _repository.Find(x => x.Code == accountCode && x.Agencia.Code == agenciaCode); if (result == null || result.Count() == 0) { throw new ArgumentException("Account not Found"); } PasswordHasher passHash = new PasswordHasher(); bool verified; bool needsUpdate; (verified, needsUpdate) = passHash.Check(result.First().Password, password); if (needsUpdate) { throw new ArgumentException("Password Needs Update"); } if (!verified) { throw new ArgumentException("Password Incorrect"); } return(result.First()); }
public ActionResult <AuthResponse> Authenticate([FromBody] AuthBinding model) { var user = _ZaxHerbivoryTrainerRepository.Authenticate(model.UserName); // return null if user not found if (user == null) { return(BadRequest(new { message = "Username or password is incorrect" })); } //password check var passwordHash = new PasswordHasher(10000); var passwordCheck = passwordHash.Check(user.Password, model.Password); if (!passwordCheck.Verified) { return(BadRequest("Username or password is incorrect")); } // authentication successful so generate jwt token var tokenHandler = new JwtSecurityTokenHandler(); var key = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(_appSettings.Secret)); var credentials = new SigningCredentials(key, SecurityAlgorithms.HmacSha256); var AuthTime = DateTime.Now; var claims = new[] { new Claim(JwtRegisteredClaimNames.Sub, model.UserName), new Claim(JwtRegisteredClaimNames.Jti, Guid.NewGuid().ToString()), new Claim(JwtRegisteredClaimNames.AuthTime, AuthTime.ToString()) }; var token = new JwtSecurityToken( issuer: _appSettings.Issuer, audience: _appSettings.Issuer, claims, expires: DateTime.Now.AddMinutes(120), signingCredentials: credentials); var encodeToken = new JwtSecurityTokenHandler().WriteToken(token); var response = new AuthResponse() { BearerToken = encodeToken, RoleType = user.RoleType, ExpiryDate = DateTime.Now.AddMinutes(120) }; var accessToken = new Token { UserGuid = "",//unknown at this point CreateTime = AuthTime, ExpiresTime = DateTime.Now.AddMinutes(120), RoleId = user.RoleType, UserId = user.RoleId }; //create login token var tokenResult = _ZaxHerbivoryTrainerRepository.CreateToken(accessToken); _ZaxHerbivoryTrainerRepository.Save(); response.AccessId = tokenResult.TokenId; return(Ok(response)); }
public void IllegalCharactersInKeyIsFalse(string key) { var hash = PasswordHasher.Check("dummy", key); Assert.True(hash == false, "Key with illegal characters doesn't result in false check."); }
//todo test transactions db methods public async Task <Account> Deposit(Guid id, decimal value, string password) { try { Movement transaction = new Movement { Id = Guid.NewGuid(), CreatedAt = DateTime.UtcNow, IdAccount = id, Type = (int)TypeMovement.Deposit, Value = value, Success = false }; if (value < 0) { throw new ArgumentException("Cannot deposit negative amount"); } var result = await _repository.SelectAsync(id); if (result == null) { throw new ArgumentException("Account not found"); } //verifies password PasswordHasher passHash = new PasswordHasher(); bool verified; bool needsUpdate; (verified, needsUpdate) = passHash.Check(result.Password, password); if (needsUpdate) { throw new ArgumentException("Password Needs Update"); } if (!verified) { throw new ArgumentException("Password Incorrect"); } if (result.Balance + value < result.Balance) { throw new ArgumentException("not enough Balance"); } result.Balance += value; var update = await _repository.UpdateAsync(result); if (update == null) { var resultTransaction = await _repositoryTransaction.InsertAsync(transaction); return(update); } else { transaction.Success = true; var resultTransaction = await _repositoryTransaction.InsertAsync(transaction); return(update); } } catch (Exception ex) { throw ex; } }
public (bool Verified, bool NeedsUpgrade) VerifyPassword(string hashedPassword, string password) { PasswordHasher passwordHasher = new PasswordHasher(); return(passwordHasher.Check(hashedPassword, password)); }
public void HashIsCancelable(string key) { bool isCorrect = PasswordHasher.Check(key, PasswordHasher.Hash(key)); Assert.True(isCorrect, "Hash is not cancelable"); }