/// <summary>
 /// Stores the current <see cref="Thread.CurrentPrincipal"/> and replaces it with
 /// a new role identified in constructor.
 /// </summary>
 /// <param name="methodUnderTest">The method under test</param>
 public override void Before(MethodInfo methodUnderTest)
 {
     originalPrincipal = Thread.CurrentPrincipal;
     var identity = new GenericIdentity("xUnit");
     var principal = new GenericPrincipal(identity, new string[] { Name });
     Thread.CurrentPrincipal = principal;
 }
Exemplo n.º 2
0
	static int Test ()
	{
		GenericIdentity identity = new GenericIdentity ("me");
		string[] roles = new string [1] { "mono hacker" };
		Thread.CurrentPrincipal = new GenericPrincipal (identity, roles);

		return LinkDemand.Test ();
	}
Exemplo n.º 3
0
 public void TrySendIdentity()
 {
     GenericIdentity gident = new GenericIdentity("Testing");
         GenericPrincipal gprincipal = new GenericPrincipal(gident, null);
         Thread.CurrentPrincipal = gprincipal;
         Console.WriteLine("IDentity="+ Thread.CurrentPrincipal.Identity.Name);
         loginObj.ReadIdentity();
 }
Exemplo n.º 4
0
	static int Test ()
	{
		Console.WriteLine ("[this should not print - as JIT will reject the LinkDemand]");

		GenericIdentity identity = new GenericIdentity ("me");
		string[] roles = new string [1] { "mono hacker" };
		Thread.CurrentPrincipal = new GenericPrincipal (identity, roles);

		return LinkDemand ();
	}
Exemplo n.º 5
0
	static int Test ()
	{
		Console.WriteLine ("[this should not print - as JIT will reject the LinkDemand]");

		GenericIdentity identity = new GenericIdentity ("me");
		string[] roles = new string [1] { "mono hacker" };
		Thread.CurrentPrincipal = new GenericPrincipal (identity, roles);

		// Note: if the next line is commented then no exception will 
		// be thrown as the JIT will never reach the LinkDemand class
		return LinkDemand.Test ();
	}
Exemplo n.º 6
0
    public void Demand()
    {
        PolicyDecision decision = new PolicyDecision(config);
        decision.ApplicationName = "Application 3";

        PolicyPermission permission = new PolicyPermission("Permission 1", decision);

        IIdentity identity = new GenericIdentity("User 1");
        IPrincipal principal = new GenericPrincipal(identity, new String[] { "Role 1" });
        Thread.CurrentPrincipal = principal;
        Assert.Throws(typeof(SecurityException),
          permission.Demand);

        identity = new GenericIdentity("User 2");
        principal = new GenericPrincipal(identity, new String[] { "Role 1", "Role 2", "Role 3" });
        Thread.CurrentPrincipal = principal;
        Assert.DoesNotThrow(permission.Demand);
    }
    /// <summary>
    /// Parses the request headers to check the permission of the sender.
    /// If it has a Basic Authentication then it makes all the checks on the user
    /// </summary>
    /// <param name="request">The HTTP request message to send</param>
    /// <param name="cancellationToken">Token to send if the request will crash</param>
    /// <returns>The task object representing the asynchronous operation</returns>
    protected override Task<HttpResponseMessage> SendAsync(HttpRequestMessage request, CancellationToken cancellationToken)
    {
        var authHeader = request.Headers.Authorization;

        if (authHeader == null)
        {
            return base.SendAsync(request, cancellationToken);
        }

        if (authHeader.Scheme != "Basic")
        {
            return base.SendAsync(request, cancellationToken);
        }

        var encodedUserPass = authHeader.Parameter.Trim();
        var userPass = Encoding.ASCII.GetString(Convert.FromBase64String(encodedUserPass));
        var parts = userPass.Split(":".ToCharArray());
        var username = parts[0];
        var password = parts[1];

        GRASPEntities db = new GRASPEntities();

        var item = (from u in db.User_Credential
                    join r in db.Roles on u.roles_id equals r.id
                    where u.username == username && u.password == password
                    select new { u, r }).FirstOrDefault();
        if (item == null)
        {
            return base.SendAsync(request, cancellationToken);
        }

        var identity = new GenericIdentity(username, "Basic");
        string[] roles = new string[1];
        roles[0] = item.r.description;
        var principal = new GenericPrincipal(identity, roles);
        Thread.CurrentPrincipal = principal;
        if (HttpContext.Current != null)
        {
            HttpContext.Current.User = principal;
        }

        return base.SendAsync(request, cancellationToken);
    }
    protected void btnRegister_Click(object sender, EventArgs e)
    {
        string UserId = this.txtUserName.Text;
        MembershipUser user = Membership.CreateUser(UserId, UserId, txtEmail.Text);
        if (user != null)
        {
            FormsAuthentication.Authenticate(UserId, UserId);
            WebProfile Profile = new WebProfile();
            Profile.Initialize(UserId, true);
            Profile.FirstName = this.txtFirstName.Text;
            Profile.LastName = this.txtLastName.Text;
            Profile.Newsletter = this.chkNewsLetter.Checked;
            Profile.Email = this.txtEmail.Text;
            Profile.Save();

            GenericIdentity userIdentity = new GenericIdentity(UserId);
            GenericPrincipal userPrincipal =
              new GenericPrincipal(userIdentity, new string[] { "User" });
            Context.User = userPrincipal;

            if (!Roles.IsUserInRole(User.Identity.Name, "User"))
            {
                PAB.Web.Providers.SimpleSqlRoleProvider prov = new SimpleSqlRoleProvider();
                NameValueCollection config = new NameValueCollection();
                config["connectionStringName"] = "OpenId";
                System.Configuration.ConnectionStringSettings ConnectionStringSettings =
                    System.Configuration.ConfigurationManager.ConnectionStrings[config["connectionStringName"]];
                prov.Initialize("", config);
                prov.AddUsersToRoles(new string[] { User.Identity.Name }, new string[] { "User" });
            }
            // go to a page for users who are authenticated
            Response.Redirect("Default2.aspx");
        }
        else
        {
            //uh-oh! you handle it appropriately.
        }

    }
        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);
        }
Exemplo n.º 10
0
        public override void OnAuthorization(AuthorizationContext filterContext)
        {
            string cookieName = FormsAuthentication.FormsCookieName;

            if (!filterContext.HttpContext.User.Identity.IsAuthenticated ||
                filterContext.HttpContext.Request.Cookies == null ||
                filterContext.HttpContext.Request.Cookies[cookieName] == null
                )
            {
                HandleUnauthorizedRequest(filterContext);
                return;
            }

            var authCookie = filterContext.HttpContext.Request.Cookies[cookieName];
            var authTicket = FormsAuthentication.Decrypt(authCookie.Value);

            string[] roles = authTicket.UserData.Split(',');

            var userIdentity  = new GenericIdentity(authTicket.Name);
            var userPrincipal = new GenericPrincipal(userIdentity, roles);

            filterContext.HttpContext.User = userPrincipal;
            base.OnAuthorization(filterContext);
        }
Exemplo n.º 11
0
        public CreateApartmentTests()
        {
            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);

            model = new ApartmentBindingModel()
            {
                FacingDirection = "North", Level = "3", Number = "1", TenantsAllowed = 2
            };

            controllerContext = new HttpControllerContext {
                RequestContext = { Principal = principal.Object }
            };
        }
Exemplo n.º 12
0
 private void btnaccept_Click(object sender, EventArgs e)
 {
     this.Enabled = false;
     if (txtpassword.Text == string.Empty || txtusername.Text == string.Empty)
     {
         MessageBox.Show("اطلاعات وارد شده درست نمی باشد .", "پیام سیستم", MessageBoxButtons.OK, MessageBoxIcon.Warning);
     }
     else
     {
         var contaxt     = new DataLayer.InventoryDBContext();
         var relateduser = contaxt.Users.FirstOrDefault(u => u.Username.Equals(txtusername.Text));
         if (relateduser == null)
         {
             MessageBox.Show("نام کاربری وجود ندارد .", "پیام سیستم", MessageBoxButtons.OK, MessageBoxIcon.Warning);
         }
         else
         {
             var saltedPassword      = txtpassword.Text + relateduser.PasswordSalt;
             var saltedPasswordBytes = System.Text.Encoding.UTF8.GetBytes(saltedPassword);
             var hashedPassword      = Convert.ToBase64String(SHA512.Create().ComputeHash(saltedPasswordBytes));
             if (!hashedPassword.Equals(relateduser.Password))
             {
                 MessageBox.Show("کلمه عبور نادرست است .", "پیام سیستم", MessageBoxButtons.OK, MessageBoxIcon.Warning);
             }
             else
             {
                 var identity  = new GenericIdentity(relateduser.Username);
                 var roles     = relateduser.Roles.Select(p => p.Title).ToArray();
                 var principal = new GenericPrincipal(identity, roles);
                 System.Threading.Thread.CurrentPrincipal = principal;
                 DialogResult = DialogResult.OK;
             }
         }
     }
     this.Enabled = true;
 }
Exemplo n.º 13
0
        /// <summary>
        /// Função que verifica se o request feito sem Basic Security Header
        /// pode ser retornado
        /// </summary>
        private static void callWithoutBasicHeader(object sender)
        {
            if (sender != null)
            {
                PropertyInfo pInfoRequest = sender.GetType().GetProperty("Request");

                if (pInfoRequest != null)
                {
                    object url = pInfoRequest.GetValue(sender, null);

                    if (url != null)
                    {
                        PropertyInfo pInfoUrl = url.GetType().GetProperty("Url");

                        if (pInfoUrl != null)
                        {
                            string urlRequest = pInfoUrl.GetValue(url, null).ToString();

                            if (!string.IsNullOrEmpty(urlRequest))
                            {
                                if (urlRequest.Contains("AppConsultorServ_RequestFA") || urlRequest.Contains("AppConsultorServ_SendFA") ||
                                    urlRequest.Contains("RetornaPoliticaReembolso"))
                                {
                                    var identity = new GenericIdentity("linx");
                                    SetPrincipal(new GenericPrincipal(identity, null));
                                }
                                else
                                {
                                    HttpContext.Current.Response.StatusCode = 401;
                                }
                            }
                        }
                    }
                }
            }
        }
Exemplo n.º 14
0
        private void CreateUser()
        {
            UserManager <ApplicationUser> manager = new UserManager <ApplicationUser>(new UserStore <ApplicationUser>(db));

            appUser = new ApplicationUser {
                UserName = EMAIL_ADDRESS_TESTER, Email = EMAIL_ADDRESS_TESTER, FullName = FULLNAME_TESTER, TimeZoneId = TIME_ZONE_TESTER
            };
            var result = manager.Create(appUser, PASSWORD_TESTER);

            result = manager.SetLockoutEnabled(appUser.Id, false);
            result = manager.AddToRole(appUser.Id, "Admin");
            db.SaveChanges();

            manager = new UserManager <ApplicationUser>(new UserStore <ApplicationUser>(db));
            var          genericIdentity = new GenericIdentity(EMAIL_ADDRESS_TESTER, "Forms");
            List <Claim> claims          = new List <Claim> {
                new Claim("http://schemas.xmlsoap.org/ws/2005/05/identity/claims/name", EMAIL_ADDRESS_TESTER),
                new Claim("http://schemas.xmlsoap.org/ws/2005/05/identity/claims/nameidentifier", appUser.Id)
            };

            genericIdentity.AddClaims(claims);

            user = new GenericPrincipal(genericIdentity, new string[] { "Admin" });
        }
Exemplo n.º 15
0
        public void DecodeToPrincipal(string token)
        {
            var tokenValidationParameters = new TokenValidationParameters();

            tokenValidationParameters.ValidIssuer        = "self";
            tokenValidationParameters.ValidAudience      = ConfigurationManager.AppSettings["SecurityTokenAddress"];
            tokenValidationParameters.IssuerSigningToken = new BinarySecretSecurityToken(AutorizeHelper.GetBytes(clave));

            var           tokenHandler = new JwtSecurityTokenHandler();
            SecurityToken validatedToken;
            var           tokenIdentity = tokenHandler.ValidateToken(token, tokenValidationParameters, out validatedToken).Identities.First();

            var clientId   = new Guid(tokenIdentity.Claims.Single(c => c.Type.Contains("nameidentifier")).Value);
            var clientName = tokenIdentity.Name;

            GenericIdentity identity = new GenericIdentity(tokenIdentity.Name);
            var             roles    = tokenIdentity.Claims.Where(c => c.Type == ClaimTypes.Role).Select(c => c.Value).ToArray();

            var principal = new GentilPrincipal(clientId, clientName, identity, roles);

            //AutorizeHelper.Principal = principal;
            Thread.CurrentPrincipal  = principal;
            HttpContext.Current.User = principal;
        }
Exemplo n.º 16
0
        public async Task <UserContext> ValidateUserAsync(string username, string password)
        {
            try
            {
                UserContext userContext = null;
                User        user        = await _da.GetModelByAsync <User, USER>(u => u.Email == username);

                if (user != null && IsUserValid(user, password))
                {
                    userContext = new UserContext();
                    string[]        roles    = new string[] { user.Role.Name };
                    GenericIdentity identity = new GenericIdentity(user.Name);

                    userContext.User      = user;
                    userContext.Principal = new GenericPrincipal(identity, roles);
                }

                return(userContext);
            }
            catch (Exception)
            {
                throw;
            }
        }
        public CreateBookingTests()
        {
            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);

            model = new BookingCreateModel()
            {
                EndTime = new DateTime(2016, 12, 25, 23, 59, 00), FacilityId = 3, StartTime = new DateTime(2016, 12, 25, 20, 00, 00)
            };

            controllerContext = new HttpControllerContext {
                RequestContext = { Principal = principal.Object }
            };
        }
Exemplo n.º 18
0
        private void MainWindow_Loaded(object sender, RoutedEventArgs e)
        {
            GenericIdentity MyIdentity = new GenericIdentity("MyIdentity");

            // Create generic principal.
            String[]         MyStringArray = { "Manager", "Teller" };
            GenericPrincipal MyPrincipal   = new GenericPrincipal(MyIdentity, MyStringArray);

            // Attach the principal to the current thread.
            // This is not required unless repeated validation must occur,
            // other code in your application must validate, or the
            // PrincipalPermisson object is used.
            AppDomain.CurrentDomain.SetThreadPrincipal(MyPrincipal);

            var MyDataList = new HashSet <MyData>();

            MyDataList.Add(new MyData {
                ID = "1", Details = "Details for 1"
            });
            MyDataList.Add(new MyData {
                ID = "2", Details = "Details for 2"
            });
            MyDataList.Add(new MyData {
                ID = "3", Details = "Details for 3"
            });
            MyDataList.Add(new MyData {
                ID = "4", Details = "Prueba"
            });
            this.ComboBox1.DataContext = MyDataList;
            this.ComboBox2.DataContext = MyDataList;

            //String original = "John Kennedy";
            //var result = Encryptor.Encode(original, Encryptor.Process("keypass"));
            //this.textBox1.Text = result;
            //this.textBox2.Text = Encryptor.Decode(result, Encryptor.Process("keypass"));
        }
Exemplo n.º 19
0
        static void Main(string[] args)
        {
            // Generic Identity를 생성합니다.
            GenericIdentity myIdentity = new GenericIdentity("MyIndentity");

            // Generic Principal을 생성합니다.
            String[]         myStringArray = { "Manager", "Teller" };
            GenericPrincipal myPrincipal   = new GenericPrincipal(myIdentity, myStringArray);

            // 현재의 쓰레드에 Principal을 첨부해라
            // 반복적은 유효성 검사가 수행되지 않는 한 이 작업은 필요하지 않다.
            // 응용 프로그램의 다른 코드가 유효성을 검사해야 함 또는
            // Principle Permission 객체가 사용된다.
            Thread.CurrentPrincipal = myPrincipal;

            //Console에 값을 출력한다.
            String name     = myPrincipal.Identity.Name;
            bool   auth     = myPrincipal.Identity.IsAuthenticated; //인증되었는가?
            bool   isInRole = myPrincipal.IsInRole("Manager");      //역할이 있는가?

            Console.WriteLine("The name is : {0}", name);
            Console.WriteLine("The isAuthenticated is : {0}", auth);
            Console.WriteLine("Is this a Manager? {0}", isInRole);
        }
        public void TestAddComment()
        {
            var identity = new GenericIdentity("*****@*****.**");

            Thread.CurrentPrincipal = new GenericPrincipal(identity, null);

            var commentResult = (controller.GetComments(1) as PartialViewResult);

            Assert.IsNotNull(commentResult);

            var comments = commentResult.Model as IEnumerable <Comment>;

            Assert.IsNotNull(comments);

            var commentCount = comments.Count();

            var createCommentResult = controller.Create(new Comment
            {
                Text      = "Hello world!",
                TimeStamp = DateTime.Now,
                User      = new User {
                    Id = 1, Email = "*****@*****.**"
                }
            }, 1);

            Assert.IsNotNull(createCommentResult);

            commentResult = (controller.GetComments(1) as PartialViewResult);
            comments      = commentResult?.Model as IEnumerable <Comment>;

            Assert.IsNotNull(comments);

            var newCommentCount = comments.Count();

            Assert.AreEqual(commentCount + 1, newCommentCount);
        }
Exemplo n.º 21
0
        public static void my_AuthenticateRequest()
        {
            HttpCookie authCookie = HttpContext.Current.Request.Cookies[FormsAuthentication.FormsCookieName];

            if (authCookie != null)
            {
                // Get the forms authentication ticket.
                FormsAuthenticationTicket authTicket = FormsAuthentication.Decrypt(authCookie.Value);
                var identity = new GenericIdentity(authTicket.Name, "Forms");

                // Get the custom user data encrypted in the ticket.
                string userData = ((FormsIdentity)(HttpContext.Current.User.Identity)).Ticket.UserData;

                // Deserialize the json data and set it on the custom principal.
                var       serializer = new JavaScriptSerializer();
                UserModel loginUser  = (UserModel)serializer.Deserialize(userData, typeof(UserModel));

                UserModel loggedUser = new UserModel();
                loggedUser.GetUser(loginUser._id);

                HttpContext.Current.Session.Add("loggedUser", loggedUser);
                // Set the context user.
            }
        }
Exemplo n.º 22
0
        public void Ctor_IEnumerableClaimsIdentity_Multiple()
        {
            var baseId1 = new ClaimsIdentity("baseId1");
            var baseId2 = new GenericIdentity("generic_name2", "baseId2");
            var baseId3 = new GenericIdentity("generic_name3", "baseId3");

            var cp = new ClaimsPrincipal(new List <ClaimsIdentity> {
                baseId1, baseId2, baseId3
            });

            Assert.NotNull(cp.Identities);
            Assert.Equal(3, cp.Identities.Count());

            Assert.NotNull(cp.Claims);
            Assert.Equal(2, cp.Claims.Count());

            Assert.Equal(baseId1, cp.Identity);

            Assert.True(cp.Claims.Any(claim => claim.Type == ClaimsIdentity.DefaultNameClaimType && claim.Value == "generic_name2"));
            Assert.True(cp.Claims.Any(claim => claim.Type == ClaimsIdentity.DefaultNameClaimType && claim.Value == "generic_name3"));

            Assert.Equal(baseId2.Claims.First(), cp.Claims.First());
            Assert.Equal(baseId3.Claims.Last(), cp.Claims.Last());
        }
        public UpdateTenantTests()
        {
            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);

            model = new TenantUpdateModel()
            {
                DateofBirth = new DateTime(1995, 03, 16), FirstName = "Vasileios", LastName = "Papadopoulos", Phone = "0123456789", UserId = "3445"
            };

            controllerContext = new HttpControllerContext {
                RequestContext = { Principal = principal.Object }
            };
        }
        public ActionResult Login(LoginModel model)
        {
            if (!String.Equals(model.Login, "test", StringComparison.Ordinal) && !String.Equals(model.Login, "admin", StringComparison.Ordinal) ||
                !String.Equals(model.Password, "1234", StringComparison.Ordinal))
            {
                return(new HttpStatusCodeResult(HttpStatusCode.Unauthorized));
            }

            var identity = new GenericIdentity(model.Login, "ApplicationCookie");
            var claims   = new Claim[0];

            if (model.Login.Equals("test", StringComparison.Ordinal))
            {
                claims = new[] { new Claim("urn:usertype", "king") };
            }
            var claimsIdentity = new ClaimsIdentity(identity, claims);

            AuthenticationManager.SignIn(new AuthenticationProperties()
            {
            }, claimsIdentity);
            SetFormsAuthCookie(claimsIdentity);

            return(RedirectToAction("Index"));
        }
Exemplo n.º 25
0
        public void Handler_ReturnsNullUserView_WhenPrincipalIdentity_IsNotClaimsIdentity()
        {
            var userId = FakeData.Id();
            var user   = new ProxiedUser(userId)
            {
                Name = FakeData.String(),
            };
            var data = new[] { user }.AsQueryable();
            var identity  = new GenericIdentity(user.Name, "authentication type");
            var principal = new GenericPrincipal(identity, null);
            var query     = new UserViewBy(principal);
            var dbSet     = new Mock <DbSet <User> >(MockBehavior.Strict).SetupDataAsync(data);
            var entities  = new Mock <IReadEntities>(MockBehavior.Strict);
            var entitySet = new EntitySet <User>(dbSet.Object, entities.Object);
            IQueryable <User> toBeReturned = entitySet;

            entities.Setup(x => x.Query <User>()).Returns(toBeReturned);
            var handler = new HandleUserViewByQuery(entities.Object);

            UserView result = handler.Handle(query).Result;

            result.ShouldBeNull();
            entities.Verify(x => x.Query <User>(), Times.Once);
        }
Exemplo n.º 26
0
        public void IEnumClaimsIdCtorMultipleIdentitiesWorks()
        {
            var baseId1 = new ClaimsIdentity("baseId1");
            var baseId2 = new GenericIdentity("generic_name2", "baseId2");
            var baseId3 = new GenericIdentity("generic_name3", "baseId3");

            var p = new ClaimsPrincipal(new List <ClaimsIdentity> {
                baseId1, baseId2, baseId3
            });

            Assert.IsNotNull(p.Identities, "#1");
            Assert.AreEqual(3, p.Identities.Count(), "#2");

            Assert.IsNotNull(p.Claims, "#3");
            Assert.AreEqual(2, p.Claims.Count(), "#4");

            Assert.AreEqual(baseId1, p.Identity, "#5");

            Assert.IsTrue(p.Claims.Any(claim => claim.Type == ClaimsIdentity.DefaultNameClaimType && claim.Value == "generic_name2"), "#6");
            Assert.IsTrue(p.Claims.Any(claim => claim.Type == ClaimsIdentity.DefaultNameClaimType && claim.Value == "generic_name3"), "#7");

            Assert.AreEqual(baseId2.Claims.First(), p.Claims.First(), "#7");
            Assert.AreEqual(baseId3.Claims.Last(), p.Claims.Last(), "#8");
        }
        public CreateFacilityTests()
        {
            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);

            model = new FacilityRegisterModel()
            {
                Level = "3", Number = "1"
            };

            controllerContext = new HttpControllerContext {
                RequestContext = { Principal = principal.Object }
            };
        }
Exemplo n.º 28
0
        public void Favourites()
        {
            var mockIdentity = new GenericIdentity("User");

            mockIdentity.AddClaim(new Claim("UserId", "5"));
            var principal = new GenericPrincipal(mockIdentity, null);

            var mockHttpContext = new Mock <HttpContext>();

            mockHttpContext.Setup(m => m.User).Returns(principal);

            var likes = new List <Like>
            {
                new Like {
                    ID = 1, UserID = 5, AdvertID = 6
                },
                new Like {
                    ID = 1, UserID = 5, AdvertID = 2
                },
                new Like {
                    ID = 1, UserID = 5, AdvertID = 10
                }
            };

            mockLikeService.Setup(m => m.FindByUser(It.IsAny <long>())).Returns(likes);

            var controller = new AdminController(mockMenuService.Object, mockUserService.Object,
                                                 mockAdvertService.Object, mockCategoryService.Object, mockLikeService.Object, mapper);

            controller.ControllerContext.HttpContext = mockHttpContext.Object; //you need access to claims object

            var result = controller.Favourites() as ViewResult;
            List <LikeViewModel> model = result.Model as List <LikeViewModel>;

            Assert.Equal(3, model.Count);
        }
Exemplo n.º 29
0
        public void CanPurchase_With_Macau_DS_True()
        {
            // Used constants.
            const string distributor = "24205277";

            System.Threading.Thread.CurrentThread.CurrentCulture = CultureInfo.GetCultureInfo("zh-MO");

            // Rules engine.
            var ruleEngine = new Ordering.Rules.PurchasingPermissions.zh_MO.PurchasingPermissionRules();

            // Getting an online distributor.
            //    var ods = OnlineDistributorHelper.GetOnlineDistributor(distributor);
            MembershipUser  user      = Membership.GetUser(distributor);
            GenericIdentity identity  = new GenericIdentity(user.UserName);
            RolePrincipal   principal = new RolePrincipal(identity);

            System.Threading.Thread.CurrentPrincipal = principal;
            HttpContext.Current.User = principal;
            // Getting a result.
            var result = ruleEngine.CanPurchase(distributor, "SG");

            // Asserts.
            Assert.AreEqual(result, true, "Macau DS with MCID should be able to purchase,No restrictions.");
        }
        protected override Task <HttpResponseMessage> SendAsync(HttpRequestMessage request, CancellationToken cancellationToken)
        {
            string appKey = RetreiveHeaderAuthenticationKey(request);

            // Doesn't match the application key
            if (appConfig.ApplicationKey != appKey)
            {
                return(Unauthorized(request));
            }

            // Check Credentials
            String userLogin    = RetreiveCustomHeaderValue(request, appConfig.AuthenticationUserLoginHeader);
            String userPassword = RetreiveCustomHeaderValue(request, appConfig.AuthenticationUserPasswordHeader);

            User user = authenticationManager.Authenticate(userLogin, userPassword);

            if (user != null)
            {
                // Successful authentication
                GenericIdentity identity = new GenericIdentity(userLogin, appConfig.AuthenticationScheme);
                string[]        roles    = new string[1] {
                    user.RoleId.ToString()
                };
                IPrincipal principal = new GenericPrincipal(identity, roles);
                Thread.CurrentPrincipal  = principal;
                HttpContext.Current.User = principal;


                // continue the flow invoking the other handlers
                return(base.SendAsync(request, cancellationToken));
            }
            else
            {
                return(Unauthorized(request));
            }
        }
Exemplo n.º 31
0
        public void Seed()
        {
            /* ----- USF People GeographicExpertises ----- */

            { // Douglas Corarito
                Person person = _entities.Get <Person>().SingleOrDefault(x => x.FirstName == "Douglas" && x.LastName == "Corarito");
                if (person == null)
                {
                    throw new Exception("USF person Douglas Corarito not found");
                }

                User user = _entities.Get <User>().SingleOrDefault(x => x.Person.RevisionId == person.RevisionId);
                if (user == null)
                {
                    throw new Exception("USF person Douglas Corarito has no User.");
                }

                var developerRoles = new[]
                {
                    RoleName.AuthorizationAgent,
                    RoleName.EstablishmentLocationAgent,
                    RoleName.EstablishmentAdministrator,
                    RoleName.ElmahViewer,
                    RoleName.AgreementManager,
                    RoleName.AgreementSupervisor,
                    RoleName.EmployeeProfileManager,
                };
                var identity  = new GenericIdentity(user.Name);
                var principal = new GenericPrincipal(identity, developerRoles);

                CreateGeographicExpertise         createGeographicExpertiseCommand;
                CreateGeographicExpertiseLocation createGeographicExpertiseLocationCommand;
                Place  place;
                string placeName;

                // GEOGRAPHIC EXPERTISE 1
                var  entityId        = new Guid("82A4789E-7B60-489F-B0FF-79AA6BA24E19");
                bool expertiseExists = _entities.Get <GeographicExpertise>().Count(x => x.EntityId == entityId) > 0;
                if (!expertiseExists)
                {
                    createGeographicExpertiseCommand = new CreateGeographicExpertise(principal)
                    {
                        EntityId    = entityId,
                        Description = "Justo altera ut eam, sit ei cibo porro homero, verear convenire constituto id duo. Ea natum ipsum liberavisse eum. Eu mei nisl ancillae, ei quando ridens volutpat eos. Sit cu eleifend deseruisse."
                    };

                    _createGeographicExpertise.Handle(createGeographicExpertiseCommand);

                    placeName = "Brazil";
                    place     = _entities.Get <Place>().FirstOrDefault(x => x.OfficialName == placeName);
                    if (place == null)
                    {
                        string message = String.Format("{0} not found", placeName);
                        throw new Exception(message);
                    }
                    createGeographicExpertiseLocationCommand = new CreateGeographicExpertiseLocation(principal, createGeographicExpertiseCommand.CreatedGeographicExpertise.RevisionId, place.RevisionId);
                    _createGeographicExpertiseLocation.Handle(createGeographicExpertiseLocationCommand);

                    placeName = "Argentina";
                    place     = _entities.Get <Place>().FirstOrDefault(x => x.OfficialName == placeName);
                    if (place == null)
                    {
                        string message = String.Format("{0} not found", placeName);
                        throw new Exception(message);
                    }
                    createGeographicExpertiseLocationCommand = new CreateGeographicExpertiseLocation(principal, createGeographicExpertiseCommand.CreatedGeographicExpertise.RevisionId, place.RevisionId);
                    _createGeographicExpertiseLocation.Handle(createGeographicExpertiseLocationCommand);

                    _unitOfWork.SaveChanges();
                } // GEOGRAPHIC EXPERTISE 1

                // GEOGRAPHIC EXPERTISE 2
                entityId        = new Guid("8E0CE863-B3D0-44AC-87A7-8F774731CCA9");
                expertiseExists = _entities.Get <GeographicExpertise>().Count(x => x.EntityId == entityId) > 0;
                if (!expertiseExists)
                {
                    createGeographicExpertiseCommand = new CreateGeographicExpertise(principal)
                    {
                        EntityId    = entityId,
                        Description = "Vocent oblique comprehensam sit id, quo nisl corpora molestie ea. Prima liberavisse qui ne, invidunt elaboraret ullamcorper eos et, volumus qualisque hendrerit nam ut."
                    };

                    _createGeographicExpertise.Handle(createGeographicExpertiseCommand);

                    placeName = "Uruguay";
                    place     = _entities.Get <Place>().FirstOrDefault(x => x.OfficialName == placeName);
                    if (place == null)
                    {
                        string message = String.Format("{0} not found", placeName);
                        throw new Exception(message);
                    }
                    createGeographicExpertiseLocationCommand = new CreateGeographicExpertiseLocation(principal, createGeographicExpertiseCommand.CreatedGeographicExpertise.RevisionId, place.RevisionId);
                    _createGeographicExpertiseLocation.Handle(createGeographicExpertiseLocationCommand);

                    placeName = "Colombia";
                    place     = _entities.Get <Place>().FirstOrDefault(x => x.OfficialName == placeName);
                    if (place == null)
                    {
                        string message = String.Format("{0} not found", placeName);
                        throw new Exception(message);
                    }
                    createGeographicExpertiseLocationCommand = new CreateGeographicExpertiseLocation(principal, createGeographicExpertiseCommand.CreatedGeographicExpertise.RevisionId, place.RevisionId);
                    _createGeographicExpertiseLocation.Handle(createGeographicExpertiseLocationCommand);

                    placeName = "Peru";
                    place     = _entities.Get <Place>().FirstOrDefault(x => x.OfficialName == placeName);
                    if (place == null)
                    {
                        string message = String.Format("{0} not found", placeName);
                        throw new Exception(message);
                    }
                    createGeographicExpertiseLocationCommand = new CreateGeographicExpertiseLocation(principal, createGeographicExpertiseCommand.CreatedGeographicExpertise.RevisionId, place.RevisionId);
                    _createGeographicExpertiseLocation.Handle(createGeographicExpertiseLocationCommand);

                    _unitOfWork.SaveChanges();
                } // GEOGRAPHIC EXPERTISE 2
            }     // Douglas Corarito
        }
        public override void OnAuthorization(HttpActionContext actionContext)
        {
            // validar se foi informado no cabeçalho da mensagem o parâmetro de autenticação.
            if (actionContext.Request.Headers.Authorization == null)
            {
                // responde para o cliente como não autorizado
                var dnsHost = actionContext.Request.RequestUri.DnsSafeHost;
                actionContext.Response = actionContext.Request.CreateResponse(HttpStatusCode.Unauthorized);
                actionContext.Response.Headers.Add("WWW-Authenticate", string.Format("Basic realm=\"{0}\"", dnsHost));
                return;
            }
            else
            {
                //obtém o parâmetro (token de autenticação)
                string tokenAutenticacao =
                    actionContext.Request.Headers.Authorization.Parameter;

                // decodifica o parâmetro, pois ele deve vir codificado em base 64
                string decodedTokenAutenticacao =
                    Encoding.Default.GetString(Convert.FromBase64String(tokenAutenticacao));

                // obtém o login e senha (usuario:senha)
                string[] userNameAndPassword = decodedTokenAutenticacao.Split(':');

                // validar as credenciais obtidas com as cadastradas no sistema
                Usuario usuario = null;
                if (ValidarUsuario(userNameAndPassword[0], userNameAndPassword[1], out usuario))
                {
                    string[] papeis = usuario.Permissoes.Select(papel => papel.Nome).ToArray();

                    var identidade  = new GenericIdentity(usuario.Email);
                    var genericUser = new GenericPrincipal(identidade, papeis);

                    // confere o perfil da action com os do usuário
                    if (string.IsNullOrEmpty(Roles))
                    {
                        // atribui o usuário informado no contexto da requisição atual
                        Thread.CurrentPrincipal = genericUser;
                        if (HttpContext.Current != null)
                        {
                            HttpContext.Current.User = genericUser;
                        }

                        return;
                    }
                    else
                    {
                        var currentRoles = Roles.Split(',');
                        foreach (var currentRole in currentRoles)
                        {
                            if (genericUser.IsInRole(currentRole))
                            {
                                // atribui o usuário informado no contexto da requisição atual
                                Thread.CurrentPrincipal = genericUser;
                                if (HttpContext.Current != null)
                                {
                                    HttpContext.Current.User = genericUser;
                                }

                                return;
                            }
                        }
                    }
                }
            }

            actionContext.Response = actionContext.Request.CreateResponse(HttpStatusCode.Unauthorized);
        }
Exemplo n.º 33
0
        private string TestUser()
        {
            string username;

#if DEBUG
            int caseSwitch = Properties.Settings.Default.TestCase;

            GenericIdentity fakeIdentiy = null;
            switch (caseSwitch)
            {
            case (int)Test.AccountingAdmin:
                // Below is AcctAdmin
                fakeIdentiy = new GenericIdentity(Properties.Settings.Default.acctAdmin);
                break;

            case (int)Test.AccountingUser:
                // Below is AcctUser
                fakeIdentiy = new GenericIdentity(Properties.Settings.Default.acctUser);
                break;

            case (int)Test.PDAdmin:
                // Below is PDAdmin
                fakeIdentiy = new GenericIdentity(Properties.Settings.Default.pndAdmin);
                break;

            case (int)Test.PDUser:
                // Below is PDtUser
                fakeIdentiy = new GenericIdentity(Properties.Settings.Default.pndUser);
                break;

            case (int)Test.UMSAdmin:

                // Below is UMSAdmin
                fakeIdentiy = new GenericIdentity(Properties.Settings.Default.umsAdmin);
                break;


            case (int)Test.UMSUser:
                // Below is UMStUser
                fakeIdentiy = new GenericIdentity(Properties.Settings.Default.umsUser);
                break;

            case (int)Test.MSAdmin:
                // Below is MStAdmin
                fakeIdentiy = new GenericIdentity(Properties.Settings.Default.msAdmin);
                break;

            case (int)Test.MSUser:
                // Below is MSUser
                fakeIdentiy = new GenericIdentity(Properties.Settings.Default.msUser);
                break;

            case (int)Test.sysadmin:
                // Below is MSUser
                fakeIdentiy = new GenericIdentity(Properties.Settings.Default.sysadmin);
                break;
            }


            GenericPrincipal principal = new GenericPrincipal(fakeIdentiy, null);
            _user    = principal;
            username = _user.Identity.Name;
#else
            string tempusername;
            UserInjectionMethod(out tempusername, out username);
#endif

            return(username);
        }
 public CustomPrincipal(string username)
 {
     Identity = new GenericIdentity(username);
 }
Exemplo n.º 35
0
 protected GenericIdentity(GenericIdentity identity);
        private void GenerateData(string name, string[] roles)
        {
            GenericIdentity identity = new GenericIdentity(name);

            Thread.CurrentPrincipal = new GenericPrincipal(identity, roles);
        }
Exemplo n.º 37
0
        public void CreateMethodShouldCreateEvent()
        {
            var eventList = new List <Event>
            {
                new Event {
                    Users = new List <ApplicationUser> {
                        new ApplicationUser {
                            Id = "1"
                        }
                    }
                },
                new Event {
                    Users = new List <ApplicationUser> {
                        new ApplicationUser {
                            Id = "1"
                        }
                    }
                },
                new Event {
                    Taken = true, Users = new List <ApplicationUser> {
                        new ApplicationUser {
                            Id = "1"
                        }
                    }
                },
                new Event {
                    Users = new List <ApplicationUser> {
                        new ApplicationUser {
                            Id = "2"
                        }
                    }
                },
            };


            var userList = new List <ApplicationUser>
            {
                new ApplicationUser {
                    Id = "1", Addresses = new List <Address> {
                        new Address()
                    }
                },
                new ApplicationUser {
                    Id = "2", Addresses = new List <Address> {
                        new Address()
                    }
                },
                new ApplicationUser {
                    Id = null, Addresses = new List <Address> {
                        new Address()
                    }
                }
            };

            bool isItemAdded    = false;
            var  eventsRepoMock = new Mock <IRepository <Event> >(MockBehavior.Strict);

            eventsRepoMock.Setup(x => x.Add(It.IsAny <Event>())).Callback(() => isItemAdded = true);
            var usersRepoMock = new Mock <IRepository <ApplicationUser> >(MockBehavior.Strict);

            usersRepoMock.Setup(x => x.All()).Returns(userList.AsQueryable());

            var uowDataMock = new Mock <IUowData>(MockBehavior.Strict);

            uowDataMock.Setup(x => x.Events).Returns(eventsRepoMock.Object);
            bool isSaveChangesExecuted = false;

            // For Async version: uowDataMock.Setup(x => x.SaveChangesAsync()).Returns(It.IsAny<Task<int>>).Callback(() => isSaveChangesExecuted = true);
            uowDataMock.Setup(x => x.SaveChanges()).Returns(It.IsAny <int>).Callback(() => isSaveChangesExecuted = true);
            uowDataMock.Setup(x => x.Users).Returns(usersRepoMock.Object);

            var routes = new RouteCollection();

            RouteConfig.RegisterRoutes(routes);

            var request = new Mock <HttpRequestBase>(MockBehavior.Strict);

            request.SetupGet(x => x.ApplicationPath).Returns("/");
            request.SetupGet(x => x.Url).Returns(new Uri("http://localhost/Events", UriKind.Absolute));
            request.SetupGet(x => x.ServerVariables).Returns(new System.Collections.Specialized.NameValueCollection());

            var response = new Mock <HttpResponseBase>(MockBehavior.Strict);

            response.Setup(s => s.ApplyAppPathModifier(It.IsAny <string>())).Returns <string>(s => s);

            var context = new Mock <HttpContextBase>(MockBehavior.Strict);

            context.SetupGet(x => x.Request).Returns(request.Object);
            context.SetupGet(x => x.Response).Returns(response.Object);
            context.Setup(x => x.GetService(It.IsAny <Type>())).Returns(It.IsAny <Type>());

            var fakeIdentity = new GenericIdentity("User");
            var principal    = new GenericPrincipal(fakeIdentity, null);

            context.SetupGet(x => x.User).Returns(principal);

            var controller = new EventsController(uowDataMock.Object);

            controller.ControllerContext = new ControllerContext(context.Object, new RouteData(), controller);
            controller.Url = new UrlHelper(new RequestContext(context.Object, new RouteData()), routes);

            var model = new CreateEventViewModel
            {
                EndDate   = new DateTime(2014, 12, 13),
                EndTime   = new DateTime(2014, 12, 13, 12, 0, 0),
                EventType = EventType.Single,
                StartDate = new DateTime(2014, 12, 13),
                StartTime = new DateTime(2014, 12, 13, 10, 30, 0),
            };
            var jsonResult = controller.Create(model) as JsonResult;

            Assert.IsNotNull(jsonResult, "UserCalendar action returns null.");
            Assert.AreEqual(true, isItemAdded, "Add method of Events is not invoked.");
            Assert.AreEqual(true, isSaveChangesExecuted, "SaveChanges method is not invoked.");
        }
Exemplo n.º 38
0
        public async Task Invoke(HttpContext context, ApiUserRepository apiUserRepository, UserRepository userRepository)
        {
            if (!context.Request.Headers.ContainsKey(AUTH))
            {
                context.Response.StatusCode = StatusCodes.Status401Unauthorized;
            }
            else
            {
                try
                {
                    var authHeader      = AuthenticationHeaderValue.Parse(context.Request.Headers[AUTH]);
                    var credentialBytes = Convert.FromBase64String(authHeader.Parameter);
                    var credentials     = Encoding.UTF8.GetString(credentialBytes).Split(':', 2);
                    var username        = credentials[0];
                    var password        = credentials[1];

                    var apiUser = await apiUserRepository.GetAsync(username, StringHelper.Hash(password));

                    if (apiUser != null)
                    {
                        var roleName = ApiAuthType.GetName(apiUser.AuthTypeId);

                        var identity  = new GenericIdentity("kc");
                        var principal = new GenericPrincipal(identity, new string[] { roleName });
                        Thread.CurrentPrincipal = principal;

                        if (context.User != null)
                        {
                            context.User = principal;
                        }

                        if (roleName == ApiAuthType.MOBILE_APP_NAME)
                        {
                            if (context.Request.Headers.TryGetValue(API_TOKEN, out StringValues stringValues) && stringValues.Count == 1)
                            {
                                var user = await userRepository.Get(stringValues.Single());

                                context.Items.Add(API_MOBILE_USER, user);
                            }
                            else if (!context.Request.Path.Value.EndsWith("Login")) // TODO: make constant
                            {
                                context.Response.StatusCode = StatusCodes.Status401Unauthorized;
                            }
                        }
                    }
                    else
                    {
                        context.Response.StatusCode = StatusCodes.Status401Unauthorized;
                    }
                }
                catch
                {
                    context.Response.StatusCode = StatusCodes.Status401Unauthorized;
                }
            }

            if (context.Response.StatusCode != StatusCodes.Status401Unauthorized)
            {
                await _next(context);
            }
        }
Exemplo n.º 39
0
        private static void AuthenticateUser(string credentials)
        {
            try
            {
                var encoding = Encoding.GetEncoding("iso-8859-1");
                credentials = encoding.GetString(Convert.FromBase64String(credentials));

                int separator = credentials.IndexOf(':');
                string name = credentials.Substring(0, separator);
                string password = credentials.Substring(separator + 1);

                if (CheckPassword(name, password))
                {
                    var identity = new GenericIdentity(name);
                    SetPrincipal(new GenericPrincipal(identity, null));
                }
                else
                {
                    // Invalid username or password.
                    HttpContext.Current.Response.StatusCode = 401;
                }
            }
            catch (FormatException)
            {
                // Credentials were not formatted correctly.
                HttpContext.Current.Response.StatusCode = 401;
            }
        }
Exemplo n.º 40
0
        public void GetObjectData(SerializationInfo info, StreamingContext context)
        {
            if (context.State == StreamingContextStates.CrossAppDomain)
            {
                GenericIdentity gIdent = new GenericIdentity(this.Name, this.AuthenticationType);
                info.SetType(gIdent.GetType());

                System.Reflection.MemberInfo[] serializableMembers;
                object[] serializableValues;

                serializableMembers = FormatterServices.GetSerializableMembers(gIdent.GetType());
                serializableValues = FormatterServices.GetObjectData(gIdent, serializableMembers);

                for (int i = 0; i < serializableMembers.Length; i++)
                {
                    info.AddValue(serializableMembers[i].Name, serializableValues[i]);
                }
            }
            else
            {
                throw new InvalidOperationException("Serialization not supported");
            }
        }
 protected GenericIdentity(GenericIdentity identity);
Exemplo n.º 42
0
    public bool IsWarewolfAuthorised(string privilege, string userName, string resourceGuid)
    {
        userName = CleanUser(userName);

        IPrincipal identity;
        try
        {
            identity = new WindowsPrincipal(new WindowsIdentity(userName));
        }
        catch (Exception)
        {
            var groups = GetLocalUserGroupsForTaskSchedule(userName);
            var tmp = new GenericIdentity(userName);
            identity = new GenericPrincipal(tmp, groups.ToArray());
        }

        if (_authorizationService.IsAuthorized(identity, AuthorizationContext.Execute, resourceGuid))
        {
            return true;
        }

        return false;
    }
Exemplo n.º 43
0
            public virtual void OnLogin(object sender, EventArgs e)
            {
                string userName = m_UserNameBox.Text;
                string password = m_PasswordBox.Text;

                if (userName == string.Empty)
                {
                    m_ErrorProvider.SetError(m_UserNameBox, "Please Enter User Name");
                    return;
                }
                else
                {
                    m_ErrorProvider.SetError(m_UserNameBox, string.Empty);
                }
                if (password == string.Empty)
                {
                    m_ErrorProvider.SetError(m_PasswordBox, "Please Enter Password");
                    return;
                }
                else
                {
                    m_ErrorProvider.SetError(m_PasswordBox, string.Empty);
                }
                string applicationName = GetAppName();
                IUserManager userManager = GetUserManager();

                bool authenticated = userManager.Authenticate(applicationName, userName, password);
                if (authenticated)
                {
                    IIdentity identity = new GenericIdentity(userName);
                    CustomPrincipal.Attach(identity, applicationName, userManager, CacheRoles);
                }
                LoginEventArgs loginEventArgs = new LoginEventArgs(authenticated);

                if (LoginEventEvent != null)
                    LoginEventEvent(this, loginEventArgs);
            }