public async Task Handle_GivenUserDoesExistButPasswordDoesNotVerifyAndAccountsAreLockableAndAttemptsNotLess_ExpectFailedResultAndUnsuccessfulAttemptLoggedWithLockApplied() { var user = new Mock <IUser>(); user.Setup(x => x.PasswordHash).Returns(BCrypt.Net.BCrypt.HashPassword("password")); user.Setup(x => x.IsVerified).Returns(true); var userRepository = new Mock <IUserRepository>(); var unitOfWork = new Mock <IUnitOfWork>(); unitOfWork.Setup(x => x.SaveEntitiesAsync(It.IsAny <CancellationToken>())).ReturnsAsync(() => true); userRepository.Setup(x => x.UnitOfWork).Returns(unitOfWork.Object); userRepository.Setup(x => x.FindByEmailAddress(It.IsAny <string>(), It.IsAny <CancellationToken>())) .ReturnsAsync(() => Maybe.From(user.Object)); var clock = new Mock <IClock>(); var securitySettings = new Mock <IOptions <SecuritySettings> >(); securitySettings.Setup(x => x.Value).Returns(() => new SecuritySettings { AllowedAttempts = 0 }); var fido = new Mock <IFido2>(); var handler = new AuthenticateUserCommandHandler(userRepository.Object, clock.Object, securitySettings.Object, fido.Object); var cmd = new AuthenticateUserCommand("email-address", "wrong-password"); var result = await handler.Handle(cmd, CancellationToken.None); Assert.True(result.IsFailure); Assert.Equal(ErrorCodes.AuthenticationFailed, result.Error.Code); user.Verify(x => x.ProcessUnsuccessfulAuthenticationAttempt(It.IsAny <DateTime>(), true)); }
public async Task TestHandle_EntityExists_ShouldReturnCorrectly(string email, string password) { // Arrange var userProfile = new UserProfile(Guid.NewGuid().ToString(), email, "username"); Context.UserProfiles.Add(userProfile); await Context.SaveChangesAsync(); var command = new AuthenticateUserCommand { Email = email, Password = password }; var mockedUserService = new Mock <IUserService>(); mockedUserService.Setup(s => s.Authenticate(email, password)) .ReturnsAsync(Result.CreateSuccess); var sut = new AuthenticateUserCommand.Handler(mockedUserService.Object, Mapper, Context); var expectedResult = Mapper.Map <UserWithProfileDto>(userProfile); // Act var actualResult = await sut.Handle(command, CancellationToken.None); // Assert actualResult.Should().BeEquivalentTo(expectedResult); }
public async Task TestHandle_ShouldCallUserServiceAuthenticateCorrectly(string email, string password) { // Arrange var userProfile = new UserProfile(Guid.NewGuid().ToString(), email, "username"); Context.UserProfiles.Add(userProfile); await Context.SaveChangesAsync(); var command = new AuthenticateUserCommand { Email = email, Password = password }; var mockedUserService = new Mock <IUserService>(); mockedUserService.Setup(s => s.Authenticate(email, password)) .ReturnsAsync(Result.CreateSuccess()); var sut = new AuthenticateUserCommand.Handler(mockedUserService.Object, Mapper, Context); // Act await sut.Handle(command, CancellationToken.None); // Assert mockedUserService.Verify(s => s.Authenticate(email, password), Times.Once); }
// User Informations and Roles Validate Method private Task <ClaimsIdentity> GetClaims(AuthenticateUserCommand command) { var customerCommand = _repository.GetByUsername(command.Username); if (customerCommand == null) { return(Task.FromResult <ClaimsIdentity>(null)); } _registeredUser = true; var user = new User(customerCommand.UserId, customerCommand.Username, customerCommand.Password, _registeredUser); var name = new Name(customerCommand.FirstName, customerCommand.LastName); var document = new Document(customerCommand.Document); var email = new Email(customerCommand.Email); var customer = new Customer(customerCommand.Id, name, document, email, user); _customer = customer; if (!user.Authenticate(command.Username, command.Password)) { return(Task.FromResult <ClaimsIdentity>(null)); } return(Task.FromResult(new ClaimsIdentity( new GenericIdentity(customerCommand.Username, "Token"), new [] { new Claim("WebStore", "User") }))); }
public async Task Handle_GivenSavingSucceeds_ExpectSuccessfulResult() { var user = new Mock <IUser>(); user.Setup(x => x.PasswordHash).Returns(BCrypt.Net.BCrypt.HashPassword("password")); user.Setup(x => x.Profile).Returns(new Profile(TestVariables.UserId, "first-name", "last-name")); user.Setup(x => x.AuthenticatorApps).Returns(new List <AuthenticatorApp>()); user.Setup(x => x.AuthenticatorDevices).Returns(new List <AuthenticatorDevice>()); user.Setup(x => x.IsVerified).Returns(true); var userRepository = new Mock <IUserRepository>(); var unitOfWork = new Mock <IUnitOfWork>(); unitOfWork.Setup(x => x.SaveEntitiesAsync(It.IsAny <CancellationToken>())).ReturnsAsync(() => true); userRepository.Setup(x => x.UnitOfWork).Returns(unitOfWork.Object); userRepository.Setup(x => x.FindByEmailAddress(It.IsAny <string>(), It.IsAny <CancellationToken>())) .ReturnsAsync(() => Maybe.From(user.Object)); var clock = new Mock <IClock>(); var securitySettings = new Mock <IOptions <SecuritySettings> >(); securitySettings.Setup(x => x.Value).Returns(new SecuritySettings()); var fido = new Mock <IFido2>(); var handler = new AuthenticateUserCommandHandler(userRepository.Object, clock.Object, securitySettings.Object, fido.Object); var cmd = new AuthenticateUserCommand("email-address", "password"); var result = await handler.Handle(cmd, CancellationToken.None); Assert.True(result.IsSuccess); }
public void AuthenticateCommand_PresentWrongPassword_ThrowsException() { // ---- Arrange ---- const string email = "*****@*****.**"; const string name = "Test user"; const string wrongPassword = "******"; const string password = "******"; var passwordHash = AuthUtils.GetMd5Hash(password); var testUser = new UserIdentityModel( Guid.NewGuid(), email, "Test user", name, passwordHash, Instant.MinValue); _authRepositoryMock.Setup(r => r.GetUserIdentity(email)) .ReturnsAsync(() => testUser); var command = new AuthenticateUserCommand(email, wrongPassword); var handler = new AuthenticateUserCommandHandler(_repositoryProviderMock.Object, _configuration); // ---- Act & Assert ---- Assert.ThrowsAsync <WrongPasswordException>( async() => await handler.Handle(command, CancellationToken.None)); _authRepositoryMock.Verify(r => r.GetUserIdentity(email), Times.Once); }
public IActionResult Login(AuthenticateUserCommand command) { if (command.Username == "DotNetCoreServer" && command.Password == "1234") { var claims = new[] { new Claim("userId", "1"), // Aqui é adicionado o id do usuário new Claim(JwtRegisteredClaimNames.Jti, Guid.NewGuid().ToString()) }; var key = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(_config["JwtSettings:SecretKey"])); var credential = new SigningCredentials(key, SecurityAlgorithms.HmacSha256); var token = new JwtSecurityToken ( claims: claims, signingCredentials: credential, expires: DateTime.Now.AddMinutes(300), issuer: _config["JwtSettings:Issuer"], audience: _config["JwtSettings:Audience"] ); var jwtToken = new { token = new JwtSecurityTokenHandler().WriteToken(token), expiration = token.ValidTo }; return(Ok(jwtToken)); } else { return(Unauthorized()); } }
private static Task <ClaimsIdentity> GetClaimsIdentity(AuthenticateUserCommand user) { if (user.Username == "andrebaltieri" && user.Password == "andrebaltieri") { return(Task.FromResult(new ClaimsIdentity( new GenericIdentity(user.Username, "Token"), new[] { new Claim("Balta.io", "User") }))); } if (user.Username == "batman" && user.Password == "batman") { return(Task.FromResult(new ClaimsIdentity( new GenericIdentity(user.Username, "Token"), new[] { new Claim("Balta.io", "Admin"), new Claim("Balta.io", "User") }))); } return(Task.FromResult <ClaimsIdentity>(null)); }
private Task <ClaimsIdentity> GetClaims(AuthenticateUserCommand command) { var customer = _repository.GetByUsername(command.Username); if (customer == null) { return(Task.FromResult <ClaimsIdentity>(null)); } if (!customer.User.Authenticate(command.Username, command.Password)) { return(Task.FromResult <ClaimsIdentity>(null)); } _customer = customer; var claims = new[] //fetch user roles or permissions { new Claim("ModernStore", "User"), new Claim("ModernStore", "Admins") }; return(Task.FromResult(new ClaimsIdentity( new GenericIdentity(customer.User.Username, "Token"), claims))); }
public GenericCommandResult Authenticate(AuthenticateUserCommand command) { command.Validate(); if (command.Invalid) { return(new GenericCommandResult(false, "Erro ao autenticar o usuário", command.Notifications)); } var user = _userRepository.Authenticate(command.Email); if (user == null) { return(new GenericCommandResult(false, "Usuário inválido", command.Notifications)); } var password = Password.VerifyPasswordHash(command.Password, user.PasswordHash, user.PasswordSalt); if (!password) { return(new GenericCommandResult(false, "Senha incorreta", Notifications)); } var token = TokenService.GenerateToken(user.Id.ToString(), Settings.Secret, 6); user.Token = token; return(new GenericCommandResult(true, "Usuário autenticado com sucesso", (DTOs.User)user)); }
public async Task WhenUserCredentialsAreCorrect_ThenUserModelIsReturned() { //Arrange var user = new User() { Id = 1, Username = "******", Password = "******", Role = "Admin" }; var users = new List <User>() { user }; dbContextMock.Setup(x => x.Users).Returns(users.ToDbSet()); //Act var command = new AuthenticateUserCommand() { Username = "******", Password = "******" }; var userModel = await authenticateUserCommandHandler.Handle(command, new CancellationToken()); //Assert Assert.Equal(user.Id, userModel.Id); Assert.Equal(user.Role, userModel.Role); Assert.Equal(user.Username, userModel.Username); }
public async Task <IActionResult> Login( [FromBody] AuthRequest authRequest, CancellationToken cancellationToken) { var command = new AuthenticateUserCommand(authRequest.Email, authRequest.Password); IActionResult response; try { var auth = await Mediator.Send(command, cancellationToken); response = ApiOk(auth.AsResponse()); } catch (InvalidEmailFormatException ex) { response = ApiBadRequest(ApiErrors.InvalidEmailFormat, ex.Email); } catch (UserNotFoundByEmailException) { response = ApiBadRequest(ApiErrors.UserIdentityNotExists); } catch (WrongPasswordException) { response = ApiBadRequest(ApiErrors.IncorrectPassword); } return(response); }
public async Task <IActionResult> Post([FromForm] AuthenticateUserCommand command) { if (command == null) { return(await Response(null, new List <Notification> { new Notification("User", "Usuário ou senha inválidos") })); } _user = _userRepository.GetByUsername(command.Username); if (_user == null) { return(await Response(null, new List <Notification> { new Notification("User", "Usuário ou senha inválidos") })); } var token = TokenService.GenerateToken(_user); var response = new { token = token, expires = DateTime.UtcNow.AddHours(2), user = new { id = _user.Id, name = _user.Name.ToString(), username = _user.Username } }; return(Ok(response)); }
public void Constructor_GiveValidArguments_PropertiesAreSet() { var command = new AuthenticateUserCommand("email-address", "password"); Assert.Equal("email-address", command.EmailAddress); Assert.Equal("password", command.Password); }
public async Task <IActionResult> Post([FromForm] AuthenticateUserCommand command) { if (command == null) { return(await Response(null, new List <Notification> { new Notification("User", "Usuário e/ou senha inválida!") })); } var identity = await GetClaims(command); if (identity == null) { return(await Response(null, new List <Notification> { new Notification("User", "Usuário e/ou senha inválida!") })); } var claims = new[] { new Claim(JwtRegisteredClaimNames.UniqueName, command.username), new Claim(JwtRegisteredClaimNames.NameId, command.username), new Claim(JwtRegisteredClaimNames.Email, command.username), new Claim(JwtRegisteredClaimNames.Sub, command.username), new Claim(JwtRegisteredClaimNames.Jti, await _tokenOptions.JtiGenerator()), new Claim(JwtRegisteredClaimNames.Iat, ToUnixEpochDate(_tokenOptions.IssuedAt).ToString(), ClaimValueTypes.Integer64), identity.FindFirst("ModernStore"), identity.FindFirst("Teste") }; //User.Identity.Name //User.Claims var jwt = new JwtSecurityToken( issuer: _tokenOptions.Issuer, audience: _tokenOptions.Audience, claims: claims.AsEnumerable(), notBefore: _tokenOptions.NotBefore, expires: _tokenOptions.Expiration, signingCredentials: _tokenOptions.SigningCredentials ); var encodedJwt = new JwtSecurityTokenHandler().WriteToken(jwt); var response = new { token = encodedJwt, expires = (int)_tokenOptions.ValidFor.TotalSeconds, user = new { id = _customer.Id, name = $"{_customer.FirstName} {_customer.LastName}", email = _customer.Email.Address, username = _customer.User.Username } }; var json = JsonConvert.SerializeObject(response, _serializerSettings); return(new OkObjectResult(response)); }
private Task <ClaimsIdentity> GetClaims(AuthenticateUserCommand command) { // Verificar Padrão DomainServices var customer = _repository.GetByUsername(command.username); if (customer == null) { return(Task.FromResult <ClaimsIdentity>(null)); } if (!customer.User.Authenticate(command.username, command.password)) { return(Task.FromResult <ClaimsIdentity>(null)); } _customer = customer; return(Task.FromResult(new ClaimsIdentity( new GenericIdentity(customer.User.Username, "Token"), new[] { new Claim("ModernStore", "User"), new Claim("Teste", "123") }))); }
public override async Task GrantResourceOwnerCredentials(OAuthGrantResourceOwnerCredentialsContext context) { //Trabalhar com os CORS context.OwinContext.Response.Headers.Add("Access-Control-Allow-Origin", new[] { "*" }); dynamic user; using (_container.BeginExecutionContextScope()) { var _userService = _container.GetInstance <IUserAppService>(); var authenticateCommand = new AuthenticateUserCommand(context.UserName, context.Password); user = _userService.Authenticate(authenticateCommand); if (user == null) { context.SetError("invalid_grant", "Usuário ou senha inválidos"); return; } } var identity = new ClaimsIdentity(context.Options.AuthenticationType); identity.AddClaim(new Claim(ClaimTypes.Name, user.Email)); identity.AddClaim(new Claim(ClaimTypes.Role, user.UserRole.ToString())); GenericPrincipal principal = new GenericPrincipal(identity, new string[] { user.UserRole == EUserRole.Admin ? "admin" : "" }); Thread.CurrentPrincipal = principal; context.Validated(identity); }
public async Task <BaseResponse <AuthenticateUserResponse> > Handle(AuthenticateUserCommand request, CancellationToken cancellationToken) { var user = await _applicationDbContext.Users.FirstOrDefaultAsync(usr => usr.Email == request.AuthenticateUserRequest.UserEmail, cancellationToken); var response = new BaseResponse <AuthenticateUserResponse>(); if (user == null) { response.SetValidationErrors(new [] { "User does not exists" }); return(response); } var verified = BCrypt.Net.BCrypt.Verify(request.AuthenticateUserRequest.Password, user.Password); if (!verified) { response.SetIsForbidden(); return(response); } response.SetIsOk(new AuthenticateUserResponse(user.Id)); return(response); }
public async Task <IActionResult> Authenticate([FromBody] AuthenticateUserCommand request) { var user = await _mediator.Send(new AuthenticateUserCommand { UserName = request.UserName, Password = request.Password }); if (user == null) { return(BadRequest(new { message = "Incorrect username or password" })); } var tokenHandler = new JwtSecurityTokenHandler(); var key = Encoding.ASCII.GetBytes(_authenticationSettings.Secret); var tokenDescriptor = new SecurityTokenDescriptor { Subject = new ClaimsIdentity(new Claim[] { new Claim(ClaimTypes.Name, user.Id.ToString()) }), Expires = DateTime.UtcNow.AddDays(7), SigningCredentials = new SigningCredentials(new SymmetricSecurityKey(key), SecurityAlgorithms.HmacSha256Signature) }; var token = tokenHandler.CreateToken(tokenDescriptor); var tokenString = tokenHandler.WriteToken(token); return(Ok(new { Id = user.Id, Username = user.UserName, FirstName = user.FirstName, LastName = user.LastName, Token = tokenString })); }
public async Task WhenUserTryToDeleteUnexistingFile_ThenCorrespondingStatusIsReturned(string username, string password, HttpStatusCode statusCode) { //Arrange Login var authCommand = new AuthenticateUserCommand() { Username = username, Password = password }; //Act Login var userModel = await client.PostAsJsonAsync <UserModel>($"api/authentication/login", authCommand); //Assert Login Assert.NotNull(userModel); Assert.NotEmpty(userModel.Token); //Arrange Delete file var authorizationHeader = new Dictionary <string, string>() { { "Authorization", $"Bearer {userModel.Token}" }, }; var missingFileId = 0; //Act Delete File var deleteFileResponse = await client.DeleteAsync($"api/File/{missingFileId}", authorizationHeader); //Assert Delete File Assert.Equal(statusCode, deleteFileResponse.StatusCode); }
public async Task <AuthenticateUserResult> AuthenticateUserAsync(UserAuthentication userAuthentication) { var command = new AuthenticateUserCommand(userAuthentication); var handler = _commands.Build(command); return(await handler.ExecuteAsync()); }
public async Task <IActionResult> Create([FromBody] AuthenticateUserRequest user) { var command = new AuthenticateUserCommand(user); var result = await Mediator.Send(command); return(await ResponseBase(result)); }
protected async Task <string> GetEncodedJwtAsync(AuthenticateUserCommand command, ClaimsIdentity identity) { if (identity == null) { return(string.Empty); } var claims = new[] { new Claim(JwtRegisteredClaimNames.UniqueName, command.Email), new Claim(JwtRegisteredClaimNames.NameId, command.Email), new Claim(JwtRegisteredClaimNames.Email, command.Email), new Claim(JwtRegisteredClaimNames.Sub, command.Email), new Claim(JwtRegisteredClaimNames.Jti, await _tokenOptions.JtiGenerator()), new Claim(JwtRegisteredClaimNames.Iat, ToUnixEpochDate(_tokenOptions.IssuedAt).ToString(), ClaimValueTypes.Integer64), identity.FindFirst("AnyGym"), identity.FindFirst("UserId") }; var jwt = new JwtSecurityToken( issuer: _tokenOptions.Issuer, audience: _tokenOptions.Audience, claims: claims.AsEnumerable(), notBefore: _tokenOptions.NotBefore, expires: _tokenOptions.Expiration, signingCredentials: _tokenOptions.SigningCredentials); var encodedJwt = new JwtSecurityTokenHandler().WriteToken(jwt); return(encodedJwt); }
public void AunthenticateUserTest() { string authToken = @"eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJpc3MiOiJ0b3B0YWwuY29tIiwiZXhwIjoxNDI2NDIwODAwL CJodHRwOi8vdG9wdGFsLmNvbS9qd3RfY2xhaW1zL2lzX2FkbWluIjp0cnVlLCJjb21wYW55IjoiVG9wdGFsIiwiYXdlc29tZSI6dHJ1ZX0 .yRQYnWzskCZUxPwaQupWkiUzKELZ49eM7oWxAQK_ZXw"; UserAuthResult userAuthResult = new UserAuthResult() { AuthToken = authToken, UserId = 1 }; var mediator = new Mock <IMediator>(); AuthenticateUserCommand command = new AuthenticateUserCommand { Name = "Admin", Password = "******" }; mediator.Setup(e => e.Send(command, new System.Threading.CancellationToken())).Returns(Task.FromResult(userAuthResult)); UserController controller = new UserController(mediator.Object); var result = controller.Authenticate(command); var response = result.Result as OkObjectResult; Assert.AreEqual(1, ((UserAuthResult)response.Value).UserId); Assert.AreEqual(authToken, ((UserAuthResult)response.Value).AuthToken); }
public AccountController(GetUsersQuery getUsersQuery, ChangeDepartmentCommand changeDepartmentCommand, ChangePasswordCommand changePasswordCommand, AuthenticateUserCommand authenticateUserCommand, TaskExecutor.TaskExecutor taskExecutor) { this.authenticateUserCommand = authenticateUserCommand; this.changePasswordCommand = changePasswordCommand; this.changeDepartmentCommand = changeDepartmentCommand; this.getUsersQuery = getUsersQuery; this.taskExecutor = taskExecutor; }
public async Task <IActionResult> Login([FromBody] AuthenticateUserCommand authenticateUser) { var userModel = await mediator.Send(authenticateUser); userModel.Token = await mediator.Send(new GenerateTokenCommand(userModel.Id, userModel.Username, userModel.Role)); return(Ok(userModel)); }
public void RegistrationPass() { AuthenticateUserCommand command = new AuthenticateUserCommand("Marcos", "hola"); handler.Trigger(command); Assert.True(true); }
public AuthenticateUserCommandContract(AuthenticateUserCommand command) { Contract = new ValidationContract() .Requires() .IsNotNullOrEmpty(command.CPF, "Username", "O campo UserName é obrigatório") .IsNotNullOrEmpty(command.Senha, "Password", "O campo Password é obrigatório") .HasMinLen(command.Senha, 6, "Password", "O campo Password precisa ter no mínimo 6 caracteres"); }
public void Validate_GivenAllPropertiesAreValid_ExpectValidationSuccess() { var cmd = new AuthenticateUserCommand("*****@*****.**", "password"); var validator = new AuthenticateUserCommandValidator(); var result = validator.Validate(cmd); Assert.True(result.IsValid); }
public void ErrorAuthenticateUserPassword(string password, int errorCode) { var command = new AuthenticateUserCommand(null, password, _appSettings); var commandResult = new UserCommandHandler(_mapper, _userRepo.Object) .Handle(command, new CancellationToken()).Result; Assert.True(commandResult.HasError(errorCode)); }
private static void CompareAuthenticateUserCommand(AuthenticateUserCommand c, AuthenticateUserCommand dc) { Assert.AreEqual(c.Username, dc.Username); Assert.AreEqual(c.Password, dc.Password); }
public void AuthenticateUser(string username, string password) { AuthenticateUserCommand loginCommand = new AuthenticateUserCommand(username, password); loginCommand.SuccessActions.Add(args => UserLoggedIn(args)); loginCommand.Execute(); }