public async Task <IActionResult> LoginUser([FromBody] UserForAuthenticationDto model) { if (model == null) { _logger.LogError("Login Model sent from client is null."); return(BadRequest("Empty User Cannot Be Logged In")); } if (!ModelState.IsValid) { _logger.LogError("Invalid model state for the Login"); return(UnprocessableEntity(ModelState)); } var user = await _userManager.FindByNameAsync(model.UserName); if (user == null) { return(BadRequest("Username or Password is incorrect")); } var userRole = await _userManager.GetRolesAsync(user); var userRoles = new List <string> { "Administrator", "Manager" }; foreach (var role in userRole) { var conditionForAuthority = userRoles.Contains(role.ToString()); if (!conditionForAuthority) { return(Unauthorized("Unauthorized")); } } if (user != null && await _userManager.CheckPasswordAsync(user, model.Password)) { Console.WriteLine("Hello"); var tokenDescriptor = new SecurityTokenDescriptor(); Claim[] myClaims = new Claim[] { new Claim("UserID", user.Id.ToString()), new Claim("UserName", user.UserName.ToString()), new Claim("UserEmail", user.Email.ToString()), new Claim(ClaimTypes.Role, userRole.FirstOrDefault()) }; tokenDescriptor.Subject = new ClaimsIdentity(myClaims); tokenDescriptor.Expires = DateTime.UtcNow.AddDays(1); tokenDescriptor.SigningCredentials = new SigningCredentials(new SymmetricSecurityKey(Encoding.UTF8.GetBytes("`!`)$^`%&`*@issu31r@ck3r!|¬9+*a-T-s|¬`(")), SecurityAlgorithms.HmacSha256Signature); var tokenHandler = new JwtSecurityTokenHandler(); var securityToken = tokenHandler.CreateToken(tokenDescriptor); var token = tokenHandler.WriteToken(securityToken); return(Ok(new { token })); } else { return(BadRequest(new { message = "Username or password is incorrect." })); } }
public async Task <bool> AuthenticateUserAsync(UserForAuthenticationDto userForAuthentication) { _user = await _userManager.FindByEmailAsync(userForAuthentication.Email); return(_user != null && await _userManager.CheckPasswordAsync(_user, userForAuthentication.Password)); }
public async Task <bool> ValidateUser(UserForAuthenticationDto userForAuth) { _user = await _userManager.FindByNameAsync(userForAuth.UserName); return(_user != null && await _userManager.CheckPasswordAsync(_user, userForAuth.Password)); }
public async Task <IActionResult> Login([FromBody] UserForAuthenticationDto userForAuthentication) { var user = await _userManager.FindByEmailAsync(userForAuthentication.Email); if (user == null || !await _userManager.CheckPasswordAsync(user, userForAuthentication.Password)) { return(Unauthorized(new AuthResponseDto { ErrorMessage = "Invalid Authentication" })); } var signingCredentials = _tokenService.GetSigningCredentials(); var claims = await _tokenService.GetClaims(user); var tokenOptions = _tokenService.GenerateTokenOptions(signingCredentials, claims); var token = new JwtSecurityTokenHandler().WriteToken(tokenOptions); user.RefreshToken = _tokenService.GenerateRefreshToken(); user.RefreshTokenExpiryTime = DateTime.Now.AddDays(7); await _userManager.UpdateAsync(user); return(Ok(new AuthResponseDto { IsAuthSuccessful = true, Token = token, RefreshToken = user.RefreshToken })); }
public IActionResult Authenticate([FromBody] UserForAuthenticationDto userDto) { var user = _userRepository.Authenticate(userDto.Username, userDto.Password); if (user == null) { return(BadRequest(new { message = "Username or password is incorrect" })); } 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.Id.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); var userFromRepo = _mapper.Map <UserDto>(user); userFromRepo.Token = tokenHandler.WriteToken(token); return(Ok(userFromRepo)); }
public async Task <AuthResponseDto> Login(UserForAuthenticationDto userForAuthentication) { var content = JsonSerializer.Serialize(userForAuthentication); var bodyContent = new StringContent(content, Encoding.UTF8, _applicationJson); HttpResponseMessage authResult = await _client.PostAsync("api/user/login", bodyContent); string authContent = await authResult.Content.ReadAsStringAsync(); var result = JsonSerializer.Deserialize <AuthResponseDto>(authContent, new JsonSerializerOptions { PropertyNameCaseInsensitive = true }); if (!authResult.IsSuccessStatusCode) { return(result); } await _localStorage.SetItemAsync("authToken", result.Token); await _localStorage.SetItemAsync("refreshToken", result.RefreshToken); ((AuthStateProvider)_authStateProvider).NotifyUserAuthentication(result.Token); _client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("bearer", result.Token); return(new AuthResponseDto { IsAuthSuccessful = true }); }
/// <summary> /// Sends password and username and get a jwt token in the result package. /// </summary> /// <param name="userForAuthentication"></param> /// <returns></returns> public async Task <AuthResponseDto> Login(UserForAuthenticationDto userForAuthentication) { string content = userForAuthentication.ToString(); StringContent bodyContent = new StringContent(content, Encoding.UTF8, "application/x-www-form-urlencoded"); HttpResponseMessage httpResponse = await _client.PostAsync("/token", bodyContent); string responseContent = await httpResponse.Content.ReadAsStringAsync(); AuthResponseDto result = JsonSerializer.Deserialize <AuthResponseDto>(responseContent, new JsonSerializerOptions { PropertyNameCaseInsensitive = true }); Console.WriteLine("Access granted is: " + httpResponse.IsSuccessStatusCode); result.Status = (int)httpResponse.StatusCode; if (!httpResponse.IsSuccessStatusCode) { result.Message = httpResponse.ReasonPhrase; return(result); } await _localStorage.SetItemAsync("authToken", result.Access_Token); ((AuthStateProvider)_authStateProvider).NotifyUserAuthentication(userForAuthentication.Username); _client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", result.Access_Token); return(result); }
public async Task <IActionResult> Authenticate([FromBody] UserForAuthenticationDto user) { if (!await _authManager.ValidateUser(user)) { _logger.LogWarn($"{nameof(Authenticate)}: Authentication failed. Wrong user name or password."); return(Unauthorized()); } var userEntity = await _userManager.FindByNameAsync(user.UserName); var claims = new List <Claim> { new Claim(ClaimTypes.Name, user.UserName) }; var accessToken = _authManager.GenerateAccessToken(claims); var refreshToken = _authManager.GenerateRefreshToken(); userEntity.RefreshToken = refreshToken; userEntity.RefreshTokenExpiryTime = DateTime.Now.AddDays(7); await _repository.SaveAsync(); return(Ok(new { Token = accessToken, RefreshToken = refreshToken })); }
/// <summary> /// Post a login request to the api. Stores the given user credentials in cookies and forwards any errors the api sends back. /// </summary> /// <param name="userForAuthentication">Holds info about which username and password a user tries to log in with.</param> /// <returns></returns> public async Task <AuthResponseContainer> Login(UserForAuthenticationDto userForAuthentication) { //Serializes the UserForAuthenticationDTO to a dictionary to easily be able to encode it to x-www-form-urlencoded in HttpRequestMessage body var content = JsonSerializer.Serialize(userForAuthentication); var dictionary = JsonSerializer.Deserialize <Dictionary <string, string> >(content); var req = new HttpRequestMessage(HttpMethod.Post, "/Token") { Content = new FormUrlEncodedContent(dictionary) }; var resultContainer = new AuthResponseContainer(); try { var authResult = await _client.SendAsync(req); var authContent = await authResult.Content.ReadAsStringAsync(); resultContainer = JsonSerializer.Deserialize <AuthResponseContainer>(authContent, new JsonSerializerOptions { PropertyNameCaseInsensitive = true }); if (!authResult.IsSuccessStatusCode) { return(resultContainer); } } catch { resultContainer.Errors = new Dictionary <string, string[]>(); string[] errorArray = { "There has been a network error, please check connection and try again." }; resultContainer.Errors.Add("Error", errorArray); resultContainer.Succeeded = false; return(resultContainer); } //Sets information about the user and acesstoken to local storage await _localStorage.SetItemAsync("authToken", resultContainer.Value.AcessToken); await _localStorage.SetItemAsync("userName", resultContainer.Value.UserName); await _localStorage.SetItemAsync("authorizationExpires", resultContainer.Value.Expires); // TODO: Remove code below if it is not necessary at this time. ((AuthStateProvider)_authStateProvider).NotifyUserAuthentication(userForAuthentication.UserName); _client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("bearer", resultContainer.Value.AcessToken); resultContainer.Succeeded = true; UpdateNavUI.Invoke(true, EventArgs.Empty); return(resultContainer); }
public async Task <IActionResult> Authenticate([FromBody] UserForAuthenticationDto user) { if (!await _authManager.ValidateUser(user)) { return(Unauthorized()); } return(Ok(new { Token = await _authManager.CreateToken() })); }
public async Task <IActionResult> Authenticate([FromBody] UserForAuthenticationDto user) { if (!await _authManager.ValidateUser(user)) { _logger.LogWarning($"{nameof(Authenticate)}: Authentication failed. Wrong user name or password."); return(Unauthorized()); } return(Ok(new { Token = await _authManager.CreateToken() })); }
public async Task <IActionResult> Login(UserForAuthenticationDto userForAuthentication) { var authResult = await _identityService.AuthorizeAsync(userForAuthentication.Email, userForAuthentication.Password); if (authResult.IsAuthSuccessful) { return(Ok(authResult)); } return(Unauthorized(authResult)); }
public async Task <IActionResult> Authenticate([FromBody] UserForAuthenticationDto userForAuthentication) { if (await _userService.ValidateUser(userForAuthentication, ModelState)) { return(Ok(await _userService.CreateToken())); } _logger.LogWarning($"{nameof(Authenticate)}: Authentication failed. " + $"Wrong user name or password."); return(BadRequest(ModelState)); }
// Refresh Token public async Task <BaseApiResponse> RefreshTokenAsync(string refreshToken) { // STEP 1: Check if refreshToken match any users var user = _context.Users.SingleOrDefault(u => u.RefreshTokens.Any(t => t.Token == refreshToken)); if (user == null) { return(BaseApiResponseHelper.GenerateApiResponse(false, "get refresh token", null, new List <string> { "Refresh token did not match any users." })); } // STEP 2: Check if refreshToken is active or not var refreshTokenFromDb = user.RefreshTokens.Single(x => x.Token == refreshToken); if (!refreshTokenFromDb.IsActive) { return(BaseApiResponseHelper.GenerateApiResponse(false, "get refresh token", null, new List <string> { "Refresh token is not active." })); } // STEP 3: Revoke the current refresh token refreshTokenFromDb.Revoked = DateTime.UtcNow; // STEP 4: Generate a new refresh token and save to database var newRefreshToken = CreateRefreshToken(); user.RefreshTokens.Add(newRefreshToken); _context.Update(user); await _context.SaveChangesAsync(); // FINALLY: Generate new JWT Token JwtSecurityToken jwtSecurityToken = await CreateJwtToken(user); var roles = await _userManager.GetRolesAsync(user).ConfigureAwait(false); var userForAuthenticationDto = new UserForAuthenticationDto() { FirstName = user.FirstName, LastName = user.LastName, Username = user.UserName, Email = user.Email, Roles = roles, AccessToken = new JwtSecurityTokenHandler().WriteToken(jwtSecurityToken), RefreshToken = newRefreshToken.Token, RefreshTokenExpiration = newRefreshToken.Expires }; return(BaseApiResponseHelper.GenerateApiResponse(true, "Get refresh token", new List <UserForAuthenticationDto> { userForAuthenticationDto }, null)); }
// POST: api/Accounts/authenticate public async Task <IActionResult> Authenticate([FromBody] UserForAuthenticationDto userDto) { var tokenResponse = await businessLogic.AuthenticateUser(userDto, Request); if (tokenResponse.IsSuccessful) { return(Ok(tokenResponse.Result)); } return(BadRequest(new { message = tokenResponse.ErrorMessage })); }
public async Task <IActionResult> AdminLogin([FromBody] UserForAuthenticationDto userForAuthentication) { var apiKeyAuthenticate = APICredentialAuth.APIKeyCheck(Request.Headers[NamePars.APIKeyStr]); if (apiKeyAuthenticate.StatusCode == ResponseCode.Error) { return(BadRequest(new ResponseDetails() { StatusCode = ResponseCode.Exception, Message = apiKeyAuthenticate.Message })); } var user = await _userManager.FindByEmailAsync(userForAuthentication.Email); if (user == null) { return(BadRequest(new AuthResponseDto { Message = "Tài khoản không tồn tại!" })); } //Nếu validate có lỗi thì trả về bad request var validate = _repository.Authenticate.ValidateLogin(userForAuthentication); if (validate != null) { return(BadRequest(validate)); } if (!await _userManager.CheckPasswordAsync(user, userForAuthentication.Password)) { return(BadRequest(new AuthResponseDto { Message = "Thông tin đăng nhập sai" })); } var userGetting = await _repository.User.GetUserByApplicationUserIDAsync(user.Id); if (userGetting.Quyen == Data.UserRole) { return(Unauthorized(new AuthResponseDto { Message = "Bạn không có được cấp quyền vào admin" })); } if (user.LockoutEnabled) { return(Unauthorized(new AuthResponseDto { Message = "Bạn chưa được admin phê duyệt" })); } return(Ok(userGetting)); }
public async Task <IActionResult> Login([FromBody] UserForAuthenticationDto userForAuthentication) { var user = await _userManager.FindByNameAsync(userForAuthentication.Email); if (user == null) { return(BadRequest("Invalid Request")); } if (!await _userManager.IsEmailConfirmedAsync(user)) { return(Unauthorized(new AuthResponseDto { ErrorMessage = "Email is not confirmed" })); } //you can check here if the account is locked out in case the user enters valid credentials after locking the account. if (!await _userManager.CheckPasswordAsync(user, userForAuthentication.Password)) { await _userManager.AccessFailedAsync(user); if (await _userManager.IsLockedOutAsync(user)) { var content = $"Your account is locked out. To reset the password click this link: {userForAuthentication.clientURI}"; var message = new Message(new string[] { userForAuthentication.Email }, "Locked out account information", content, null); await _emailSender.SendEmailAsync(message); return(Unauthorized(new AuthResponseDto { ErrorMessage = "The account is locked out" })); } return(Unauthorized(new AuthResponseDto { ErrorMessage = "Invalid Authentication" })); } if (await _userManager.GetTwoFactorEnabledAsync(user)) { return(await GenerateOTPFor2StepVerification(user)); } var signingCredentials = _jwtHandler.GetSigningCredentials(); var claims = await _jwtHandler.GetClaims(user); var tokenOptions = _jwtHandler.GenerateTokenOptions(signingCredentials, claims); var token = await _jwtHandler.GenerateToken(user); await _userManager.ResetAccessFailedCountAsync(user); return(Ok(new AuthResponseDto { IsAuthSuccessful = true, Token = token })); }
public async Task <bool> ValidateUser(UserForAuthenticationDto userForAuthenticationDto) { User = await _userManager.FindByEmailAsync(userForAuthenticationDto.Email); if (User != null && await _userManager.CheckPasswordAsync(User, userForAuthenticationDto.Password)) { return(true); } return(false); }
public async Task <IActionResult> Authenticate([FromBody] UserForAuthenticationDto user) { if (!await _authenticationService.AuthenticateUserAsync(user)) { return(Unauthorized()); } var(token, exp) = await _authenticationService.CreateTokenAsync(); return(Ok(new { token, exp })); }
public async Task <IActionResult> Authenticate(UserForAuthenticationDto user) { if (!await _authManager.ValidateUser(user)) { _logger.LogWarn($"{nameof(Authenticate)}: Authentication failed. Wrong username or Password"); return(Unauthorized()); } var token = await _authManager.CreateToken(); HttpContext.Response.Headers.Add("Authorization", token); return(Ok("Logged in successfully")); }
public async Task <IActionResult> Authenticate([FromBody] UserForAuthenticationDto user) { if (!ModelState.IsValid) { return(BadRequest()); } if (!await _authManager.ValdiateUser(user)) { return(Unauthorized($"{ nameof(Authenticate)}: Authentication failed. Wrong user name or password.")); } return(Ok(new { Token = await _authManager.CreateToken() })); }
public async Task <IActionResult> Login([FromBody] UserForAuthenticationDto userForAuthentication) { if (await _userService.ValidateUser(userForAuthentication)) { return(Ok(new { Token = await _userService.CreateToken(), Username = _userService.User.UserName, _userService.User.PhoneNumber })); } return(Unauthorized()); }
public async Task <IActionResult> Login([FromBody] UserForAuthenticationDto user) { if (!await _authManager.ValidateUser(user)) { _logger.LogWarning($"{nameof(Login)}: Login failed. Wrong user name or password."); return(Unauthorized()); //throw new ProblemDetailsException(401, "Unauthorized"); } var userFromRepo = await _userManager.FindByNameAsync(user.UserName); var userToReturn = _mapper.Map <UserDto>(userFromRepo); var token = await _authManager.CreateToken(); return(Ok(new { Token = token, User = userToReturn })); }
public async Task <AuthResponseDto> Authenticate(UserForAuthenticationDto model) { var user = await GetByEmail(model?.Email !); if (user == null || !BC.Verify(model?.Password !, user.Password)) { return(new AuthResponseDto { Errors = new string[] { "Invalid email or password" } }); } var token = generateJwtToken(user); return(new AuthResponseDto { IsSuccessful = true, Token = token }); }
public async Task <IActionResult> Authenticate(UserForAuthenticationDto userForAuthenticationDto) { if (!await _authenticationManager.ValidateUser(userForAuthenticationDto)) { // Log the invalid login attempt. return(Unauthorized()); } var authenticationModel = await _authenticationManager.CreateTokenAsync(); if (!string.IsNullOrEmpty(authenticationModel.RefreshToken)) { SetRefreshTokenInCookie(authenticationModel.RefreshToken, authenticationModel.RefreshTokenExpiration); } return(Ok(new { authenticationModel.JwtToken })); }
public async Task <IActionResult> CreateToken([FromBody] UserForAuthenticationDto model) { var user = await _userMgr.FindByNameAsync(model.UserName); if (user == null) { return(BadRequest("Failed to generate token")); } if (_hasher.VerifyHashedPassword(user, user.PasswordHash, model.Password) == PasswordVerificationResult.Success) { // create claims var userClaims = await _userMgr.GetClaimsAsync(user); var claims = new[] { new Claim(JwtRegisteredClaimNames.Sub, user.UserName), new Claim(JwtRegisteredClaimNames.Jti, Guid.NewGuid().ToString()), new Claim(JwtRegisteredClaimNames.GivenName, user.FirstName), new Claim(JwtRegisteredClaimNames.FamilyName, user.LastName), new Claim(JwtRegisteredClaimNames.Email, user.Email) }.Union(userClaims); // create signature var key = new SymmetricSecurityKey( Encoding.UTF8.GetBytes(_config["Tokens:Key"])); var creds = new SigningCredentials(key, SecurityAlgorithms.HmacSha256); // create token var token = new JwtSecurityToken( claims: claims, expires: DateTime.UtcNow.AddMinutes(15), signingCredentials: creds ); return(Ok(new { token = new JwtSecurityTokenHandler().WriteToken(token), expiration = token.ValidTo })); } return(BadRequest()); }
public async Task <bool> ValidateUser(UserForAuthenticationDto userForAuthentication, ModelStateDictionary modelState) { _user = await _userManager.FindByEmailAsync(userForAuthentication.Email); if (_user == null) { modelState.TryAddModelError("wrongEmailOrPassword", "Wrong email or password"); return(false); } if (!(await _userManager.IsEmailConfirmedAsync(_user))) { modelState.TryAddModelError("notConfirmedEmail", "Email wasn't confirmed!"); return(false); } return(_user != null && await _userManager .CheckPasswordAsync(_user, userForAuthentication.Password)); }
public async Task <IActionResult> DeleteUser([FromBody] UserForAuthenticationDto userForRegistration) { var user = await _userManager.FindByNameAsync(userForRegistration.Email); if (user == null || !await _userManager.CheckPasswordAsync(user, userForRegistration.Password)) { return(Unauthorized(new AuthResponseDto { ErrorMessage = "Invalid Authentication" })); } var result = await _userManager.DeleteAsync(user); if (!result.Succeeded) { return(BadRequest()); } return(StatusCode(200)); }
public async Task <IActionResult> Login([FromBody] UserForAuthenticationDto userForAuthentication) { if (!ModelState.IsValid) { return(BadRequest(new AuthResponseDto { Errors = ModelState.Values.SelectMany(v => v.Errors.Select(b => b.ErrorMessage)) })); } var response = await _userService.Authenticate(userForAuthentication); if (!response.IsSuccessful) { return(Unauthorized(response)); } return(Ok(response)); }
public async Task <IActionResult> Login([FromForm] UserForAuthenticationDto userForLogin) { if (userForLogin == null) { throw new ArgumentNullException(nameof(UserForAuthenticationDto)); } // check user exists in the db and that the details provided are valid for login purposes var result = await _svc.Login(userForLogin.Username.Trim(), userForLogin.Password).ConfigureAwait(false); // if user does not exist return Unauthorized if (result.ResultStatus != ServiceResultStatusCode.Success) { // if username or password not recognised, produce an alert and reload the view Alert(result.Message, AlertType.warning); return(View()); } if (result.UserAccountDetails == null) { _logger.LogError($"User account passed authentication checks but UserDetails were not returned to build ClaimsPrincipal." + $"\"Username\"={userForLogin.Username}"); Alert("Account login failed due to an Internal Error", AlertType.danger); return(View()); } var claimsPrincipal = BuildClaimsPrincipal(result); // Make sure the ClaimsPrincipal was created if (claimsPrincipal == null) { // if username or password not recognised, produce an alert and reload the view _logger.LogError($"AuthController returned success but failed to build ClaimsPrincipal. \"Username\"={userForLogin.Username}"); Alert("Account login failed due to an Internal Error", AlertType.danger); return(View()); } // sign user in using cookie authentication to store principal await HttpContext.SignInAsync( CookieAuthenticationDefaults.AuthenticationScheme, claimsPrincipal).ConfigureAwait(false); return(RedirectToAction("Index", "Home")); }