public AuthenticationResultDto AttemptAuthentication(string Username, string Password, System.Net.IPAddress clientIP) { AuthenticationResultDto result = new AuthenticationResultDto(); bool success = false; var user = _userRepository.GetQuery().Where(x => x.Username == Username).FirstOrDefault(); if (user == null) { result.ErrorMessage = "Invalid username"; } else { if (user.DeactivatedAt == null) { success = _cipherService.SHA256HashMatches(Password, user.Salt, user.PasswordHash); if (!success) { result.ErrorMessage = "Invalid password"; } } else { result.ErrorMessage = "This user account is inactive. Contact an administrator."; } } _nhSession.Save(new AuthenticationAttempt() { OccurredAt = DateTime.UtcNow, Username = Username, WasSuccessful = success, ClientIP = clientIP.ToString() }); result.User = _mapper.Map <User, UserDto>(user); return(result); }
/// <inheritdoc /> public async Task <AuthenticationResultDto> ResetPasswordAsync(ResetPasswordRequest resetPasswordRequest) { await securityAuditService.ProcessResetPassword(resetPasswordRequest.Email); if (resetPasswordRequest.Password != resetPasswordRequest.ConfirmPassword) { return(new AuthenticationResultDto { Errors = new[] { "Passwords don't match" }, }); } var user = await userManager.FindByEmailAsync(resetPasswordRequest.Email); if (user == null) { return(new AuthenticationResultDto { Errors = new[] { "User does not exist" } }); } var result = await userManager.ResetPasswordAsync(user, resetPasswordRequest.Token, resetPasswordRequest.Password); if (result.Succeeded) { return(await tokenService.Generate(user)); } var r = new AuthenticationResultDto { Errors = result.Errors.Select(x => x.Description), Success = false }; return(r); }
public async Task <IActionResult> Login(string Username, string Password) { AuthenticationResultDto result = _userService.AttemptAuthentication(Username, Password, this.Request.HttpContext.Connection.RemoteIpAddress); if (result.Success) { var claims = new List <Claim> { new Claim(AppConstants.CLAIM_TYPE_USER_ID, result.User.Id.ToString()), new Claim(ClaimTypes.Name, result.User.Username), new Claim(AppConstants.CLAIM_TYPE_USER_FULL_NAME, result.User.FullName) }; // new Claim(ClaimTypes.Role, String.Join(",", result.User.Roles.Select(x => (int)x))), foreach (var r in result.User.Roles) { claims.Add( new Claim(ClaimTypes.Role, ((int)r).ToString())); } var claimsIdentity = new ClaimsIdentity(claims, CookieAuthenticationDefaults.AuthenticationScheme); var authProperties = new AuthenticationProperties { AllowRefresh = true, ExpiresUtc = DateTimeOffset.UtcNow.AddMinutes(180), IsPersistent = true, IssuedUtc = DateTimeOffset.UtcNow }; await HttpContext.SignInAsync(CookieAuthenticationDefaults.AuthenticationScheme, new ClaimsPrincipal(claimsIdentity), authProperties); return(await Task.Run <RedirectToActionResult>(() => { return RedirectToAction("Index"); })); } else { TempData.Put("LoginVM", new LoginVM() { Username = Username, Password = Password, Message = result.ErrorMessage }); return(await Task.Run <RedirectToActionResult>(() => { return RedirectToAction("Login"); })); } }
private ActionResult <AuthSuccessResponse> ValidateAuthResponse(AuthenticationResultDto authResponse) { if (!authResponse.Success) { return(BadRequest(new AuthFailedResponse { Errors = authResponse.ErrorMessages })); } ; return(Ok(new AuthSuccessResponse { Token = authResponse.Token, RefreshToken = authResponse.RefreshToken })); }
public async Task <IActionResult> Login([FromBody] LoginViewModel loginViewModel) { try { var user = await _userManager.FindByEmailAsync(loginViewModel.UserName); if (user is null) { _logger.LogError(LoggingEvents.GetItemNotFound, "Login failed: User not found"); return(StatusCode(500, new AuthenticationResultDto() { FailureReason = AuthenticationFailureReason.Other })); } if (user.EmailConfirmed == false) { _logger.LogInformation("EmailNotConfirmed", "You cannot login until you confirm your email."); return(StatusCode(500, new AuthenticationResultDto() { FailureReason = AuthenticationFailureReason.EmailConfirmationRequired })); } var result = await _signInManager.CheckPasswordSignInAsync(user, loginViewModel.Password, false); if (result.IsLockedOut) { _logger.LogWarning("User account locked out."); return(StatusCode(500, new AuthenticationResultDto() { FailureReason = AuthenticationFailureReason.LockedOut })); } //ToDo: move to separate Service? if (result.Succeeded) { var claims = new List <Claim> { new Claim(JwtRegisteredClaimNames.Email, user.Email), new Claim(JwtRegisteredClaimNames.UniqueName, user.UserName), new Claim("ImageUrl", user.Avatar), new Claim("DefaultLatitude", user.DefaultLocationLatitude.ToString()), new Claim("DefaultLongitude", user.DefaultLocationLongitude.ToString()), new Claim("FlickrKey", _configuration["FlickrApiKey"]), new Claim("MapKey", _configuration["MapApiKey"]), new Claim(JwtRegisteredClaimNames.Jti, Guid.NewGuid().ToString()), }; var secretKey = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(_configuration["TokenKey"])); var signinCredentials = new SigningCredentials(secretKey, SecurityAlgorithms.HmacSha256); var baseUrl = string.Concat(_configuration["Scheme"], _configuration["Domain"]); var tokenOptions = new JwtSecurityToken( issuer: baseUrl, audience: baseUrl, claims: claims, expires: _systemClock.GetNow.AddDays(2), signingCredentials: signinCredentials); var viewModel = new AuthenticationResultDto() { FailureReason = AuthenticationFailureReason.None, AuthenticationToken = new JwtSecurityTokenHandler().WriteToken(tokenOptions) }; return(Ok(viewModel)); } _logger.LogWarning(LoggingEvents.GenerateItems, "Other authentication failure"); return(StatusCode(500, new AuthenticationResultDto() { FailureReason = AuthenticationFailureReason.Other })); } catch (Exception ex) { _logger.LogError(LoggingEvents.Exception, ex, "An unexpeceted error occurred"); return(StatusCode(500, new AuthenticationResultDto() { FailureReason = AuthenticationFailureReason.Other })); } }