// ReSharper disable once InconsistentNaming public void Middleware_can_not_sucessfully_update_a_users_account_based_on_invalid_password_confirmations() { using (new HttpClient()) { // Arrange var loggedInUserValid = _userMgr.FindAsync(_login.UserName, _login.Password).Result; var acctCtrl = new AccountController(_userMgr); // Assumes valid loggedInUser. IList<Claim> claimsCollection = new List<Claim> { new Claim(ClaimTypes.Name, loggedInUserValid.UserName), new Claim(ClaimTypes.NameIdentifier, loggedInUserValid.Id), new Claim(ClaimTypes.PostalCode, "94065"), new Claim(ClaimTypes.StateOrProvince, "California") }; // Associate claims with Identity var claimsIdentity = new ClaimsIdentity(claimsCollection, "PIMS web site"); // Associate Identity with Principal var claimsPrincipal = new ClaimsPrincipal(claimsIdentity); Thread.CurrentPrincipal = claimsPrincipal; // Setup: RequestContext-RequestMessage-HttpConfiguration var requestCtx = new Mock<HttpRequestContext>(); requestCtx.SetupGet(s => s.Principal).Returns(claimsPrincipal); var config = new HttpConfiguration(); var route = config.Routes.MapHttpRoute( name: "ManageRoute", routeTemplate: "api/{controller}/ManageAsync", defaults: new { } ); var routeData = new HttpRouteData(route, new HttpRouteValueDictionary { { "controller", "Account" } }); var requestMsg = new HttpRequestMessage(HttpMethod.Post, "http://localhost/Pims.Web.Api/api/Account/ManageAsync"); requestMsg.Properties[HttpPropertyKeys.HttpConfigurationKey] = config; requestMsg.Properties[HttpPropertyKeys.HttpRouteDataKey] = new HttpRouteData(new HttpRoute()); acctCtrl.ControllerContext = new HttpControllerContext(config, routeData, requestMsg); acctCtrl.Request = requestMsg; acctCtrl.Request.Properties[HttpPropertyKeys.HttpConfigurationKey] = config; acctCtrl.ControllerContext.RequestContext.Principal = claimsPrincipal; // Change to invalid confirmation passwords. var userEdits = new ManageUserModel { OldPassword = _login.Password, NewPassword = "******", ConfirmPassword = "******" }; // Act var actionResult = acctCtrl.ManageAsync(userEdits).Result; var loggedInUserUnModified = _userMgr.FindAsync(_login.UserName, userEdits.OldPassword).Result; // Create response message. var responseMsg = actionResult.ExecuteAsync(new CancellationToken(false)); // Assert Assert.IsTrue(responseMsg.Result.StatusCode == HttpStatusCode.BadRequest); Assert.IsNotNullOrEmpty(loggedInUserUnModified.Id); } }
// ReSharper disable once InconsistentNaming public void Middleware_can_sucessfully_update_a_users_password_upon_request() { #region - Unsuccessful tests/code via Moq for UserManager. Defer ? //var userMgrMock = new Mock<UserManager<ApplicationUser>>( // new UserStore<ApplicationUser>(NHibernateConfiguration.CreateSessionFactory(ConnString).OpenSession())); //userMgrMock.Setup(x => x.ChangePasswordAsync(loggedInUser.Id, _login.Password, "pwrd0827b")) // .ReturnsAsync(new IdentityResult()); //var userStoreMock = new Mock<UserStore<ApplicationUser>>(NHibernateConfiguration.CreateSessionFactory(ConnString).OpenSession()); //var userMgr2Mock = new Mock<UserManager<ApplicationUser>>(userStoreMock.Object); //userMgr2Mock.Setup(x => x.ChangePasswordAsync(It.IsAny<string>(), It.IsAny<string>(), It.IsAny<string>())) // .ReturnsAsync(new IdentityResult()); // returns: IdentityResult.Succeeded = false - 8/27/14; 8/28 - definitely a Moq setup issue! //userMgrMock.Setup(x => x.ChangePasswordAsync(It.IsAny<string>(), It.IsAny<string>(), It.IsAny<string>())) // .ReturnsAsync(new IdentityResult()); //var acctCtrl = new AccountController(userMgrMock.Object); //no //var acctCtrl = new AccountController(userMgr2Mock.Object); //var identity = new GenericIdentity(loggedInUser.UserName); //var claimsIdentity = new ClaimsIdentity(); //identity.AddClaim(new Claim("http://schemas.xmlsoap.org/ws/2005/05/identity/claims/nameidentifier", loggedInUser.Id)); //identity.AddClaims(claimsCollection); //var principal = new GenericPrincipal(identity, new[] {"user"}); //requestCtx.SetupGet(s => s.Principal).Returns(principal); //requestMsg.SetRequestContext(requestCtx.Object); //var descriptor = new HttpControllerDescriptor(); //var controller = new Mock<IHttpController>(); //acctCtrl.ControllerContext.RequestContext.Principal = principal; //acctCtrl.ControllerContext = new HttpControllerContext(requestCtx.Object, requestMsg, descriptor, controller.Object ); //var testCall = client.PostAsJsonAsync("http://localhost/Pims.Web.Api/api/Account/ManageAsync", editedPassword).Result; // Mimic user login. // Validate currently logged in User and their existence in ASP.NET Identity. //var loggedInUser2 = _userMgr.FindAsync(_login.UserName, _login.Password).Result; // mimic SignInAsync() //var authenticationManager = HttpContext.Current.GetOwinContext().Authentication; //authenticationManager.SignOut(DefaultAuthenticationTypes.ExternalCookie); //var claimsIdentity = await _userMgr.CreateIdentityAsync(loggedInUser, DefaultAuthenticationTypes.ApplicationCookie); //authenticationManager.SignIn(new AuthenticationProperties { IsPersistent = true }, claimsIdentity); //// Identity created with added claim. //var identity = new GenericIdentity(loggedInUser.UserName); //identity.AddClaim(new Claim("http://schemas.xmlsoap.org/ws/2005/05/identity/claims/nameidentifier", loggedUserId)); //// Principal created with associated Identity. //var principal = new GenericPrincipal(identity, new[] {"user"}); //var urlHelper = new Mock<UrlHelper>(); //urlHelper.Setup(s => s.Link(It.IsAny<string>(), It.IsAny<object>())) // .Returns("http://localhost/PIMS.Web.Api/api/Account"); //// HttpRequestContext created //var requestCtx = new Mock<HttpRequestContext>(); //requestCtx.Setup(s => s.Url).Returns(urlHelper.Object); //requestCtx.SetupGet(s => s.Principal).Returns(principal); //// Set HttpRequestMessage on HttpRequestContext via HttpConfiguration object. //var config = new HttpConfiguration(); //config.Routes.MapHttpRoute( // name: "ManageRoute", // routeTemplate: "api/Account/ManageAsync" // ); //var requestMsg = TestHelpers.GetHttpRequestMessage( // HttpMethod.Post, // UrlBase + "/ManageAsync", // new AccountController(_userMgr), // "ManageRoute", // "api/Account/ManageAsync", // new { } // ); //// Set required objects for HttpControllerContext. //requestMsg.SetRequestContext(requestCtx.Object); //var descriptor = new HttpControllerDescriptor(); //var controller = new Mock<IHttpController>(); //var accountCtrl = new AccountController(_userMgr) // { // ControllerContext = new HttpControllerContext // ( // requestCtx.Object, // requestMsg, // descriptor, // controller.Object // ) // }; //client.DefaultRequestHeaders.Add("UserId", loggedInUser.Id); //client.BaseAddress = new Uri(UrlBase); //client.DefaultRequestHeaders.Accept.Clear(); //client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json")); //var settings = new JsonSerializerSettings(); //var serializer = JsonSerializer.Create(settings); //var editedPassword = new ManageUserModel // { // OldPassword = _login.Password, // NewPassword = "******", // ConfirmPassword = "******" // //UserId = loggedUserId // }; //var j = JObject.FromObject(editedData, serializer); //HttpContent content = new StringContent(j.ToString()); //content.Headers.ContentType = new MediaTypeHeaderValue("application/json"); //var contentData = content.ReadAsStringAsync(); // Act //var claimsIdentityFactory = new PimsClaimsIdentityFactory(); //var claimsIdentity = claimsIdentityFactory.CreateClaimsIdentity(_login); //IList<Claim> claimsCollection = new List<Claim> // { // new Claim(ClaimTypes.Name, "Richard"), // new Claim(ClaimTypes.PostalCode, "94065"), // new Claim(ClaimTypes.MobilePhone, "650.465.3609"), // new Claim(ClaimTypes.Locality, "Redwood Shores") // }; //NHibernate.AspNet.Identity.IdentityUserClaim nhClaim = new IdentityUserClaim(); //var claimsIdentity = new ClaimsIdentity(claimsCollection, "PIMS test authType"); //claimsIdentity.AddClaims(claimsCollection); //var claimsPrincipal = new ClaimsPrincipal(claimsIdentity); #endregion using (new HttpClient()) { // Arrange var loggedInUser = _userMgr.FindAsync(_login.UserName, _login.Password).Result; var acctCtrl = new AccountController(_userMgr); // Assumes valid loggedInUser. IList<Claim> claimsCollection = new List<Claim> { new Claim(ClaimTypes.Name, loggedInUser.UserName), new Claim(ClaimTypes.NameIdentifier, loggedInUser.Id), new Claim(ClaimTypes.PostalCode, "94065"), new Claim(ClaimTypes.StateOrProvince, "California") }; // Associate claims with Identity var claimsIdentity = new ClaimsIdentity(claimsCollection, "PIMS web site"); // Associate Identity with Principal var claimsPrincipal = new ClaimsPrincipal(claimsIdentity); Thread.CurrentPrincipal = claimsPrincipal; // Setup: RequestContext-RequestMessage-HttpConfiguration var requestCtx = new Mock<HttpRequestContext>(); requestCtx.SetupGet(s => s.Principal).Returns(claimsPrincipal); var config = new HttpConfiguration(); var route = config.Routes.MapHttpRoute( name: "ManageRoute", routeTemplate: "api/{controller}/ManageAsync", defaults: new {} ); var routeData = new HttpRouteData(route, new HttpRouteValueDictionary {{"controller", "Account"}}); var requestMsg = new HttpRequestMessage(HttpMethod.Post, "http://localhost/Pims.Web.Api/api/Account/ManageAsync"); requestMsg.Properties[HttpPropertyKeys.HttpConfigurationKey] = config; requestMsg.Properties[HttpPropertyKeys.HttpRouteDataKey] = new HttpRouteData(new HttpRoute()); acctCtrl.ControllerContext = new HttpControllerContext(config, routeData, requestMsg); acctCtrl.Request = requestMsg; acctCtrl.Request.Properties[HttpPropertyKeys.HttpConfigurationKey] = config; acctCtrl.ControllerContext.RequestContext.Principal = claimsPrincipal; var userEdits = new ManageUserModel { OldPassword = _login.Password, NewPassword = "******", ConfirmPassword = "******" }; // Act // Confirm userEdits & _login passwords are configured correctly. var actionResult = acctCtrl.ManageAsync(userEdits).Result; var loggedInUserModified = _userMgr.FindAsync(_login.UserName, userEdits.NewPassword).Result; // Create response message. var responseMsg = actionResult.ExecuteAsync(new CancellationToken(false)); // Assert Assert.AreEqual(responseMsg.Result.StatusCode, HttpStatusCode.OK); Assert.IsNotNullOrEmpty(loggedInUserModified.UserName); } }