public AuthenticateUserResponse AuthenticateUser(AuthenticateUserRequest request) { try { var response = new AuthenticateUserResponse(); if (string.IsNullOrEmpty(request.UserName) || string.IsNullOrEmpty(request.Password)) { response.Success = false; response.FailureInformation = "Invalid username or password."; return(response); } response.Id = Guid.NewGuid(); response.Email = "*****@*****.**"; response.Firstname = "Test"; response.Lastname = "User"; // pass-through success and set Auth cookie in controller override response.Success = true; return(response); } catch (Exception ex) { return(ServiceHelper.GetPopulatedFailureResponse <AuthenticateUserResponse>(ex)); } }
public void TestAuthenticateFailToVerifyPasswordHash() { User user = new User(); mockUserRepository.Setup(u => u.GetByEmailAddress(It.IsAny <string>())) .Returns(user); mockAuthenticationHelper.Setup(a => a.VerifyPasswordHash(It.IsAny <string>(), It.IsAny <byte[]>(), It.IsAny <byte[]>())) .Returns(false); userService = new UserService(mockUserRepository.Object, mockFoodEntryRepository.Object, mockMapper.Object, mockLogger.Object, mockAuthenticationHelper.Object, mockJwtHelper.Object, mockUserProfileCalculator.Object); string email = "*****@*****.**"; string password = "******"; AuthenticateUserResponse response = userService.Authenticate(email, password); Assert.AreEqual(response.ResponseStatus.Status, ResponseStatusCode.UNAUTHORIZED); Assert.AreEqual(response.ResponseStatus.Message, Constants.AuthenticateUserMessages.InvalidCredentials); }
/// <summary> /// Authorize User To Domains /// </summary> /// <param name="data">AuthenticateUserResponse</param> /// <param name="role">Role</param> /// <param name="returnUrl">Return Url</param> /// <returns>ActionResult</returns> protected virtual ActionResult AuthorizeUserToDomains(AuthenticateUserResponse data, string role, string returnUrl, bool rememberMe = true) { string userData = String.Empty; if (data.IsAuthenticated) { var domainRoles = UsersService.GetDomainRoleForUser(new GetDomainRoleForUserRequest { User = data.User }); userData = FlowTasksIdentity.SetUserData(data.User, new AuthorizeData { Domains = domainRoles.DomainRole.Domanis, Roles = domainRoles.DomainRole.Roles }); } AddAuthCookie(data.User, userData, rememberMe); // PG. Changes for New UI return(Json(true)); // END if (data.IsAuthenticated) { return(RedirectToReturnUrl(returnUrl)); } return(RedirectToAction("Index", "Home")); }
public AuthenticateUserResponse AuthenticateUser(AuthenticateUserRequest request) { try { var response = new AuthenticateUserResponse(); if (string.IsNullOrEmpty(request.UserName) || string.IsNullOrEmpty(request.Password)) { response.SetError("Invalid username or password."); return(response); } response.Id = Guid.NewGuid(); response.Email = "*****@*****.**"; response.Firstname = "Test"; response.Lastname = "User"; // passthrough success and set Auth cooki in controller override response.Success = true; return(response); } catch (Exception ex) { return(new AuthenticateUserResponse { Success = false, FailureInformation = "Generic error in UserService::AuthenticateUser" }); } }
public void TestAuthenticateInvalidPasswordSaltLength() { User user = new User(); mockUserRepository.Setup(u => u.GetByEmailAddress(It.IsAny <string>())) .Returns(user); ArgumentException exception = new ArgumentException(Constants.AuthenticationHelperExceptions.InvalidPasswordSaltLength); mockAuthenticationHelper.Setup(a => a.VerifyPasswordHash(It.IsAny <string>(), It.IsAny <byte[]>(), It.IsAny <byte[]>())) .Throws(exception); userService = new UserService(mockUserRepository.Object, mockFoodEntryRepository.Object, mockMapper.Object, mockLogger.Object, mockAuthenticationHelper.Object, mockJwtHelper.Object, mockUserProfileCalculator.Object); string email = "*****@*****.**"; string password = "******"; AuthenticateUserResponse response = userService.Authenticate(email, password); Assert.AreEqual(response.ResponseStatus.Status, ResponseStatusCode.INTERNAL_SERVER_ERROR); Assert.IsTrue(response.ResponseStatus.Message.Contains(exception.Message)); }
protected void LogIn(object sender, EventArgs e) { using (ServiceReference1.Service1Client client = new Consumer.ServiceReference1.Service1Client()) { AuthenticateUserResponse response = client.AuthenticateUser(new AuthenticateUserRequest() { Username = Email.Text, Password = Password.Text }); if (response.Errored) { FailureText.Text = "Username or password incorrect"; } else { if (response.Authenticated) { Session["User"] = response.Person; Person pson = (Person)Session["User"]; FormsAuthentication.RedirectFromLoginPage(pson.Username, RememberMe.Checked); } else { FailureText.Text = "can't authenticate"; } } } }
public AuthenticateUserResponse IsAuthenticated() { AuthenticateUserInput userTry = new AuthenticateUserInput() { Username = Username, Password = Password, DeviceName = "Apple", Station = "123", Version = "1" }; var authResponse = new AuthenticateUserResponse(); try { if (Mvx.Resolve <IValidation>().ObjectIsNotNull(userTry)) { authResponse = Mvx.Resolve <IRestService>().AuthenticateUser(userTry); } } catch (Exception) { Mvx.Resolve <IUserDialogs>().Toast("An error occurred!", null); //logger.Log(LogLevel.Info,e.ToString); } return(authResponse); }
public bool AuthenticateUser(string userName, string password) { AuthenticateUserRequest request = new AuthenticateUserRequest(userName, password); AuthenticateUserResponse response = this.AuthenticateUser(request); return(response.AuthenticateUserResult); }
public async Task <AuthenticateUserResponse> AuthenticateUser(AuthenticateUserRequest request) { var response = new AuthenticateUserResponse(); try { var command = this.userSqlCommandFactory.AuthenticateUser(request); var result = await this.dataAccess.ExecuteReader(command); if (result.DataTable.Rows.Count == 1) { response.Message = "Successfully authenticated user."; response.Success = true; response.Data = new UserAuthenticationModel(); response.Data.User = BuildUserFromDataRow(result.DataTable.Rows[0]); } else { response.Message = "Incorrect authentication details."; response.Success = false; } } catch (Exception ex) { response.Errors.Add(ex.Message); response.Message = "Failed to authenticate user."; } return(response); }
public void TestAuthenticateInvalidCredentials() { string email = ""; string password = "******"; AuthenticateUserResponse response = userService.Authenticate(email, password); Assert.AreEqual(response.ResponseStatus.Status, ResponseStatusCode.BAD_REQUEST); Assert.AreEqual(response.ResponseStatus.Message, Constants.AuthenticateUserMessages.InvalidCredentials); email = null; response = userService.Authenticate(email, password); Assert.AreEqual(response.ResponseStatus.Status, ResponseStatusCode.BAD_REQUEST); Assert.AreEqual(response.ResponseStatus.Message, Constants.AuthenticateUserMessages.InvalidCredentials); email = "*****@*****.**"; password = ""; response = userService.Authenticate(email, password); Assert.AreEqual(response.ResponseStatus.Status, ResponseStatusCode.BAD_REQUEST); Assert.AreEqual(response.ResponseStatus.Message, Constants.AuthenticateUserMessages.InvalidCredentials); password = null; response = userService.Authenticate(email, password); Assert.AreEqual(response.ResponseStatus.Status, ResponseStatusCode.BAD_REQUEST); Assert.AreEqual(response.ResponseStatus.Message, Constants.AuthenticateUserMessages.InvalidCredentials); }
protected void LogIn(object sender, EventArgs e) { if (IsValid) { using (ServiceReference1.Service1Client client = new ServiceReference1.Service1Client()) { AuthenticateUserResponse response = client.AuthenticateUser(new AuthenticateUserRequest() { Username = Email.Text, Password = Password.Text }); // see doc if (response.Errored) { ErreurMessage.Text = "Username or password incorrect"; } if (response.Authenticated) { if (response.Person.IsAdmin && response.Person.IsApproved) { Session["User"] = response.Person; Person pson = (Person)Session["User"]; FormsAuthentication.RedirectFromLoginPage(response.Person.Username, RememberMe.Checked); } else { FailureText.Text = "You don't have permission to access this page"; ErrorMessage.Visible = true; } } } } }
public AuthenticateUserResponse AuthenticateUser(AuthenticateUserInput input) { //logger.Trace("Service : IRestService, Method : AuthenticateUser , Request : AuthenticateUserInput = {"Username" : input.username,"Password" : input.Password, "DeviceName" : "Apple", "Station" : "123", "Version" : "1" };") AuthenticateUserResponse loginResponse = new AuthenticateUserResponse(); if (input.Username == "admin" && input.Password == "password") { loginResponse = new AuthenticateUserResponse() { ReturnCode = "1", Name = "Admin User", Message = "Successfully Login", AppAccess = "Pier,Arrival,Departure,Claim,BSO" }; } else { loginResponse = new AuthenticateUserResponse() { ReturnCode = "0", Name = "XamarinRFID", Message = "Failed Login", AppAccess = null }; } //logger.Trace("Service : IRestService , Method : AuthenticateUser , Response : AuthenticateUserResponse = {"Name" : loginResponse.Name , "AppAccess" : loginResponse.AppAccess, "ReturnCode" : loginResponse.ReturnCode,"Message" : loginResponse.Message}; return(loginResponse); }
public override string Authenticate(string dn, string user, string password) { log.Debug("Token request from user: "******""; AuthenticateUserReq aur = new AuthenticateUserReq(); aur.ItemElementName = ItemChoiceType42.password; aur.Item = password; aur.userid = user; AuthenticateUserResponse aures = _aas.doAuthenticateUser(aur); if ([email protected]) { if (userCanMonitoring(dn, user)) { token = GenerateToken(dn); } else { throw new AuthenticationMismatchException(); } } else { throw new AuthenticationFailedException(); } return(token); }
public static string AuthenticateUser(LoginViewModel model) { try { using (_certonaService = new CertonaServiceClient()) { try { var user = new UserDTO { UserID = model.UserName, Password = Encryption.GetMd5Sum(model.Password) }; var request = new AuthenticateUserRequest { User = user }; AuthenticateUserResponse response = _certonaService.AuthenticateUser(request); if (!response.Success) { return(Utilities.ParseServiceErrors(response.Errors)); } if (response.User == null || response.User.UserID == null) { return("Invalid user account."); } var userDetailsRequest = new GetUserAccountApplicationFeaturesRequest { User = response.User }; var userDetailsResponse = _certonaService.GetUserAccountApplicationFeatures(userDetailsRequest); if (userDetailsResponse.Success) { response.User.Accounts = userDetailsResponse.Accounts; } FormsAuth.SetAuthCookie(response.User, false); ReportingStartDate = DateTime.Now.AddDays(-30); ReportingEndDate = DateTime.Now; } catch (TimeoutException exception) { _certonaService.Abort(); throw; } catch (CommunicationException exception) { _certonaService.Abort(); throw; } } } catch (Exception ex) { } return(""); }
public AuthenticateUserResponse AuthenticateUser(string userName, string password) { bool isValidUser = false; string encodedString = String.Empty; AuthenticateUserResponse response = null; if ((!(string.IsNullOrWhiteSpace(userName)) && !(string.IsNullOrWhiteSpace(password)))) { string salt = GetSaltForGivenUser(userName); string hashedPassword = CreateHashedPassword(Encoding.UTF8.GetBytes(password + salt)); isValidUser = UserAccess.ValidateUser(userName, hashedPassword); } if (isValidUser) { HMACSHA256 hmac = new HMACSHA256(); hmac.Key = Encoding.UTF8.GetBytes(key); byte[] secretKey = hmac.Key; JwtSecurityTokenHandler tokenHandler = new JwtSecurityTokenHandler(); SecurityTokenDescriptor descriptor = new SecurityTokenDescriptor(); JwtSecurityToken token = tokenHandler.CreateJwtSecurityToken(new Microsoft.IdentityModel.Tokens.SecurityTokenDescriptor() { Subject = new ClaimsIdentity (new[] { new System.Security.Claims.Claim(System.Security.Claims.ClaimTypes.Name, userName) } ), Issuer = "http://localhost:53596", Expires = DateTime.Now.AddMinutes(30), NotBefore = DateTime.Now, IssuedAt = DateTime.Now, SigningCredentials = new Microsoft.IdentityModel.Tokens.SigningCredentials (new Microsoft.IdentityModel.Tokens.SymmetricSecurityKey(secretKey), SecurityAlgorithms.HmacSha256Signature) }); encodedString = tokenHandler.WriteToken(token); response = new AuthenticateUserResponse() { IsUserAuthenticated = true, AuthenticationToken = encodedString }; } else { response = new AuthenticateUserResponse() { IsUserAuthenticated = false, AuthenticationToken = string.Empty }; } return(response); }
private async Task <bool> AuthenticatePassword(LoginCredentials loginCredentials, CancellationToken token) { if (_authenticateUserResponse == null) { _authenticateUserResponse = await _userAuthenticationService.AuthenticateUser(loginCredentials.EmailAddress, loginCredentials.Password); } return(_authenticateUserResponse.PasswordValid); }
public object Authenticate( [FromBody] AuthenticateUserRequest request, [FromServices] SigningConfigurations signingConfigurations, [FromServices] TokenConfigurations tokenConfigurations) { bool credenciaisValidas = false; AuthenticateUserResponse response = _serviceUser.AuthenticateUser(request); credenciaisValidas = response != null; if (credenciaisValidas) { ClaimsIdentity identity = new ClaimsIdentity( new GenericIdentity(response.Id.ToString(), "Id"), new[] { new Claim(JwtRegisteredClaimNames.Jti, Guid.NewGuid().ToString("N")), //new Claim(JwtRegisteredClaimNames.UniqueName, response.Usuario) new Claim("User", JsonConvert.SerializeObject(response)) } ); DateTime dataCriacao = DateTime.Now; DateTime dataExpiracao = dataCriacao + TimeSpan.FromSeconds(tokenConfigurations.Seconds); var handler = new JwtSecurityTokenHandler(); var securityToken = handler.CreateToken(new SecurityTokenDescriptor { Issuer = tokenConfigurations.Issuer, Audience = tokenConfigurations.Audience, SigningCredentials = signingConfigurations.SigningCredentials, Subject = identity, NotBefore = dataCriacao, Expires = dataExpiracao }); var token = handler.WriteToken(securityToken); return(new { authenticated = true, created = dataCriacao.ToString("yyyy-MM-dd HH:mm:ss"), expiration = dataExpiracao.ToString("yyyy-MM-dd HH:mm:ss"), accessToken = token, message = "OK", FirstName = response.FirstName }); } else { return(new { authenticated = false, _serviceUser.Notifications }); } }
private AuthenticateUserResponse GetUser() { var user = new AuthenticateUserResponse { Id = 1, FirstName = "John", LastName = "Smith" }; return(user); }
public async Task GivenEmailAddressIsNotAllowed_ItReturnsUnauthorised( string invalidEmail) { SetEmailWhitelist($"mark-as-invalid-{invalidEmail}"); AuthenticateUserRequest request = CreateUseCaseRequestForEmail(invalidEmail); AuthenticateUserResponse response = await _classUnderTest.ExecuteAsync(request, CancellationToken.None); response.Authorised.Should().BeFalse(); }
GivenEmailAddressIsAllowed_WithMultipleEmailsInTheWhitelist_ItReturnsAuthorised(string validEmail) { SetEmailWhitelist($"[email protected];{validEmail};[email protected]"); AuthenticateUserRequest request = CreateUseCaseRequestForEmail(validEmail); StubTokenCreator(validEmail, "stub"); AuthenticateUserResponse response = await _classUnderTest.ExecuteAsync(request, CancellationToken.None); response.Authorised.Should().BeTrue(); }
public async Task GivenEmailAddress_WhenCreatingAuthenticationToken_ItAddsEmailAddress(string validEmail) { SetEmailWhitelist($"[email protected];{validEmail.ToUpper()};[email protected]"); AuthenticateUserRequest request = CreateUseCaseRequestForEmail(validEmail); StubTokenCreator(validEmail, "stub"); AuthenticateUserResponse response = await _classUnderTest.ExecuteAsync(request, CancellationToken.None); response.Authorised.Should().BeTrue(); }
public void TimeoutTest_WithCredentialsData() { #region Valid user with user details #region Setup Test Data var controller = new SessionController(); LoginViewModel model = new LoginViewModel { Account = "ValidAccountID", UserName = "******", Password = "******" }; UserDTO user = new UserDTO() { Email = "*****@*****.**", Name = "Test", UserID = "TestUserID" }; var response = new AuthenticateUserResponse() { Success = true, User = user }; Mock <ICertonaService> applicationMock = new Mock <ICertonaService>(); controller.ForesightService = applicationMock.Object; applicationMock.Setup(p => p.AuthenticateUser(It.IsAny <AuthenticateUserRequest>())).Returns(response); Mock <IFormsAuthentication> formsAuthenticationMock = new Mock <IFormsAuthentication>(); controller.FormsAuth = formsAuthenticationMock.Object; formsAuthenticationMock.Setup(p => p.SetAuthCookie(It.IsAny <string>(), It.IsAny <CertonaCredential>(), It.IsAny <bool>())); #endregion #region Execute Test var result = controller.Timeout("ValidAccountID", "ValidUserName", "ValidPassword"); #endregion #region Evaluate Results Assert.IsTrue(controller.ModelState.IsValid, "ModelState must be valid for valid credentials"); // It should redirect to home page JsonResult jsonResult = (JsonResult)result; Assert.IsInstanceOfType(result, typeof(JsonResult), "Should return json result"); Assert.AreEqual("Success", jsonResult.Data, "Default Login with authenticated user set should return success data"); #endregion #endregion }
public async Task <IActionResult> Authenticate( [HttpTrigger( AuthorizationLevel.Anonymous, "post", Route = "user/authenticate")] [RequestBodyType(typeof(AuthenticateUserRequest), "Authenticate User Request")] HttpRequest req, ILogger log) { if (req.ContentLength <= 0) { return(HttpCodeHelper.EmptyRequestBody()); } string requestBody; using (StreamReader readStream = new StreamReader(req.Body)) { requestBody = await readStream.ReadToEndAsync(); } RegisterUserRequest payload; try { payload = JsonConvert.DeserializeObject <RegisterUserRequest>(requestBody); } catch (Exception e) { return(HttpCodeHelper.Return400(e.Message)); } User user; try { user = _userService.Authenticate(payload.Email, payload.Password); } catch (JournallyException ex) { return(HttpCodeHelper.Return400(ex.Message)); } var tokenString = _tokenService.GenerateToken(user); var response = new AuthenticateUserResponse { Email = user.Email, Token = tokenString }; return(new OkObjectResult(response)); }
public static AuthenticateUserWebResponse ToWebResponse(this AuthenticateUserResponse response) { var webResponse = new AuthenticateUserWebResponse() { Success = response.Success, Errors = response.Errors, Message = response.Message, Data = response.Data }; return(webResponse); }
private AuthenticateUserResponse AuthenticateUser(AuthenticateUserRequest request) { CFInvokeInfo info = new CFInvokeInfo(); info.Action = "http://tempuri.org/IStockService/AuthenticateUser"; info.RequestIsWrapped = true; info.ReplyAction = "http://tempuri.org/IStockService/AuthenticateUserResponse"; info.ResponseIsWrapped = true; AuthenticateUserResponse retVal = base.Invoke <AuthenticateUserRequest, AuthenticateUserResponse>(info, request); return(retVal); }
public void TimeoutTest_WithInvalidCredentialsData() { #region Invalid user with user details #region Setup Test Data var controller = new SessionController(); LoginViewModel model = new LoginViewModel { Account = "InValidAccountID", UserName = "******", Password = "******" }; ErrorResult[] errors = new ErrorResult[] { new ErrorResult { Description = "Invalid credentials" } }; var response = new AuthenticateUserResponse() { Success = false, Errors = errors }; Mock <ICertonaService> authenticationMock = new Mock <ICertonaService>(); controller.ForesightService = authenticationMock.Object; authenticationMock.Setup(p => p.AuthenticateUser(It.IsAny <AuthenticateUserRequest>())).Returns(response); Mock <IFormsAuthentication> formsAuthenticationMock = new Mock <IFormsAuthentication>(); controller.FormsAuth = formsAuthenticationMock.Object; formsAuthenticationMock.Setup(p => p.SetAuthCookie(It.IsAny <string>(), It.IsAny <CertonaCredential>(), It.IsAny <bool>())); #endregion #region Execute Test var result = controller.Timeout("InValidAccountID", "InValidUserName", "InValidPassword"); #endregion #region Evaluate Results Assert.IsFalse(controller.ModelState.IsValid, "ModelState must be invalid for invalid credentials"); JsonResult jsonResult = (JsonResult)result; Assert.IsInstanceOfType(result, typeof(JsonResult), "Should return json result"); Assert.AreEqual("Invalid credentials\r\n", jsonResult.Data, "Invalid credentials should return error message 'Invalid credentials' "); #endregion #endregion }
public IActionResult Authenticate([FromBody] AuthenticateModel authenticateModel) { AuthenticateUserResponse response = _userService.Authenticate(authenticateModel.EmailAddress, authenticateModel.Password); if (!response.ResponseStatus.HasError()) { return(Ok(new { User = response.UserDto, response.Token })); } return(StatusCode(response.ResponseStatus.Status, response.ResponseStatus.Message)); }
public IHttpActionResult AuthenticateUser([FromBody] AuthenticateUserRequest request) { AuthenticateUserResponse response = null; response = _iUserOperations.AuthenticateUser(request.Username, request.Password); if (response.IsUserAuthenticated) { return(Ok(response)); } else { return(Ok(response)); } }
public async Task <IActionResult> List() { try { string userClaims = _httpContextAccessor.HttpContext.User.FindFirst("User").Value; AuthenticateUserResponse userResponse = JsonConvert.DeserializeObject <AuthenticateUserResponse>(userClaims); var response = _servicePlayList.List(userResponse.Id); return(await ResponseAsync(response, _servicePlayList)); } catch (Exception ex) { return(await ResponseExceptionAsync(ex)); } }
public override async Task GrantResourceOwnerCredentials(OAuthGrantResourceOwnerCredentialsContext context) { try { IServiceUser serviceUser = _container.Resolve <IServiceUser>(); AuthenticateUserRequest request = new AuthenticateUserRequest(); request.Email = context.UserName; request.Senha = context.Password; AuthenticateUserResponse response = serviceUser.AuthenticateUser(request); if (serviceUser.IsInvalid()) { if (response == null) { context.SetError("invalid_grant", "Preencha um e-mail válido e uma senha com pelo menos 6 caracteres."); return; } } serviceUser.ClearNotifications(); if (response == null) { context.SetError("invalid_grant", "Usuário não encontrado!"); return; } var identity = new ClaimsIdentity(context.Options.AuthenticationType); //Definindo as Claims identity.AddClaim(new Claim("User", JsonConvert.SerializeObject(response))); var principal = new GenericPrincipal(identity, new string[] { }); Thread.CurrentPrincipal = principal; context.Validated(identity); } catch (Exception ex) { context.SetError("invalid_grant", ex.Message); return; } }