private async Task <AuthenticationResponseDto> TokenBuild(UserCredentialDto userCredentialDto) { var claims = new List <Claim>() { new Claim("email", userCredentialDto.Email) }; var user = await userManager.FindByEmailAsync(userCredentialDto.Email); var claimsDB = await userManager.GetClaimsAsync(user); claims.AddRange(claimsDB); var key = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(configuration["keyjwt"])); var creds = new SigningCredentials(key, SecurityAlgorithms.HmacSha256); var expiration = DateTime.UtcNow.AddDays(1); var token = new JwtSecurityToken(issuer: null, audience: null, claims: claims, expires: expiration, signingCredentials: creds); return(new AuthenticationResponseDto() { Token = new JwtSecurityTokenHandler().WriteToken(token), Expiration = expiration }); }
public IHttpActionResult GetNewUserAsync(UserCredentialDto dto) { IRegisterUser register = new UserRegister(); User user = register.GetNewUser(dto.Username, dto.Password); return(Ok(user)); }
public static void GenerateHashWithUserResponse(UserCredentialDto userCredentialsDto) { var hash = SecurityManager.HashPassword(userCredentialsDto.Password.Trim(), 12); userCredentialsDto.Salt = hash.Salt; userCredentialsDto.Password = hash.HashedPassword; }
public async Task <IActionResult> AuthorizeAsync([FromBody] UserCredentialDto userCredential) { var user = await _userDao.VerifyCredentialAsync(userCredential.Email, userCredential.Password); var token = TokenManager.GnerateToken(user); await _userDao.UpdateTokenAsync(user.Id, token); return(Ok(new SuccessResponse <TokenResponse>(new TokenResponse(token)))); }
public IHttpActionResult GetUserIdentity(UserCredentialDto dto) { string username = dto.Username; string password = dto.Password; IUserAuthenticationService service = new UserAuthenticationService(); var user = service.AuthenticateUser <AccommodationContext>(username, password); return(Ok(user)); }
public async Task <CustomIdentity> GetUserAsync(string username, string clearTextPassword) { UserCredentialDto dto = new UserCredentialDto() { Username = username, Password = clearTextPassword }; return(await Post <UserCredentialDto, CustomIdentity>("user", dto)); }
public async Task <User> GetNewUserAsync(string username, string clearTextPassword) { UserCredentialDto dto = new UserCredentialDto() { Username = username, Password = clearTextPassword }; return(await Post <UserCredentialDto, User>("newUser", dto)); }
public IActionResult Authenticate(UserCredentialDto userCredentialDto) { var token = _jWTAuthenticationManager.Authenticate(userCredentialDto.UserName, userCredentialDto.Password); if (token != null) { return(Ok(token)); } return(Unauthorized()); }
public IActionResult Authenticate([FromBody] UserCredentialDto userParam) { var user = userService.Authenticate(userParam.Username, userParam.Password); if (user == null) { return(BadRequest(new { message = "Username or password is incorrect" })); } return(Ok(user)); }
/// <summary> /// Map dto to entity /// </summary> /// <param name="dto">User credential dto object instance</param> public static UserCredential Map(this UserCredentialDto dto) { return(new UserCredential() { UserId = dto.UserId, Login = dto.Login, Password = dto.Password, ChangeCredentials = dto.ChangeCredentials, AuthFailsQty = dto.AuthFailsQty, LockoutUntil = dto.LockoutUntil }); }
/// <summary> /// Map entity to dto /// </summary> /// <param name="entity">Object to extension</param> /// <param name="dto">User Dto object</param> public static UserCredential Map(this UserCredential entity, UserCredentialDto dto) { if (dto != null) { entity.UserId = dto.UserId; entity.Login = dto.Login; //Password => NEVER MAP THIS FIELD HERE entity.ChangeCredentials = dto.ChangeCredentials; entity.AuthFailsQty = dto.AuthFailsQty; entity.LockoutUntil = dto.LockoutUntil; } return(entity); }
public static UserCredential ConvertToModel(this UserCredentialDto userCredentialDto) { var userCredential = new UserCredential(userCredentialDto.UserName, userCredentialDto.Password) { FirstName = userCredentialDto.FirstName, LastName = userCredentialDto.LastName, Email = userCredentialDto.Email, Agree = userCredentialDto.Agree, Salt = userCredentialDto.Salt }; return(userCredential); }
public static UserCredentialDto ConvertToDto(this UserCredential userCredential) { var userCredentialDto = new UserCredentialDto { FirstName = userCredential.FirstName, LastName = userCredential.LastName, Email = userCredential.Email, Agree = userCredential.Agree, Salt = userCredential.Salt }; return(userCredentialDto); }
public async Task <IActionResult> Issue([FromBody] UserCredentialDto userCredential) { var user = await _userManager.FindByNameAsync(userCredential.UserName); if (user == null) { return(NotFound()); } if (!user.EmailConfirmed) { return(NotFound("User email not confirmed")); //TODO: inform user the email need to verify before can use the api } ; var verifiedUser = _passwordHasher.VerifyHashedPassword(user, user.PasswordHash, userCredential.Password) == PasswordVerificationResult.Success; if (!verifiedUser) { return(BadRequest("User verification failed")); } var userClaims = await _userManager.GetClaimsAsync(user); var claims = new List <Claim> { new Claim(JwtRegisteredClaimNames.Sub, user.UserName), new Claim(JwtRegisteredClaimNames.Jti, Guid.NewGuid().ToString()) }.Union(userClaims); var secretKey = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(_configuration["IssuerSigningKey"])); var credentials = new SigningCredentials(secretKey, SecurityAlgorithms.HmacSha256); var expires = DateTime.Now.AddDays(Convert.ToInt32(_configuration["TokenExpirationNoDays"])); var securityToken = new JwtSecurityToken( _configuration["Issuer"], _configuration["Audience"], claims, expires: expires, signingCredentials: credentials ); var token = new JwtSecurityTokenHandler().WriteToken(securityToken); var tokenInformation = new TokenDto() { token = token, expiration = expires }; return(Ok(tokenInformation)); }
public async Task <ActionResult <AuthenticationResponseDto> > Login([FromBody] UserCredentialDto userCredentialDto) { var result = await signInManager.PasswordSignInAsync(userCredentialDto.Email, userCredentialDto.Password, isPersistent : false, lockoutOnFailure : false); if (result.Succeeded) { return(await TokenBuild(userCredentialDto)); } else { return(BadRequest("Failure Login")); } }
public async Task <ActionResult <AuthenticationResponseDto> > Create([FromBody] UserCredentialDto userCredentialDto) { var user = new IdentityUser { UserName = userCredentialDto.Email, Email = userCredentialDto.Email }; var result = await userManager.CreateAsync(user, userCredentialDto.Password); if (result.Succeeded) { return(await TokenBuild(userCredentialDto)); } else { return(BadRequest(result.Errors)); } }
public async Task <IHttpActionResult> UserRegistrationAsync(UserCredentialDto userCredentialsDto) { try { if (ModelState.IsValid) { var userResponse = await _userService.CreateUserAsync(userCredentialsDto); return(Ok(userResponse)); } return(InternalServerError()); } catch (System.Exception ex) { return(InternalServerError(ex)); } }
public static string GenerateToken(string jwtSecretKey, UserCredentialDto userData) { var unixEpoch = new DateTime(1970, 1, 1, 0, 0, 0, DateTimeKind.Utc); var expiry = Math.Round((DateTime.UtcNow.AddMinutes(TOKEN_EXPIRATION_IN_MINUTES) - unixEpoch).TotalSeconds); var issuedAt = Math.Round((DateTime.UtcNow - unixEpoch).TotalSeconds); //var notBefore = Math.Round((DateTime.UtcNow.AddMonths(6) - unixEpoch).TotalSeconds); var payLoad = new Dictionary <string, object> { { "userid", userData.Id }, { "sub", userData.UserName }, { "nbf", issuedAt }, { "iat", issuedAt }, { "exp", expiry } }; _encoder = new JwtEncoder(_algorithm, _serializer, _urlEncoder); var token = _encoder.Encode(payLoad, jwtSecretKey); return(token); }
public static UserCredentialDto Map(this UserCredential entity) { if (entity == null) { return(null); } UserCredentialDto dto = new UserCredentialDto(); if (!entity.Valid) { dto.AddNotifications(entity.Notifications); } dto.UserId = entity.UserId; dto.Login = entity.Login; //Password => NEVER MAP THIS FIELD HERE dto.ChangeCredentials = entity.ChangeCredentials; dto.AuthFailsQty = entity.AuthFailsQty; dto.LockoutUntil = entity.LockoutUntil; return(dto); }
public async Task <SignInResponse> SigninUserAsync(UserLoginDto userLoginDto) { var userCredentialsDto = new UserCredentialDto { Email = userLoginDto.Email, Password = userLoginDto.Password }; var userCredential = userCredentialsDto.ConvertToModel(); var userData = await _storageService.FindUserByEmailAsync(userCredential); var signInResponse = new SignInResponse(); if (userData != null) { var passwordModel = SecurityManager.HashPassword(userCredentialsDto.Password, userData.Salt); if (userData.RowKey == passwordModel.HashedPassword) { signInResponse.Token = SecurityManager.GenerateToken(_jwtSecretKey, userData.ConvertToDto()); } } return(await Task.FromResult(signInResponse)); }
public IActionResult UpdateUserCredentials(long id, [FromBody] UserCredentialDto userCredentialDto) { Logger.LogInformation("Begin update attempt for user id [{0}]", id); //Validate token's claim to the specified user id if (_tokenIssuerService.ValidateToken(User, id)) { //Ensure request body could be deserialized into the desired type if (userCredentialDto == null) { //Handle 400 Bad Request Logger.LogInformation("Update attempt for user id [{0}] failed, bad request", id); return(BadRequest()); } //Ensure user entity exists var userEntity = _userRepo.GetUser(id); if (userEntity == null) { //Handle 404 Not Found Logger.LogInformation("Update attempt for user id [{0}] failed, user not found", id); return(NotFound()); } //Ensure existing credentials are valid if (_userRepo.GetUserByUsernameAndPassword(userCredentialDto.CurrentUsername, userCredentialDto.CurrentPassword) == null) { //Handle authorization failure Logger.LogInformation("Update attempt for user id [{0}] failed, existing credentials invalid", id); return(Unauthorized()); } //Ensure username is unique (if changed) if (userCredentialDto.NewUsername != userEntity.Username && _userRepo.GetUserByUsername(userCredentialDto.NewUsername) != null) { ModelState.AddModelError("Username", $"The updated Username '{userCredentialDto.NewUsername}' is not unique"); } //Ensure email is unique (if changed) if (userCredentialDto.NewEmail != userEntity.Email && _userRepo.GetUserByEmail(userCredentialDto.NewEmail) != null) { ModelState.AddModelError("Email", $"The updated Email '{userCredentialDto.NewEmail}' is not unique"); } //Ensure model validation succeeds if (!ModelState.IsValid) { //Handle 400 Bad Request Logger.LogInformation("Update attempt for user id [{0}] failed, data validation fail", id); return(BadRequest(ModelState)); } //Handle password updates if (!string.IsNullOrWhiteSpace(userCredentialDto.NewPassword)) { //Set password to updated value userEntity.Password = userCredentialDto.NewPassword; } //Handle email updates if (!string.IsNullOrWhiteSpace(userCredentialDto.NewEmail)) { //Set email to updated value userEntity.Email = userCredentialDto.NewEmail; } //Handle username updates if (!string.IsNullOrWhiteSpace(userCredentialDto.NewUsername)) { //Set username to updated value userEntity.Username = userCredentialDto.NewUsername; } //Ensure entity is persisted successfully if (!_userRepo.Save()) { Logger.LogError("Update attempt for user id [{0}] failed, server error", id); return(StatusCode(500, "An error occurred while updating the User")); } //Success! Issue a new JWT and return no content Logger.LogInformation("Update attempt for user id [{0}] successful, user updated", id); AddJwtToResponseHeader(_tokenIssuerService.GenerateToken(userEntity.Id, userEntity.Username)); return(NoContent()); } //Handle authorization failure Logger.LogInformation("Update attempt for user id [{0}] failed, not authorized", id); return(Unauthorized()); }
public async Task <IHttpActionResult> CreateAsync([FromBody] UserCredentialDto userCredential) => await ExecuteAsync( async() => await _userService.LoginAsync(userCredential) );
public async Task <IApplicationResult> LoginAsync(UserCredentialDto userCredential) { return(await ExecuteAsync(async() => { if (userCredential == null) { return new ApplicationResult <LoginResultDto> { Status = ApplicationResultStatus.Unauthenticated, Data = new LoginResultDto { Status = LoginStatus.InvalidEmailOrPassword } } } ; var byEmail = _userPredicateFactory.CreateByEmail(userCredential.Email); var user = await _unitOfWork.Users.GetFirstAsync(byEmail); if (user == null) { return new ApplicationResult <LoginResultDto> { Status = ApplicationResultStatus.Unauthenticated, Data = new LoginResultDto { Status = LoginStatus.InvalidEmailOrPassword } } } ; if (!user.EmailConfirmed) { return new OkApplicationResult <LoginResultDto> { Data = new LoginResultDto { Status = LoginStatus.UnconfirmedEmail } } } ; if (!user.Active) { return new OkApplicationResult <LoginResultDto> { Data = new LoginResultDto { Status = LoginStatus.Inactive } } } ; if (user.IsLocked()) { user.GenerateDefaultPassword(); user.ResetAccessFailedCount(); await _unitOfWork.Users.UpdateAsync(user); var email = await _emailFactory.CreateForUserForgotPasswordAsync(user); _emailService.SendAsync(email); return new OkApplicationResult <LoginResultDto> { Data = new LoginResultDto { Status = LoginStatus.Locked } }; } //TODO use encrypted password if (!user.HasPassword(userCredential.Password)) { user.AccessFailedCount++; await _unitOfWork.Users.UpdateAsync(user); return new OkApplicationResult <LoginResultDto> { Data = new LoginResultDto { Status = LoginStatus.InvalidEmailOrPassword } }; } user.LastLoginTime = DateTime.UtcNow; user.ResetAccessFailedCount(); await _unitOfWork.Users.UpdateAsync(user); var tokenGenerateResponse = await _tokenService.GenerateAsync(new TokenGenerateRequest { Expires = _appSettingsService.DefaultTokenExpiresTime, Claims = new List <Claim> { new Claim(ClaimTypes.NameIdentifier, user.Id.ToString()), new Claim(ClaimTypes.Email, user.Email), new Claim(ClaimTypes.GivenName, user.FirstName), new Claim(ClaimTypes.Surname, user.GetSurname()) } }); if (tokenGenerateResponse == null) { throw new InternalServerException("SecurityToken could not be generated"); } return new OkApplicationResult <LoginResultDto> { Data = new LoginResultDto { Status = user.IsUsingCustomPassword ? LoginStatus.Success : LoginStatus.NonCustomPassword, SecurityToken = new SecurityTokenDto { Token = tokenGenerateResponse.SecurityToken, Expires = tokenGenerateResponse.Expires } } }; }, false)); }
public async Task <UserCreationResponse> CreateUserAsync(UserCredentialDto userCredentialsDto) { var saveResponse = await _storageService.SaveToTableAsync(userCredentialsDto); return(saveResponse); }