public async Task Updates_with_username_and_password() { // setup var auth0serverUrl = "https://localhost"; var auth0Connection = "unit-test-connection"; var apiClient = new Mock <IAuthenticationApiClient>(MockBehavior.Strict); AuthenticationRequestDto authRequest = null; apiClient.Setup(ac => ac.AuthenticateAsync(It.IsAny <AuthenticationRequestDto>(), auth0serverUrl)) .Callback((AuthenticationRequestDto token, string server) => authRequest = token) .Returns(Task.FromResult(new AuthenticationResponseDto { IdToken = Guid.NewGuid().ToString() })); var tokenProvider = new Auth0TokenProvider(loggerFactor.Object, new Auth0ClientSettings { Auth0ServerUrl = auth0serverUrl, Auth0Connection = auth0Connection }, apiClient.Object, autoScheduler.Object); var auth0ClientSettings = new Auth0ClientSettings { Auth0ClientId = Guid.NewGuid().ToString(), Auth0Username = Guid.NewGuid().ToString(), Auth0Password = Guid.NewGuid().ToString() }; // execute await tokenProvider.AddOrUpdateClientAsync(auth0ClientSettings); // validate apiClient.Verify(ac => ac.AuthenticateAsync(It.IsAny <AuthenticationRequestDto>(), auth0serverUrl), Times.Once); Assert.NotNull(authRequest); authRequest.ClientId.Should().Be(auth0ClientSettings.Auth0ClientId); authRequest.Username.Should().Be(auth0ClientSettings.Auth0Username); authRequest.Password.Should().Be(auth0ClientSettings.Auth0Password); authRequest.Scope.Should().Be("openid"); authRequest.Connection.Should().Be(auth0Connection); authRequest.GrantType.Should().Be("password"); authRequest.Device.Should().Be("api"); }
/// <summary> /// Updates the auth0 authentication header for the client id using username and password asynchronous. /// </summary> /// <param name="clientId">The client identifier.</param> /// <param name="forceRefresh">if set to <c>true</c> [force refresh].</param> /// <returns> /// A task, when completed, ensures that the authentication header got updated. /// </returns> /// <exception cref="System.Collections.Generic.KeyNotFoundException"></exception> private async Task UpdateAuthHeaderWithUsernameAndPasswordAsync(string clientId, bool forceRefresh = false) { if (await syncObject.WaitAsync(5000)) { try { if (!clientTokenCache.ContainsKey(clientId)) { throw new KeyNotFoundException($"Cannot update the auth token for client {clientId}, because of missing information."); } // Only update if really needed. // Especially when multiple tasks are invoked at the same time we only need to update once. // Testing for a valid token happens within GetAuthHeaderForClient but outside of the locked section. // Therefore it might happen that the token was already updated once entering the locked section. if (clientTokenCache[clientId].LastRefresh > DateTimeOffset.Now.AddSeconds(-5) && !forceRefresh) { return; } var request = new AuthenticationRequestDto { ClientId = clientId, // client ID from bucket service Auth0 app Username = clientTokenCache[clientId].Auth0Username, // auth0 user Password = clientTokenCache[clientId].Auth0Password, // the corresponding password Scope = "openid", // we want openID process Connection = clientTokenCache[clientId].Auth0Connection, // auth0 connection GrantType = "password", // it should be granted based on our password Device = "api" // we want to access an API }; // authenticate with auth0 var authToken = await authenticationApiClient.AuthenticateAsync(request, clientTokenCache[clientId].Auth0ServerUrl); // set the authorization header clientTokenCache[clientId].Auth0HeaderValue = new AuthenticationHeaderValue("Bearer", authToken.IdToken); clientTokenCache[clientId].LastRefresh = DateTimeOffset.Now; logger.LogInformation($"Successfully authenticated with the service client id {clientId} with username and password."); ScheduleAutoRefresh(clientTokenCache[clientId]); } catch (Exception ex) { // any exceptions during authentication are logged here logger.LogError($"Error authenticating with service: {clientId} using user {clientTokenCache[clientId].Auth0Username}.", ex); } finally { syncObject.Release(); } } else { logger.LogWarning("Auth0TokenProvider could not get lock for retrieving an authentication token."); } }
public async Task <ActionResult <AuthenticationResponseDto> > Authenticate(AuthenticationRequestDto requestDto) { _logger.LogInformation($"{nameof(AccountController)}: {nameof(Authenticate)} was called."); var request = _mapper.Map <AuthenticationRequest>(requestDto); var response = await _authenticationService.AuthenticateAsync(request); return(Ok(_mapper.Map <AuthenticationResponseDto>(response))); }
public IActionResult Authenticate([FromBody] AuthenticationRequestDto model) { var response = _userService.Authenticate(model); if (response == null) { return(BadRequest("Kullanıcı adı veya şifre yanlış")); } return(Ok(response)); }
private void ValidateAuthenticationRequest(AuthenticationRequestDto authenticationRequestDto) { if (authenticationRequestDto == null || string.IsNullOrWhiteSpace(authenticationRequestDto.UserName) || string.IsNullOrWhiteSpace(authenticationRequestDto.UserPassword)) { throw new SSException( ExceptionCodes.InvalidInput, ExceptionMessages.InvalidInput); } }
public void AuthenticationTestPositive() { AuthenticationRequestDto authenticationRequest = new AuthenticationRequestDto { UserName = "******", UserPassword = "******" }; var authenticationProvider = Factory.AuthenticationBusinessProvider(); var responseDto = authenticationProvider.Authenticate(authenticationRequest); Assert.AreEqual(responseDto.ServiceResponseStatus, 1); }
public IActionResult Post([FromBody] AuthenticationRequestDto dto) { var success = this.securityService.SignIn(dto.UserName, dto.Password); if (!success) { return(this.Unauthorized()); } var accessToken = this.jwtTokenGenerator.GenerateAccessToken(dto.UserName, ToClaim(dto)); return(this.Json(new AuthenticationResultDto() { Token = accessToken, UserName = dto.UserName, })); }
public UserActivateResponseDto UpdateUserPassword(UserPasswordRequestDto userPasswordRequestDto) { UserActivateResponseDto userActivateResponseDto = new UserActivateResponseDto(); try { AuthenticationRequestDto authenticationRequestDto = new AuthenticationRequestDto { UserName = userPasswordRequestDto.UserName, UserPassword = userPasswordRequestDto.Password }; var authenticationResponseDto = reportAuthentication.Authenticate(authenticationRequestDto); if (string.IsNullOrEmpty(authenticationResponseDto.LoginName)) { userActivateResponseDto.ServiceResponseStatus = 0; userActivateResponseDto.ErrorMessage = "Old Password is invalid"; } else { userActivateResponseDto = businessAuthentication.UpdateUserPassword(userPasswordRequestDto); userActivateResponseDto.ServiceResponseStatus = 1; } } catch (SSException applicationException) { userActivateResponseDto = new UserActivateResponseDto { ServiceResponseStatus = 0, ErrorMessage = applicationException.Message, ErrorCode = applicationException.ExceptionCode }; } catch (Exception exception) { userActivateResponseDto = new UserActivateResponseDto { ServiceResponseStatus = 0, ErrorCode = ExceptionAttributes.ExceptionCodes.InternalServerError, ErrorMessage = exception.Message }; } return(userActivateResponseDto); }
public async Task <SignInResultDto> SignInAsync(AuthenticationRequestDto authenticationRequestDto) { var signInResult = await _signInManager.PasswordSignInAsync(authenticationRequestDto.UserName, authenticationRequestDto.Password, true, false); var serializedJwtToken = string.Empty; if (signInResult.Succeeded) { serializedJwtToken = await _jwtTokenAppFactory.CreateSerializedJtwTokenAsync(authenticationRequestDto.UserName); } var result = new SignInResultDto { SerializedJwtToken = serializedJwtToken, Succeeded = signInResult.Succeeded }; return(result); }
public AuthenticationResponseDto Authenticate(AuthenticationRequestDto authenticationRequestDto) { ValidateAuthenticationRequest(authenticationRequestDto); AuthenticationResponseDto auth; var userName = authenticationRequestDto.UserName.Trim().ToLower(); var password = authenticationRequestDto.UserPassword; var userInformation = authenticationRepository.GetUserInformation(new CustomUserInformationCommandModel { UserName = userName, Password = password }); if (userInformation.LoginName != null) { var hashCode = userInformation.PasswordSalt; //Password Hasing Process Call Helper Class Method var encodingPasswordString = Helper.EncodePassword(password, hashCode); if (userInformation.UserPassword != encodingPasswordString) { return(new AuthenticationResponseDto { ErrorMessage = "Invalid credentials" }); } } else { return(new AuthenticationResponseDto { ErrorMessage = "Invalid credentials" }); } var responseSend = GetAuthenticationResponse(userInformation); responseSend.Token = Helper.GenerateToken(userInformation); responseSend.TokenExpiry = Helper.TokenExpirationMins; //var byteActualPassword = Convert.FromBase64String(userInformation.UserPassword); //var isValidatedPassword = ValidateRecord( // ComputeHashedValue(password, userInformation.PasswordSalt), // byteActualPassword); return(responseSend); }
public IActionResult Post([FromBody] AuthenticationRequestDto dto) { var userResult = _userReadConductor.FindAll(e => e.Username == dto.Username && e.Password == dto.Password); if (userResult.ResultObject == null) { return(BadRequest <AuthenticationResponseDto>(null, new Error() { Key = "Credentials Incorrect", Message = "Username or Password is incorrect.", ErrorType = ErrorType.Error })); } var user = userResult.ResultObject.FirstOrDefault(); // authentication successful so generate jwt token var tokenHandler = new JwtSecurityTokenHandler(); var key = Encoding.ASCII.GetBytes("some_big_key_value_here_secret"); var tokenDescriptor = new SecurityTokenDescriptor { Subject = new ClaimsIdentity(new Claim[] { new Claim(ClaimTypes.Name, "1") }), Expires = DateTime.UtcNow.AddDays(7), SigningCredentials = new SigningCredentials(new SymmetricSecurityKey(key), SecurityAlgorithms.HmacSha256Signature) }; var token = tokenHandler.CreateToken(tokenDescriptor); var response = new AuthenticationResponseDto(); response.Authenticated = true; response.FirstName = user.FirstName; response.LastName = user.LastName; response.Username = user.Username; response.Token = tokenHandler.WriteToken(token); return(Ok(response)); }
public AuthenticationResponseDto Authenticate(AuthenticationRequestDto authenticationRequestDto) { AuthenticationResponseDto authenticationResponseDto; try { authenticationResponseDto = reportAuthentication.Authenticate(authenticationRequestDto); if (string.IsNullOrEmpty(authenticationResponseDto.LoginName)) { authenticationResponseDto.ServiceResponseStatus = 0; } else { authenticationResponseDto.ServiceResponseStatus = 1; } } catch (SSException exception) { authenticationResponseDto = new AuthenticationResponseDto { ServiceResponseStatus = 0, ErrorMessage = exception.Message, ErrorCode = exception.ExceptionCode }; } catch (Exception exception) { authenticationResponseDto = new AuthenticationResponseDto { ServiceResponseStatus = 0, ErrorCode = ExceptionAttributes.ExceptionCodes.InternalServerError, ErrorMessage = exception.Message }; } return(authenticationResponseDto); }
public AuthenticationResponseDto Authenticate(AuthenticationRequestDto model) { var user = _context.Users.SingleOrDefault(x => x.Username == model.UserName && x.Password == model.Password); // return null if user not found if (user == null) { return(null); } // authentication successful so generate jwt and refresh tokens var jwtToken = generateJwtToken(user); var refreshToken = generateRefreshToken(); RefreshToken _refreshToken = new RefreshToken(); _refreshToken = refreshToken; _refreshToken.UserId = user.Id; // save refresh token _context.Add(refreshToken); _context.SaveChanges(); return(new AuthenticationResponseDto(user, jwtToken, refreshToken.Token)); }
public async Task <IActionResult> LoginAsync([FromBody] AuthenticationRequestDto authenticationRequestDto) { var signInResult = await _signInService.SignInAsync(authenticationRequestDto); return(Ok(signInResult)); }
private IEnumerable <Claim> ToClaim(AuthenticationRequestDto dto) => new List <Claim> { new Claim(ClaimTypes.GivenName, dto.UserName), new Claim(ClaimTypes.Surname, dto.UserName) };
public AuthentificationRequestBuilder() { request = new AuthenticationRequestDto(); }