public static void MockCurrentUser(this Controller controller, string id, string username) { var identity = new GenericIdentity(username); identity.AddClaim(new Claim("http://schemas.xmlsoap.org/ws/2005/05/identity/claims/name", username)); identity.AddClaim(new Claim("http://schemas.xmlsoap.org/ws/2005/05/identity/claims/nameidentifier", id)); var principal = new GenericPrincipal(identity, null); //var mockHttpContext = new Mock<HttpContext>(); //mockHttpContext.SetupGet(c => c.User).Returns(principal); //var mockControllerContext = new Mock<ControllerContext>(); //mockControllerContext.SetupGet(c => c.HttpContext).Returns(mockHttpContext.Object); controller.ControllerContext = Mock.Of <ControllerContext>(ctx => ctx.HttpContext == Mock.Of <HttpContext>(http => http.User == principal)); }
public async void Add_AddIsFalse() { //Mock Claims object var mockIdentity = new GenericIdentity("User"); mockIdentity.AddClaim(new Claim("UserId", "2")); var principal = new GenericPrincipal(mockIdentity, null); //Mock HttpContext var mockHttpContext = new Mock <HttpContext>(); mockHttpContext.Setup(m => m.User).Returns(principal); List <Notification> notifications = new List <Notification> { new Notification { NotificationCatID = 1, NotificationTypeID = 3, DeviceID = 2, UserID = 2 }, new Notification { NotificationCatID = 2, NotificationTypeID = 1, DeviceID = 1, UserID = 2 }, }; var user = new User { ID = 1, Activated = 0, Email = "user@email", Notifications = notifications }; mockUserService.Setup(m => m.Find(It.IsAny <long>(), It.IsAny <Expression <Func <User, object> >[]>())) .Returns(user); var controller = new NotificationController(mapper, mockUserService.Object, mockNotificationService.Object); controller.ControllerContext.HttpContext = mockHttpContext.Object; var result = await controller.Add(false, 2, 1, 3) as JsonResult; Assert.Equal("Done!", result.Value); }
public override void OnAuthorization(HttpActionContext actionContext) { if (actionContext.Request.Headers.Authorization == null) { actionContext.Response = actionContext.Request.CreateResponse(HttpStatusCode.Unauthorized); if (actionContext.Response.StatusCode == HttpStatusCode.Unauthorized) { actionContext.Response.Headers.Add("WWW-Authenticate", string.Format("Basic realm=\"{0}\"", Realm)); } } else { string authenticationToken = actionContext.Request.Headers.Authorization.Parameter; string decodedAuthenticationToken = Encoding.UTF8.GetString(Convert.FromBase64String(authenticationToken)); string[] usernamePasswordArray = decodedAuthenticationToken.Split(':'); string username = usernamePasswordArray[0]; string password = usernamePasswordArray[1]; if (UserValidate.Login(username, password)) { var UserDetails = UserValidate.GetUserDetails(username, password); var identity = new GenericIdentity(username); identity.AddClaim(new Claim("Email", UserDetails.Email)); identity.AddClaim(new Claim(ClaimTypes.Name, UserDetails.UserName)); identity.AddClaim(new Claim("ID", Convert.ToString(UserDetails.ID))); IPrincipal principal = new GenericPrincipal(identity, UserDetails.Roles.Split(',')); Thread.CurrentPrincipal = principal; if (HttpContext.Current != null) { HttpContext.Current.User = principal; } } else { actionContext.Response = actionContext.Request .CreateResponse(HttpStatusCode.Unauthorized); } } }
protected override Task <HttpResponseMessage> SendAsync(HttpRequestMessage request, CancellationToken cancellationToken) { try { var authenticationToken = request.Headers.GetValues("Authorization").FirstOrDefault(); if (authenticationToken != null) { byte[] data = Convert.FromBase64String(authenticationToken); string decodedAuthenticationToken = Encoding.UTF8.GetString(data); string[] UsernamePasswordArray = decodedAuthenticationToken.Split(':'); string username = UsernamePasswordArray[0]; string password = UsernamePasswordArray[1]; DataEntry ObjUser = new ValidateUser().CheckUserCredentials(username, password); if (ObjUser != null) { var identity = new GenericIdentity(ObjUser.user.UserName); identity.AddClaim(new Claim("Email", ObjUser.user.UserEmailID)); IPrincipal principal = new GenericPrincipal(identity, ObjUser.user.UserRoles.Split(',')); Thread.CurrentPrincipal = principal; if (HttpContext.Current != null) { HttpContext.Current.User = principal; } return(base.SendAsync(request, cancellationToken)); } else { var response = new HttpResponseMessage(HttpStatusCode.Unauthorized); var tsc = new TaskCompletionSource <HttpResponseMessage>(); tsc.SetResult(response); return(tsc.Task); } } else { var response = new HttpResponseMessage(HttpStatusCode.BadRequest); var tsc = new TaskCompletionSource <HttpResponseMessage>(); tsc.SetResult(response); return(tsc.Task); } } catch { var response = new HttpResponseMessage(HttpStatusCode.Forbidden); var tsc = new TaskCompletionSource <HttpResponseMessage>(); tsc.SetResult(response); return(tsc.Task); } }
static async Task SignInAsync(HttpContext context) { if (string.Compare(context.Request.Method, "GET") == 0) { context.Response.ContentType = "text/html"; await context.Response.WriteAsync( @"<html><head><title>Login</title></head> <body> <form method='post'> <input type='text' name='username' placeholder='User name' value='' /> <input type='text' name='password' type='password' placeholder='password' value=''/> <input type='submit' value='Sign In' /> </form> </body> <html>"); } else { var username = context.Request.Form["username"]; var password = context.Request.Form["password"]; if (_accounts.TryGetValue(username, out var pwd) && string.Equals(password, pwd)) { var identity = new GenericIdentity(username, CookieAuthenticationDefaults.AuthenticationScheme); if (_userRoles.TryGetValue(username, out var role)) { identity.AddClaim(new Claim(ClaimTypes.Role, role)); } var principal = new ClaimsPrincipal((identity)); await context.SignInAsync(principal); } else { context.Response.ContentType = "text/html"; await context.Response.WriteAsync( @"<html><head><title>Login</title></head> <body> <form method='post'> <input type='text' name='username' placeholder='User name' value='' /> <input type='text' name='password' type='password' placeholder='password' value=''/> <input type='submit' value='Sign In' /> </form> </body> <html>"); } } }
public void Setup() { _apiClient = new Mock <IApiClient>(); _applyApiClient = new Mock <IApplicationApiClient>(); _qnaApiClient = new Mock <IQnaApiClient>(); _httpContextAccessor = new Mock <IHttpContextAccessor>(); _answerService = new Mock <IAnswerService>(); _answerInjectionService = new Mock <IAnswerInjectionService>(); _logger = new Mock <ILogger <ApplicationController> >(); var identity = new GenericIdentity("test user"); identity.AddClaim(new Claim("http://schemas.xmlsoap.org/ws/2005/05/identity/claims/givenname", "JOHN")); identity.AddClaim(new Claim("http://schemas.xmlsoap.org/ws/2005/05/identity/claims/surname", "DUNHILL")); _httpContextAccessor.Setup(a => a.HttpContext.User.Identities) .Returns(new List <ClaimsIdentity>() { identity }); _controller = new ApplicationController(_apiClient.Object, _applyApiClient.Object, _qnaApiClient.Object, _httpContextAccessor.Object, _answerService.Object, _answerInjectionService.Object, _logger.Object); }
public void Should_ApproveEnquiryReply_OnTender() { #region Mock-User var context = new Mock <HttpContext>(); var claim = new Claim("sub", "15445"); var idintity = new GenericIdentity("testUser"); idintity.AddClaim(claim); context.SetupGet(x => x.User.Identity).Returns(() => { return(idintity); }); _httpContextAccessor.SetupGet(x => x.HttpContext).Returns(context.Object); #endregion Mock-User _enquiryQueries.Setup(x => x.GetEnquiryReplyWithTender(It.IsAny <int>())) .Returns(() => { return(Task.FromResult <EnquiryReply>(new EnquiryDefaults().GetEnquiryReplyDataWithTender())); }); List <string> suppliers = new List <string> { "123" }; _iDMAppService.Setup(x => x.GetAllSupplierOnTender(It.IsAny <int>())) .Returns(() => { return(Task.FromResult <List <string> >(suppliers)); }); _enquiryQueries.Setup(x => x.GetEnquiryReplyWithCommunicationRequest(It.IsAny <int>())) .Returns(() => { return(Task.FromResult <EnquiryReply>(new EnquiryDefaults().GetEnquiryReplyDataWithCommunicationRequest())); }); var communicationRequest = new CommunicationRequestDefault().GetGeneralAgencyCommunicationRequest(); _enquiryDomain.Setup(x => x.GetEnquiryCommunicationRequestByRequestId(It.IsAny <int>())) .Returns(() => { return(Task.FromResult <AgencyCommunicationRequest>(communicationRequest)); }); communicationRequest.UpdateAgencyCommunicationRequestStatus((int)Enums.AgencyCommunicationRequestStatus.PendingEnquiryForReply); var result = _sut.ApproveEnquiryReply(1); Assert.NotNull(result); _enquiryCommands.Verify(x => x.UpdateReplyAsync(It.IsAny <EnquiryReply>()), Times.Once); }
public void ReturnDefaultViewWithModel_WhenStateIsValidWithoutUploadedImageAndRoleNotChanged() { // Arrange var dataMock = new Mock <IPickAndBookData>(); var companyRepositoryMock = new Mock <ICompanyRepository>(); dataMock.Setup(c => c.Companies).Returns(companyRepositoryMock.Object); var categoryRepositoryMock = new Mock <ICategoryRepository>(); var categoriesAll = GetCategories(5); categoryRepositoryMock.Setup(c => c.All()).Returns(categoriesAll.AsQueryable()); dataMock.Setup(c => c.Categories).Returns(categoryRepositoryMock.Object); string userId = Guid.NewGuid().ToString(); var identity = new GenericIdentity(userId, ""); var nameIdentifierClaim = new Claim(ClaimTypes.NameIdentifier, userId); identity.AddClaim(nameIdentifierClaim); var userMock = new Mock <IPrincipal>(); userMock.Setup(x => x.Identity).Returns(identity); var controllerContextMock = new Mock <ControllerContext>(); controllerContextMock.Setup(cc => cc.HttpContext.User).Returns(userMock.Object); RegisterCompanyController controller = new RegisterCompanyController(dataMock.Object, new FileUploader(new TestPathProvider()), new TestUserRoleManagerFalse()) { ControllerContext = controllerContextMock.Object }; Company company = new Company() { CompanyId = Guid.NewGuid(), Address = "Adress", City = "City", CategoryId = Guid.NewGuid(), CompanyDescription = "Description", CompanyName = "Name", Email = "Email", PhoneNumber = "889966558855", UserId = Guid.NewGuid().ToString() }; // Act & Assert controller.WithCallTo(c => c.Index(company, null)) .ShouldRenderDefaultView() .WithModel <Company>(company); }
public void ManageUpdateUserAlias_TestEmpty() { // Arrange var context = new Mock <HttpContextBase>(); var identity = new GenericIdentity("test"); identity.AddClaim(new Claim("http://schemas.xmlsoap.org/ws/2005/05/identity/claims/nameidentifier", "f752739e-8d58-4bf5-a140-fc225cc5ebdb")); //test user var principal = new GenericPrincipal(identity, new[] { "user" }); context.Setup(s => s.User).Returns(principal); var userStore = new Mock <IUserStore <ApplicationUser> >(); var userManager = new Mock <ApplicationUserManager>(userStore.Object); var authenticationManager = new Mock <IAuthenticationManager>(); var signInManager = new Mock <ApplicationSignInManager>(userManager.Object, authenticationManager.Object); var claimsIdentity = new Mock <ClaimsIdentity>(MockBehavior.Loose); claimsIdentity.Setup(x => x.AddClaim(It.IsAny <Claim>())); IList <UserLoginInfo> userlogins = new List <UserLoginInfo>(); userManager.Setup(x => x.GetPhoneNumberAsync(It.IsAny <string>())).Returns(Task.FromResult("123")); userManager.Setup(x => x.GetTwoFactorEnabledAsync(It.IsAny <string>())).Returns(Task.FromResult(true)); userManager.Setup(x => x.GetLoginsAsync(It.IsAny <string>())).Returns(Task.FromResult(userlogins)); ManageController controller = new ManageController(userManager.Object, signInManager.Object, new EventService()); controller.ControllerContext = new ControllerContext(context.Object, new RouteData(), controller); // Act JsonResult result = controller.UpdateUserAlias("").Result as JsonResult; // Assert Assert.IsNotNull(result); IDictionary <string, object> data = new RouteValueDictionary(result.Data); Assert.IsTrue(condition: (string)data["result"] == "Failure"); // Act result = controller.UpdateUserAlias(Uri.UnescapeDataString("%E2%80%8F")).Result as JsonResult; // Assert Assert.IsNotNull(result); data = new RouteValueDictionary(result.Data); Assert.IsTrue(condition: (string)data["result"] == "Failure"); }
protected override Task <AuthenticateResult> HandleAuthenticateAsync() { return(Task.Run(() => { try { var APIKey = Context.Request.Headers["APIKey"]; var encrypted_buff = Convert.FromBase64String(APIKey); var DecryptedAPIKey = apiKeyProvider.DecryptData(encrypted_buff); SignedKeyData signedData = JsonConvert.DeserializeObject <SignedKeyData>(Encoding.ASCII.GetString(DecryptedAPIKey)); if (signedData.expiresAt.HasValue) { DateTime expireTime = DateTime.FromFileTimeUtc(signedData.expiresAt.Value); if (DateTime.Now > expireTime) { return AuthenticateResult.Fail("Expired Token"); } } var identity = new GenericIdentity("API"); identity.AddClaim(new System.Security.Claims.Claim("Origin", "Api")); foreach (var role in signedData.roles) { identity.AddClaim(new System.Security.Claims.Claim("role", role)); } var principal = new GenericPrincipal(identity, new[] { signedData.name }); var ticket = new AuthenticationTicket(principal, new AuthenticationProperties(), Scheme.Name); return AuthenticateResult.Success(ticket); } catch (System.Exception e) { return AuthenticateResult.Fail("Invalid APIKey"); } })); }
//inspired from https://forums.asp.net/t/2028867.aspx?UnitTest+How+to+Mock+User+Identity+GetUserId+ public static T WithAuthenticatedUser <T>(this T controller, string userId) where T : Controller { var context = new Mock <HttpContextBase>(); //var request = new Mock<HttpRequestBase>(); var identity = new GenericIdentity(userId); identity.AddClaim(new Claim("http://schemas.xmlsoap.org/ws/2005/05/identity/claims/nameidentifier", userId)); var principal = new GenericPrincipal(identity, new[] { "user" }); context.Setup(s => s.User).Returns(principal); controller.ControllerContext = new ControllerContext(context.Object, new RouteData(), controller); return(controller); }
private GenericIdentity CreateIdentity(MembershipProviderUser user) { var identity = new GenericIdentity(user.Username, BasicScheme); identity.AddClaim(new Claim(ClaimTypes.Sid, user.UserId)); identity.AddClaim(new Claim(ClaimTypes.Email, user.Email)); if (GetAdditionalClaims != null) { try { var claims = GetAdditionalClaims(user); identity.AddClaims(claims); } catch (Exception exception) { const string msg = "Error getting additional claims from caller"; Debug.WriteLine(msg + ": " + exception); throw new Exception(msg, exception); } } return(identity); }
private void MoqUser() { var context = new Mock <HttpContext>(); var claim = new Claim("selectedAgency", "selectedAgency,022001000000"); var usernum = new Claim(IdentityConfigs.Claims.SelectedCR, "1010000154"); var agencyCode = new Claim(IdentityConfigs.Claims.Agency, "022001000000"); var idintity = new GenericIdentity(IdentityConfigs.Claims.SelectedGovAgency, "selectedAgency"); idintity.AddClaim(usernum); idintity.AddClaim(claim); idintity.AddClaim(agencyCode); var headers = new Dictionary <string, StringValues>(); headers.Add("language", "ar-SA"); context.Setup(x => x.Request.Headers) .Returns(new HeaderDictionary(headers)); context.Setup(x => x.Items) .Returns(new Dictionary <object, object>()); context.SetupGet(x => x.User.Identity).Returns(() => { return(idintity); }); context.SetupGet(x => x.User.Claims).Returns(() => { return(idintity.Claims); }); _moqHttpContextAccessor.SetupGet(x => x.HttpContext).Returns(context.Object); }
private void MockIdentity() { // http://forums.asp.net/t/2028867.aspx?UnitTest+How+to+Mock+User+Identity+GetUserId+ var context = new Mock <HttpContextBase>(); var request = new Mock <HttpRequestBase>(); var identity = new GenericIdentity("*****@*****.**"); identity.AddClaim(new Claim("http://schemas.xmlsoap.org/ws/2005/05/identity/claims/nameidentifier", "1")); var principal = new GenericPrincipal(identity, new[] { "user" }); context.Setup(s => s.User).Returns(principal); this.controller.ControllerContext = new ControllerContext(context.Object, new RouteData(), this.controller); }
public static void MockCurrentUser(this Controller controller, string userId, string userName) { var identity = new GenericIdentity(userName); identity.AddClaim( new Claim("http://schemas.xmlsoap.org/ws/2005/05/identity/claims/name" , userName)); identity.AddClaim( new Claim("http://schemas.xmlsoap.org/ws/2005/05/identity/claims/nameidentifier" , userId)); var principal = new GenericPrincipal(identity, null); //We dont use roles here! var mockHttpContext = new Mock <HttpContextBase>(); mockHttpContext.SetupGet(c => c.User).Returns(principal); var mockControllerContext = new Mock <ControllerContext>(); mockControllerContext.SetupGet(c => c.HttpContext).Returns(mockHttpContext.Object); controller.ControllerContext = mockControllerContext.Object; }
public void ReturnJsonWithCorrectModel_WhennModelStateIsValid() { // Arrange // This code mock User.Identity.GetUserId() var context = new Mock <HttpContextBase>(); var identity = new GenericIdentity("*****@*****.**"); identity.AddClaim(new Claim("http://schemas.xmlsoap.org/ws/2005/05/identity/claims/nameidentifier", "1")); var principal = new GenericPrincipal(identity, new[] { "user" }); context.Setup(s => s.User).Returns(principal); // var advertViewModel = new AdvertViewModel() { Title = "advert", VehicleModelId = 1, Year = 100, Price = 100m, Power = 100, DistanceCoverage = 100, CityId = 1, Description = "ani description", CreatedOn = DateTime.Now }; var advertService = new Mock <IAdvertService>(); var ajaxAdvertController = new CarAdverts.Web.Areas.Administrator.Controllers.AjaxAdvertController(advertService.Object); ajaxAdvertController.ControllerContext = new ControllerContext(context.Object, new RouteData(), ajaxAdvertController); // Act and Arrange ajaxAdvertController .WithCallTo(x => x.Add(advertViewModel)) .ShouldReturnJson(data => { Assert.AreEqual(data.Title, advertViewModel.Title); Assert.AreEqual(data.VehicleModelId, advertViewModel.VehicleModelId); Assert.AreEqual(data.Year, advertViewModel.Year); Assert.AreEqual(data.Price, advertViewModel.Price); Assert.AreEqual(data.Power, advertViewModel.Power); Assert.AreEqual(data.DistanceCoverage, advertViewModel.DistanceCoverage); Assert.AreEqual(data.CityId, advertViewModel.CityId); Assert.AreEqual(data.Description, advertViewModel.Description); Assert.AreEqual(data.CreatedOn, advertViewModel.CreatedOn); }); }
public void TestDismissAction_ShouldDismissTheContest() { var data = new PhotoContestDataMock(); var users = data.Users; users.Add(new ApplicationUser() { Id = "0", Email = "*****@*****.**", UserName = "******", FirstName = "*****@*****.**" }); var contests = data.Contests; contests.Add(new Contest() { Id = 0, Title = "test", Description = "test", DeadlineStrategy = DeadlineStrategy.ByTime, MaxParticipationsCount = 5, ParticipationEndTime = DateTime.Now.AddDays(10), ParticipationStrategy = Strategy.Open, VotingStrategy = Strategy.Open, State = TypeOfEnding.Ongoing, OwnerId = users.All().First().Id }); var identity = new GenericIdentity("*****@*****.**"); identity.AddClaim(new Claim("http://schemas.xmlsoap.org/ws/2005/05/identity/claims/nameidentifier", "0")); var controller = new ContestController(data); var controllerContext = new TestableControllerContext(); var principal = new GenericPrincipal(identity, null); var testableHttpContext = new TestableHttpContext { User = principal }; controllerContext.HttpContext = testableHttpContext; controller.ControllerContext = controllerContext; var result = controller.Dismiss(0) as ViewResult; Assert.AreEqual(TypeOfEnding.Dissmissed, data.Contests.All().First().State); Assert.IsTrue(data.IsSaveCalled); }
public void Create_RecipientAndSubject_OpenCreateMessageView() { // Arrange var messagesController = this.CreateMessagesController(true); var user = new ApplicationUser() { UserName = "******", Email = "*****@*****.**" }; mockadvert_siteContext.Users.Add(user); mockadvert_siteContext.SaveChanges(); var identity = new GenericIdentity(fakeUser.Id, ClaimTypes.NameIdentifier); identity.AddClaim(new Claim(ClaimTypes.NameIdentifier, fakeUser.Id)); var fakeUserIdent = new GenericPrincipal(identity, new string[] { "User" }); var httpContext = new Mock <HttpContext>(); httpContext.Setup(x => x.Request.Query["recipientId"]).Returns(user.Id); httpContext.Setup(x => x.Request.Query["subject"]).Returns(this.fakeUser.Id); httpContext.Setup(x => x.User).Returns(fakeUserIdent); var controllerContext = new ControllerContext() { HttpContext = httpContext.Object }; messagesController.ControllerContext = controllerContext; // Act var result = messagesController.Create(); var resultView = (ViewResult)result; var sender = (CreateMessageModel)resultView.Model; // Assert Assert.IsType <ViewResult>(result); Assert.IsType <CreateMessageModel>(resultView.Model); Assert.Equal(user.Id, sender.RecipientId); }
public void TestRemoveParticipantAction_ContestWrongOwner_ShouldRedirectToGetUserContests() { var data = new PhotoContestDataMock(); var users = data.Users; users.Add(new ApplicationUser() { Id = "0", Email = "*****@*****.**", UserName = "******", FirstName = "*****@*****.**" }); var contests = data.Contests; contests.Add(new Contest() { Id = 0, Title = "test", Description = "test", DeadlineStrategy = DeadlineStrategy.ByTime, MaxParticipationsCount = 5, ParticipationEndTime = DateTime.Now.AddDays(10), ParticipationStrategy = Strategy.Open, VotingStrategy = Strategy.Open, State = TypeOfEnding.Ongoing, OwnerId = "1" }); var identity = new GenericIdentity("*****@*****.**"); identity.AddClaim(new Claim("http://schemas.xmlsoap.org/ws/2005/05/identity/claims/nameidentifier", "0")); var controller = new ContestController(data); var controllerContext = new TestableControllerContext(); var principal = new GenericPrincipal(identity, null); var testableHttpContext = new TestableHttpContext { User = principal }; controllerContext.HttpContext = testableHttpContext; controller.ControllerContext = controllerContext; var result = (RedirectToRouteResult)controller.RemoveParticipant(0, "*****@*****.**"); Assert.AreEqual("GetUserContests", result.RouteValues["action"]); Assert.AreEqual("User", result.RouteValues["controller"]); }
private IController CreateControllerInstance(IPhotoService service) { //prepare identity for test var context = new Mock <HttpContextBase>(); var identity = new GenericIdentity("*****@*****.**"); identity.AddClaim(new Claim("http://schemas.xmlsoap.org/ws/2005/05/identity/claims/nameidentifier", "1")); var principal = new GenericPrincipal(identity, new[] { "user" }); context.Setup(s => s.User).Returns(principal); // create new instance of controller and setup some value for it _photoController = new PhotosController(service); _photoController.ControllerContext = new ControllerContext(context.Object, new RouteData(), _photoController); return(_photoController); }
public GenericIdentity CreateIdentity(string userName, User user) { var identity = new GenericIdentity(string.IsNullOrEmpty(user.DisplayName) ? userName : user.DisplayName); identity.AddClaim(new Claim(ClaimTypes.Sid, user.Id.ToString())); identity.AddClaim(new Claim(ClaimTypes.GivenName, user.DisplayName)); identity.AddClaim(new Claim(ClaimTypes.Name, user.UserName)); identity.AddClaim(new Claim(SmartClaimTypes.ProjectName, string.Empty)); identity.AddClaim(new Claim(SmartClaimTypes.ProjectID, "0")); identity.AddClaim(new Claim(SmartClaimTypes.IsAdmin, user.IsAdmin ? bool.TrueString : bool.FalseString)); return(identity); }
public void CreatePost_Should_RedirectToDefaultViewWithCorrectParameterModel_WhenThereIsExceptionOnCreatingInDatabase() { // Arrange var mockedContext = new Mock <HttpContextBase>(); var identity = new GenericIdentity("*****@*****.**"); identity.AddClaim(new Claim("http://schemas.xmlsoap.org/ws/2005/05/identity/claims/nameidentifier", "1")); var principal = new GenericPrincipal(identity, new[] { "user" }); mockedContext.Setup(s => s.User).Returns(principal); var model = new AdvertCreateViewModel(); IEnumerable <HttpPostedFileBase> uploadedFiles = null; var mockedAdvertService = new Mock <IAdvertService>(); var mockedMappingService = new Mock <IMappingService>(); var mockedCityService = new Mock <ICityService>(); var mockedVehicleModelService = new Mock <IVehicleModelService>(); mockedAdvertService.Setup(a => a.CreateAdvert(It.IsAny <Advert>(), It.IsAny <IEnumerable <HttpPostedFileBase> >())).Throws(new Exception()); var advertController = new AdvertController( mockedAdvertService.Object, mockedMappingService.Object, mockedVehicleModelService.Object, mockedCityService.Object); advertController.ControllerContext = new ControllerContext(mockedContext.Object, new RouteData(), advertController); // Act & Assert advertController .WithCallTo(c => c.Create(model, uploadedFiles)) .ShouldRenderDefaultView() .WithModel <AdvertCreateViewModel>(x => { Assert.IsNull(x.Title); Assert.AreEqual(x.VehicleModelId, 0); Assert.AreEqual(x.Year, 0); Assert.AreEqual(x.Price, 0); Assert.AreEqual(x.Power, 0); Assert.AreEqual(x.DistanceCoverage, 0); Assert.AreEqual(x.CityId, 0); Assert.IsNull(x.Description); }); }
public void ShouldGetIDMRolesSuccess(string key, string value) { var claim = new Claim(key, value); var idintity = new GenericIdentity(IdentityConfigs.Claims.VRORole, "VRORole"); idintity.AddClaim(claim); _httpContext.SetupGet(x => x.HttpContext.User.Identity).Returns(() => { return(idintity); }); _httpContext.SetupGet(x => x.HttpContext.User.Claims).Returns(() => { return(idintity.Claims); }); _moqIDMApp.Setup(m => m.GetIDMRoles()) .Returns(() => { return(new List <IDMRolesModel>(new CommitteeDefaults().GetIDMRolesModel())); }); var result = _sutManageUsersAssignationAppService.GetIDMRoles(); Assert.NotNull(result); }
public ClaimsPrincipal GetCustomPrincipal(string uniqueIdentifier) { string cacheKey = this.GetFullCacheKey(uniqueIdentifier); ClaimsPrincipal cachedOrFreshPrincipal = GetFromCache <ClaimsPrincipal>( cacheKey, () => { ClaimsPrincipal returnPrinc = null; ClaimsIdentity ci = new GenericIdentity(this.GetType().ToString()); ci.AddClaim(new Claim("MyType", "MyValue")); returnPrinc = new ClaimsPrincipal(ci); return(returnPrinc); }); return(cachedOrFreshPrincipal); }
public static Mock <IHttpContextAccessor> Context(Guid userId, string username = "******", string[] roles = null) { //Mock IHttpContextAccessor var mockHttpContextAccessor = new Mock <IHttpContextAccessor>(); var context = new DefaultHttpContext(); mockHttpContextAccessor.Setup(_ => _.HttpContext).Returns(context); // Generamos la identidad en base al usuario, el id y los roles var fakeIdentity = new GenericIdentity(username); fakeIdentity.AddClaim(new System.Security.Claims.Claim(UserApp.IdentityIdClaim, userId.ToString())); var principal = new GenericPrincipal(fakeIdentity, roles); context.User = principal; return(mockHttpContextAccessor); }
public void OnAuthorization(AuthorizationFilterContext context) { if (context.HttpContext.User.Identity.IsAuthenticated) { return; } var headers = context.HttpContext.Request.Headers["Authorization"]; if (headers.IsNullOrEmpty() || !headers[0].StartsWith("Basic ")) { return; } var token = headers[0].Substring(6); var decryptedToken = Convert.FromBase64String(token); var credentials = Encoding.UTF8.GetString(decryptedToken).Split(':'); var username = credentials[0]; var password = credentials[1]; var dbContext = (ApplicationDbContext)context.HttpContext.RequestServices.GetService(typeof(ApplicationDbContext)); var passwordHasher = (IPasswordHasher <ApplicationUser>)context.HttpContext.RequestServices.GetService( typeof(IPasswordHasher <ApplicationUser>)); var user = dbContext.ApplicationUsers.FirstOrDefault(u => u.Email.Equals(username)); if (user == null) { return; } if (passwordHasher.VerifyHashedPassword(user, user.PasswordHash, password) != PasswordVerificationResult.Success) { return; } var identity = new GenericIdentity(username); identity.AddClaim(new Claim(new ClaimsIdentityOptions().UserIdClaimType, user.Id)); var principal = new ClaimsPrincipal(identity); context.HttpContext.User = principal; }
public FetchBuildingTenantsTests() { facade = new Mock <IFacade>(); var username = "******"; var identity = new GenericIdentity(username, ""); var nameIdentityClaim = new Claim(ClaimTypes.NameIdentifier, username); identity.AddClaim(nameIdentityClaim); var principal = new Mock <IPrincipal>(); principal.Setup(p => p.Identity).Returns(identity); principal.Setup(p => p.IsInRole("Tenant")).Returns(true); controllerContext = new HttpControllerContext { RequestContext = { Principal = principal.Object } }; }
public void RedirectToDefaultViewWithCorrectParameterModel_WhenOcuredExceptionOfCreatingInDb() { // Arrange // This code mock User.Identity.GetUserId() var context = new Mock <HttpContextBase>(); var identity = new GenericIdentity("*****@*****.**"); identity.AddClaim(new Claim("http://schemas.xmlsoap.org/ws/2005/05/identity/claims/nameidentifier", "1")); var principal = new GenericPrincipal(identity, new[] { "user" }); context.Setup(s => s.User).Returns(principal); // var model = new AdvertInputViewModel(); IEnumerable <HttpPostedFileBase> uploadedFiles = null; var advertService = new Mock <IAdvertService>(); advertService.Setup(a => a.CreateAdvert(It.IsAny <Advert>(), It.IsAny <IEnumerable <HttpPostedFileBase> >())).Throws(new Exception()); var cityService = new Mock <ICityService>(); var modelService = new Mock <IVehicleModelService>(); var advertController = new CRUDAdvertController(advertService.Object, cityService.Object, modelService.Object); advertController.ControllerContext = new ControllerContext(context.Object, new RouteData(), advertController); // Act and Assert advertController .WithCallTo(c => c.Create(model, uploadedFiles)) .ShouldRenderDefaultView() .WithModel <AdvertInputViewModel>(x => { Assert.IsNull(x.Title); Assert.AreEqual(x.VehicleModelId, 0); Assert.AreEqual(x.Year, 0); Assert.AreEqual(x.Price, 0); Assert.AreEqual(x.Power, 0); Assert.AreEqual(x.DistanceCoverage, 0); Assert.AreEqual(x.CityId, 0); Assert.IsNull(x.Description); }); }
public void ReturnCompanyDetailsPageWhitCompanyModel_WhenCompanyForCurrentUserFound() { // Arrange var dataMock = new Mock <IPickAndBookData>(); var companyRepositoryMock = new Mock <ICompanyRepository>(); string userId = Guid.NewGuid().ToString(); Company company = new Company() { CompanyId = Guid.NewGuid(), Address = "Adress", City = "City", CategoryId = Guid.NewGuid(), CompanyDescription = "Description", CompanyName = "Name", Email = "Email", PhoneNumber = "889966558855", UserId = userId }; companyRepositoryMock.Setup(c => c.GetCompanyByUserId(userId)).Returns(company); dataMock.Setup(c => c.Companies).Returns(companyRepositoryMock.Object); var identity = new GenericIdentity(userId, ""); var nameIdentifierClaim = new Claim(ClaimTypes.NameIdentifier, userId); identity.AddClaim(nameIdentifierClaim); var userMock = new Mock <IPrincipal>(); userMock.Setup(x => x.Identity).Returns(identity); var controllerContextMock = new Mock <ControllerContext>(); controllerContextMock.Setup(cc => cc.HttpContext.User).Returns(userMock.Object); RegisterCompanyController controller = new RegisterCompanyController(dataMock.Object) { ControllerContext = controllerContextMock.Object }; // Act & Assert controller.WithCallTo(c => c.Index()) .ShouldRenderView("CompanyDetails") .WithModel <Company>(company); }
public void TestIndexAction_ReturnIndexView() { var identity = new GenericIdentity("as"); identity.AddClaim(new Claim("http://schemas.xmlsoap.org/ws/2005/05/identity/claims/nameidentifier", "0")); var controller = new ContestController(new PhotoContestDataMock()); var controllerContext = new TestableControllerContext(); var principal = new GenericPrincipal(identity, null); var testableHttpContext = new TestableHttpContext { User = principal }; controllerContext.HttpContext = testableHttpContext; controller.ControllerContext = controllerContext; var result = controller.Index() as ViewResult; Assert.AreEqual("Index", result.ViewName); }