public async Task AuthenticateServiceReturnedToken() { var request = new AuthenticateRequestDto { Password = "******", Username = "******" }; const string expectedResponseToken = "someJwt"; var expectedResponse = new AuthenticateResponse { Token = expectedResponseToken }; _mockAuthenticationService.Setup(service => service.Authenticate(request)) .Returns(Task.FromResult(expectedResponse)); var actualResult = await _usersController.Authenticate(request); Assert.IsType <OkObjectResult>(actualResult); var okResult = (OkObjectResult)actualResult; Assert.IsType <AuthenticateResponse>(okResult.Value); var okResultObject = (AuthenticateResponse)okResult.Value; Assert.Equal(expectedResponseToken, okResultObject.Token); }
public async Task <AuthenticateResponseDto> Login(AuthenticateRequestDto request) { return(await ProcessRequest(async() => { var user = await _unitOfWork.User.FindByNameAsync(request.UserName); if (user == null) { throw new AppException(_logger, $"User: {request.UserName} not found"); } if (!VerifyPasswordHash(request.Password, user.PasswordHash, user.PasswordSalt)) { throw new AppException(_logger, $"Login Failed"); } var jwtToken = _tokenService.GenerateJWTToken(user, 5); var refreshToken = _tokenService.GenerateRefreshJWTToken(user); user.RefreshTokens.Add(refreshToken); refreshToken.AccessToken = jwtToken; _unitOfWork.User.Update(user); await _unitOfWork.SaveAsync(); return new AuthenticateResponseDto(user, jwtToken, refreshToken.Token); })); }
public async Task <AuthenticateResponseDto> AuthenticateAsync(AuthenticateRequestDto request, string ipv4Address, string ipv6Address) { await _authenticateRequestValidator.ValidateAndThrowAsync(request); var account = _dbContext.Accounts.SingleOrDefault(x => x.Email == request.Email); if (account == null || !account.IsVerified || !BC.Verify(request.Password, account.PasswordHash)) { throw new AppException("Email or password is incorrect"); } // authentication successful so generate jwt and refresh tokens var jwtToken = GenerateJwtToken(account); var refreshToken = GenerateRefreshToken(ipv4Address, ipv6Address); account.RefreshTokens.Add(refreshToken); // remove old refresh tokens from account RemoveOldRefreshTokens(account); // save changes to db _dbContext.Update(account); await _dbContext.SaveChangesAsync(); var response = _mapper.Map <AuthenticateResponseDto>(account); response.JwtToken = jwtToken; response.RefreshToken = refreshToken.Token; return(response); }
public async Task <IActionResult> Authenticate(AuthenticateRequestDto model) { try { if (model == null) { throw new ArgumentNullException(nameof(model)); } var response = await _authenticationService.Authenticate(model); if (response == null) { _logger.LogInformation($"Unable to authenticate user {model.Username}"); return(BadRequest()); } return(Ok(response)); } catch (Exception e) { _logger.LogError(e, "Exception happened during authentication request"); return(BadRequest()); } }
public async Task <AuthenticateResponseDto> Authenticate(AuthenticateRequestDto model) { var user = await _context.Users.Include(user => user.Role).FirstOrDefaultAsync(u => u.Username == model.Username && u.Password == _hashingManager.GetHashedPassword(model.Password)); if (user == null) { throw new AuthenticationException("Username or password is incorrect"); } if (!user.IsActivated) { throw new AuthenticationException("Please activate your account first!"); } if ((user.WasPasswordChanged && user.WasPasswordForgotten) || (!user.WasPasswordChanged && !user.WasPasswordForgotten)) { user.WasPasswordChanged = false; _context.Users.Update(user); await _context.SaveChangesAsync(); var token = _jwtService.GenerateAuthenticationJWT(user); var authenticateResponseDto = new AuthenticateResponseDto(user, token); return(authenticateResponseDto != null ? authenticateResponseDto : throw new AuthenticationException("Username or password is incorrect")); } throw new AuthenticationException("Username or password is incorrect"); }
public void AuthenticateRequestValidation_Success_When_AllFilled() { var request = new AuthenticateRequestDto { Email = "*****@*****.**", Password = "******" }; AuthenticateRequestValidator.Validate(request).IsValid.Should().BeTrue(); }
public void AuthenticateRequestValidation_ShouldFailed_When_Email_Not_Valid() { var request = new AuthenticateRequestDto { Email = "testtest.com", Password = "******" }; AuthenticateRequestValidator.Validate(request).IsValid.Should().BeFalse(); }
public void AuthenticateRequestValidation_ShouldFailed_When_Password_Missing() { var request = new AuthenticateRequestDto { Email = "*****@*****.**", Password = null }; AuthenticateRequestValidator.Validate(request).IsValid.Should().BeFalse(); }
public IActionResult Authenticate(AuthenticateRequestDto model) { var response = _securityService.Authenticate(model); if (response == null) { return(BadRequest(new { message = "Username or password is incorrect" })); } return(Ok(response)); }
public async Task <IActionResult> Login(AuthenticateRequestDto request) { try { var login = await _userService.Login(request); setTokenCookie(login.RefreshToken); return(Ok(login)); } catch (AppException ex) { return(BadRequest(new { message = ex.Message })); } }
public async Task AuthenticateServiceReturnedNullExpectBadRequest() { var request = new AuthenticateRequestDto { Password = "******", Username = "******" }; _mockAuthenticationService.Setup(service => service.Authenticate(request)) .Returns(Task.FromResult(null as AuthenticateResponse)); var actualResult = await _usersController.Authenticate(request); Assert.IsType <BadRequestResult>(actualResult); }
public async Task Authenticate_ShouldReturn_OkResultWhenUserIsValid() { // Arrange var newAuthenticationRequest = new AuthenticateRequestDto { Username = "******", Password = "******" }; // Act var response = await _userController.AuthenticateAsync(newAuthenticationRequest); // Assert Assert.IsType <OkObjectResult>(response.Result); }
public AuthenticateResponseDto Authenticate(AuthenticateRequestDto model) { //var user = _users.SingleOrDefault(x => x.Username == model.Username && x.Password == model.Password); var user = "******"; // return null if user not found if (user == null) { return(null); } // authentication successful so generate jwt token var token = generateJwtToken(user); return(new AuthenticateResponseDto(token)); }
public async Task <IActionResult> Authenticate([FromBody] AuthenticateRequestDto request) { // If validation fails, return error response if (!ModelState.IsValid) { return(ValidationProblem(ModelState)); } // Authenticate user var result = await _signInManager.PasswordSignInAsync(request.Email, request.Password, isPersistent : false, lockoutOnFailure : false); if (result.Succeeded) { // Retrieve authenticated user if successfully authenticated var user = await _userManager.FindByEmailAsync(request.Email); // If email not yet confirmed, return error response if (!user.EmailConfirmed) { return(Unauthorized(new ErrorDto(ErrorDto.EmailNotVerified, "Please verify your email address by clicking the link in the email you have been sent."))); } var tokenString = await _tokenGenerator.GenerateTokenForDefaultRole(user); // Return authentication token return(Ok(new AuthenticatedResponseDto { Token = tokenString, })); } // If two factor auth is required, return success response if (result.RequiresTwoFactor) { return(Ok(new Require2FAResponseDto())); } // If user is locked out, return error response if (result.IsLockedOut) { return(Unauthorized(new ErrorDto(ErrorDto.UserLockedOut, "Account locked"))); } // If authentication failed, return error response return(Unauthorized(new ErrorDto(ErrorDto.UserNotFound, "User not found matching the provided credentials"))); }
public async Task <AuthenticateResponse> Authenticate(AuthenticateRequestDto authenticationRequestDto) { if (authenticationRequestDto == null) { throw new ArgumentNullException(nameof(authenticationRequestDto)); } var user = await _usersRepo.Authenticate(authenticationRequestDto.Username, authenticationRequestDto.Password); return(user == null ? null : new AuthenticateResponse { Token = GenerateJwtToken(user) }); }
public IActionResult Login([FromBody] AuthenticateRequestDto authRequest) { if (authRequest == null) { return(BadRequest()); } // Check if Master Admin account exists // If not then create then validate user creds if (PerformanceReviewRepository.GetAll <Employee>() .FirstOrDefault(emp => emp.Username.ToUpper() == "ADMIN" && emp.Password == "ADMIN") == null) { var admin = new Employee { IsAdmin = true, Username = "******", Password = "******", FirstName = "ADMIN", Surname = "ADMIN", JobTitle = "Administrator", }; PerformanceReviewRepository.Insert(admin); } // This part is a stub for a real Authentication Service // Find account matching username and password supplied // This is the account details client will store as User Logged In var authenticatedEmployeeAccountFromRepo = PerformanceReviewRepository.GetAll <Employee>() .FirstOrDefault(emp => emp.Username.ToUpper() == authRequest.Username.ToUpper() && emp.Password == authRequest.Password); if (authenticatedEmployeeAccountFromRepo == null) { return(NotFound()); } var authenticatedEmployeeAccount = Mapper.Map <EmployeeDto>(authenticatedEmployeeAccountFromRepo); return(Ok(authenticatedEmployeeAccount)); }
public IActionResult Authenticate([FromBody] AuthenticateRequestDto request) { // Authenticate user var user = _userService.Authenticate(request.Email, request.Password); // If invalid credentials provided, return an unauthorized response if (user == null) { return(Unauthorized()); } // Generate JWT token to return in the response 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.Roles[0].Name), }), Expires = DateTime.UtcNow.AddDays(7), SigningCredentials = new SigningCredentials(new SymmetricSecurityKey(key), SecurityAlgorithms.HmacSha256Signature) }; var token = tokenHandler.CreateToken(tokenDescriptor); var tokenString = tokenHandler.WriteToken(token); // Return basic user info (without password) and token to store client side return(Ok(new AuthenticateResponseDto { Token = tokenString, User = new UserDto { Id = user.Id, Email = user.Email, FirstName = user.FirstName, LastName = user.LastName, Roles = user.Roles.Select(i => i.Name).ToArray(), }, })); }
public async Task OnAuthorization_ShouldReturn_NotNullForExistentUser() { // Arrange var newAuthenticateRequest = new AuthenticateRequestDto { Username = "******", Password = "******" }; // Act var response = await _testingService.AuthenticateAsync(newAuthenticateRequest); var taskSource = new TaskCompletionSource <UserDto>(); taskSource.SetResult(_mockMapper.Map <UserDto>(response)); _authorizationFilterContext.HttpContext.Items["User"] = taskSource.Task; await _authorizeAttribute.OnAuthorizationAsync(_authorizationFilterContext); // Assert Assert.Null(_authorizationFilterContext.Result); }
public async Task Authenticate_ShouldReturn_AValidResponseForValidUser() { // Arrange _context = new PizzaProblemContext( new DbContextOptionsBuilder <PizzaProblemContext>() .UseInMemoryDatabase(databaseName: "Authenticate") .Options); _context.Database.EnsureCreated(); _testingService = new UserService(_testingOptions, _mockMapper, _context); var newAuthenticateRequest = new AuthenticateRequestDto { Username = "******", Password = "******" }; // Act var response = await _testingService.AuthenticateAsync(newAuthenticateRequest); // Assert Assert.Equal(1, response.Id); }
public async Task Invoke_AttachsUserToContext_WhenTokenNotNull() { // Arrange var newAuthenticateRequest = new AuthenticateRequestDto { Username = "******", Password = "******" }; var response = await _testingService.AuthenticateAsync(newAuthenticateRequest); _mockContext.Request.Headers.Add("Authorization", response.Token); // Act await _authenticationMiddleware.InvokeAsync(_mockContext, _next); // Assert Assert.True(_mockContext.Items.TryGetValue("User", out var header)); var user = header as Task <UserDto>; Assert.Equal(2, user.Result.Id); }
public async Task OnAuthorization_ShouldReturn_UnauthorizedForNonExistentUser() { // Arrange var newAuthenticateRequest = new AuthenticateRequestDto { Username = "******", Password = "******" }; // Act var response = await _testingService.AuthenticateAsync(newAuthenticateRequest); var taskSource = new TaskCompletionSource <UserDto>(); taskSource.SetResult(_mockMapper.Map <UserDto>(response)); _authorizationFilterContext.HttpContext.Items["User"] = taskSource.Task; await _authorizeAttribute.OnAuthorizationAsync(_authorizationFilterContext); // Assert var result = _authorizationFilterContext.Result as JsonResult; Assert.Equal(StatusCodes.Status401Unauthorized, result.StatusCode); }
public async Task Invoke_AttachsUserToContext_WhenTokenNotNull() { // Arrange var newAuthenticateRequest = new AuthenticateRequestDto { Username = "******", Password = "******" }; var response = await _userController.AuthenticateAsync(newAuthenticateRequest); var result = response.Result as OkObjectResult; _mockContext.Request.Headers.Add("Authorization", _mockMapper.Map <AuthenticateResponseDto>(result.Value).Token); // Act await _authenticationMiddleware.InvokeAsync(_mockContext, _next); // Assert Assert.True(_mockContext.Items.TryGetValue("User", out var header)); var user = header as Task <User>; Assert.Equal(2, user.Result.Id); }
public async Task <ActionResult <AuthenticateResponseDto> > AuthenticateAsync(AuthenticateRequestDto model) { var request = _mapper.Map <AuthenticateRequest>(model); var response = await _userService.AuthenticateAsync(request); if (response == null) { return(BadRequest(new { message = "Username or password is incorrect" })); } response.Token = JwtTokenGenerator.GenerateJwtToken(response.Id, _appSettings.Secret); return(Ok(_mapper.Map <AuthenticateResponseDto>(response))); }
public async Task <ActionResult <AuthenticateResponseDto> > AuthenticateAsync(AuthenticateRequestDto request) { var response = await _accountService.AuthenticateAsync(request, GetIpv4Address(), GetIpv6Address()); SetTokenCookie(response.RefreshToken); return(Ok(response)); }
public AuthenticateResponseDto PostAuthAuthenticate(string raceId, AuthenticateRequestDto authentication) { return(apiAuthentication.Authenticate(raceId, authentication)); }
public async Task <IActionResult> Authenticate(AuthenticateRequestDto model) { return(Ok(await _authenticationService.Authenticate(model))); }