コード例 #1
0
        public bool IsCurrentUserDomainAdmin()
        {
            using (WindowsIdentity identity = WindowsIdentity.GetCurrent())
            {
                try
                {
                    Domain.GetComputerDomain();
                }
                catch (ActiveDirectoryObjectNotFoundException)
                {
                    return(false);
                }

                PrincipalContext ctx;
                try
                {
                    ctx = new PrincipalContext(ContextType.Domain);
                }
                catch
                {
                    return(false);
                }

                var up = UserPrincipal.FindByIdentity(ctx, identity.Name);
                if (up != null)
                {
                    PrincipalSearchResult <Principal> authGroups = up.GetAuthorizationGroups();
                    return(authGroups.Any(principal =>
                                          principal.Sid.IsWellKnown(WellKnownSidType.AccountDomainAdminsSid) ||
                                          principal.Sid.IsWellKnown(WellKnownSidType.AccountEnterpriseAdminsSid)));
                }

                return(false);
            }
        }
コード例 #2
0
        public bool CheckAccountIsBuiltIn(string name)
        {
            bool isBuiltin = false;


            PrincipalContext PrincipalContext = new PrincipalContext(ContextType.Machine);
            UserPrincipal    userPrincipal    = new UserPrincipal(PrincipalContext);

            userPrincipal.Name = name;

            PrincipalSearcher principalSearcher = new PrincipalSearcher();

            principalSearcher.QueryFilter = userPrincipal;
            PrincipalSearchResult <Principal> results = principalSearcher.FindAll();

            if (userPrincipal != null)
            {
                foreach (Principal p in results)
                {
                    if (p.Name == name)
                    {
                        if (p.Description.Contains("Ingebouwde account") || p.Description.Contains("Built-in account"))
                        {
                            isBuiltin = true;
                            break;
                        }
                    }
                }
            }


            return(isBuiltin);;
        }
コード例 #3
0
        public bool IsCurrentUserMachineAdmin()
        {
            using (WindowsIdentity identity = WindowsIdentity.GetCurrent())
            {
                // Require user to run app as admin
                WindowsPrincipal winPrincipal = new WindowsPrincipal(identity);
                if (winPrincipal.IsInRole(WindowsBuiltInRole.Administrator))
                {
                    return(true);
                }

                PrincipalContext ctx;
                try
                {
                    ctx = new PrincipalContext(ContextType.Machine);
                }
                catch
                {
                    return(false);
                }

                var up = UserPrincipal.FindByIdentity(ctx, identity.Name);
                if (up != null)
                {
                    PrincipalSearchResult <Principal> authGroups = up.GetAuthorizationGroups();
                    return(authGroups.Any(principal =>
                                          principal.Sid.IsWellKnown(WellKnownSidType.BuiltinAdministratorsSid) ||
                                          principal.Sid.IsWellKnown(WellKnownSidType.AccountAdministratorSid)));
                }
            }

            return(false);
        }
コード例 #4
0
        public static List <DomainUsers> GetDomainUsers(string group = null)
        {
            List <DomainUsers> listUsers = new List <DomainUsers>();

            try
            {
                //PrincipalContext AD = new PrincipalContext(ContextType.Domain, "LDAP://172.16.10.2");
                PrincipalContext AD = new PrincipalContext(ContextType.Domain, ConfigReader.GetLdapServer());

                UserPrincipal     u      = new UserPrincipal(AD);
                PrincipalSearcher search = new PrincipalSearcher(u);
                PrincipalSearchResult <Principal> searchResult = null;

                searchResult = search.FindAll();

                var usersList = searchResult.Where(s => string.IsNullOrEmpty(group) ||
                                                   s.GetGroups().Any(t => t.Name == group)).ToList();

                foreach (var result in usersList)
                {
                    listUsers.Add(new DomainUsers
                    {
                        UserName = result.SamAccountName,
                        FullName = result.Name
                    });
                }

                return(listUsers);
            }
            catch (Exception ex)
            {
            }

            return(listUsers);
        }
コード例 #5
0
        /// <summary>
        /// Gets a list of locked out users in Active directory
        /// </summary>
        /// <param name="domain"></param>
        /// <param name="username"></param>
        /// <param name="password"></param>
        /// <returns></returns>
        public static List <Users> GetLockedUsers()
        {
            List <Users> lockedUsers = new List <Users>();

            using (PrincipalContext pc = new PrincipalContext(ContextType.Domain, Config.ServiceSettings.PrimaryDC, Config.ServiceSettings.Username, Config.ServiceSettings.Password))
            {
                using (UserPrincipal up = new UserPrincipal(pc))
                {
                    using (PrincipalSearcher ps = new PrincipalSearcher(up))
                    {
                        PrincipalSearchResult <Principal> results = ps.FindAll();
                        foreach (UserPrincipal r in results)
                        {
                            if (r.IsAccountLockedOut())
                            {
                                lockedUsers.Add(new Users()
                                {
                                    UserGuid          = (Guid)r.Guid,
                                    DisplayName       = r.DisplayName,
                                    UserPrincipalName = r.UserPrincipalName,
                                    SamAccountName    = r.SamAccountName,
                                    DistinguishedName = r.DistinguishedName,
                                    IsEnabled         = false
                                });
                            }
                        }
                    }
                }
            }

            return(lockedUsers);
        }
コード例 #6
0
ファイル: LocalAccount.cs プロジェクト: cupid0426/MyProject
        /// <summary>
        /// Finds and returns the UserPrincipal object if it exists, if not, returns null.
        /// This method uses PrincipalSearcher because it is faster than UserPrincipal.FindByIdentity.
        /// The username comparison is case insensitive.
        /// </summary>
        /// <param name="username">The username to search for.</param>
        /// <returns>The UserPrincipal object, or null if not found.</returns>
        public static UserPrincipal GetUserPrincipal(string username)
        {
            if (string.IsNullOrEmpty(username))
            {
                return(null);
            }

            // Since PrincipalSearcher is case sensitive, and we want a case insensitive
            // search, we get a list of all users and compare the names "manually."
            using (PrincipalSearcher searcher = new PrincipalSearcher(new UserPrincipal(m_machinePrincipal)))
            {
                PrincipalSearchResult <Principal> sr = searcher.FindAll();
                foreach (Principal p in sr)
                {
                    if (p is UserPrincipal)
                    {
                        UserPrincipal user = (UserPrincipal)p;
                        if (user.Name.Equals(username, StringComparison.CurrentCultureIgnoreCase))
                        {
                            return(user);
                        }
                    }
                }
            }

            return(null);
        }
コード例 #7
0
ファイル: ADHelper.cs プロジェクト: MarkusBlick/Printum_PT
        public static bool CheckUserinAD(string domain, string username)
        {
            var ADUser_Id = "PRINT\\erp"; //make sure user name has domain name.
            var Password  = "******";
            var context   = new PrincipalContext(ContextType.Domain, "192.168.26.250", ADUser_Id, Password);

            /* server_address = "192.168.15.36"; //don't include ldap in url */


            using (var domainContext = new PrincipalContext(ContextType.Domain, "192.168.26.250", ADUser_Id, Password))
            {
                using (var user = new UserPrincipal(domainContext))
                {
                    user.SamAccountName = username;

                    using (var pS = new PrincipalSearcher())
                    {
                        pS.QueryFilter = user;

                        using (PrincipalSearchResult <Principal> results = pS.FindAll())
                        {
                            if (results != null && results.Count() > 0)
                            {
                                return(true);
                            }
                        }
                    }
                }
            }

            return(false);
        }
コード例 #8
0
ファイル: LocalAccount.cs プロジェクト: cupid0426/MyProject
        /// <summary>
        /// Finds and returns the GroupPrincipal object if it exists, if not, returns null.
        /// This method uses PrincipalSearcher because it is faster than GroupPrincipal.FindByIdentity.
        /// The group name comparison is case insensitive.
        /// </summary>
        /// <param name="groupname"></param>
        /// <returns></returns>
        public static GroupPrincipal GetGroupPrincipal(string groupname)
        {
            if (string.IsNullOrEmpty(groupname))
            {
                return(null);
            }

            // In order to do a case insensitive search, we need to scan all
            // groups "manually."
            using (PrincipalSearcher searcher = new PrincipalSearcher(new GroupPrincipal(m_machinePrincipal)))
            {
                PrincipalSearchResult <Principal> sr = searcher.FindAll();
                foreach (Principal p in sr)
                {
                    if (p is GroupPrincipal)
                    {
                        GroupPrincipal group = (GroupPrincipal)p;
                        if (group.Name.Equals(groupname, StringComparison.CurrentCultureIgnoreCase))
                        {
                            return(group);
                        }
                    }
                }
            }
            return(null);
        }
コード例 #9
0
ファイル: LocalAccount.cs プロジェクト: cupid0426/MyProject
        /// <summary>
        /// Returns a list of groups of which the user is a member.  It does so in a fashion that
        /// may seem strange since one can call UserPrincipal.GetGroups, but seems to be much faster
        /// in my tests.
        /// </summary>
        /// <param name="user"></param>
        /// <returns></returns>
        private static List <GroupPrincipal> GetGroups(UserPrincipal user)
        {
            List <GroupPrincipal> result = new List <GroupPrincipal>();

            // Get all groups using a PrincipalSearcher and
            GroupPrincipal filter = new GroupPrincipal(m_machinePrincipal);

            using (PrincipalSearcher searcher = new PrincipalSearcher(filter))
            {
                PrincipalSearchResult <Principal> sResult = searcher.FindAll();
                foreach (Principal p in sResult)
                {
                    if (p is GroupPrincipal)
                    {
                        GroupPrincipal gp = (GroupPrincipal)p;
                        if (LocalAccount.IsUserInGroup(user, gp))
                        {
                            result.Add(gp);
                        }
                        else
                        {
                            gp.Dispose();
                        }
                    }
                    else
                    {
                        p.Dispose();
                    }
                }
            }
            return(result);
        }
コード例 #10
0
        public IEnumerable <LicenseUser> GetAllUsers()
        {
            using (var principalContext = new PrincipalContext(ContextType.Domain))
            {
                using (var userPrincipal = new UserPrincipal(principalContext))
                {
                    using (var principalSearcher = new PrincipalSearcher(userPrincipal))
                    {
                        using (PrincipalSearchResult <Principal> results = principalSearcher.FindAll())
                        {
                            foreach (Principal principal in results)
                            {
                                if (!principal.Guid.HasValue)
                                {
                                    continue;
                                }

                                LicenseUser localUser = GetUserById(principal.Guid.Value);
                                if (localUser == null)
                                {
                                    continue;
                                }

                                yield return(localUser);
                            }
                        }
                    }
                }
            }
        }
コード例 #11
0
ファイル: WinUserInfo.cs プロジェクト: rtjust/PastProjects
        public bool CreateUserPrincipal()
        {
            // Create connection to domain and do a search for the user
            try
            {
                context = new PrincipalContext(ContextType.Domain, givenDomain);

                    UserPrincipal tempUserPrincipal = new UserPrincipal(context);
                    tempUserPrincipal.SamAccountName = givenUserName;

                    // Search for user
                    PrincipalSearcher searchUser = new PrincipalSearcher();
                    searchUser.QueryFilter = tempUserPrincipal;

                    UserPrincipal foundUser = (UserPrincipal)searchUser.FindOne();

                    userPrincipal = foundUser;
                    userGroups = userPrincipal.GetGroups();
                    return true;

            }
            catch (PrincipalServerDownException)
            {
                System.Windows.Forms.MessageBox.Show("Cannot contact the server.");
                return false;
            }
            catch (Exception e)
            {
                System.Windows.Forms.MessageBox.Show(e.Message, "Unknown Error", System.Windows.Forms.MessageBoxButtons.OK, System.Windows.Forms.MessageBoxIcon.Error);
                return false;
            }
        }
コード例 #12
0
        public List <User> GetAllUsers()
        {
            PrincipalContext context = new PrincipalContext(ContextType.Domain);

            _logger.Debug($"Using PrincipalContext: {context.Name} - Server: {context.ConnectedServer}");
            UserPrincipal userPrincipal = new UserPrincipal(context);

            _logger.Debug($"Using UserPrincipal: {userPrincipal.Name} - Default");

            PrincipalSearcher search = new PrincipalSearcher(userPrincipal);
            List <User>       users  = new List <User>();
            PrincipalSearchResult <Principal> searchResults = search.FindAll();

            _logger.Debug($"Principal search executed. Result: Count: {searchResults.Count()}");

            foreach (UserPrincipal result in searchResults)
            {
                if (!string.IsNullOrWhiteSpace(result.SamAccountName) && !string.IsNullOrWhiteSpace(result.EmailAddress) &&
                    (!string.IsNullOrEmpty(result.GivenName) || !string.IsNullOrEmpty(result.Surname)))
                {
                    users.Add(new User()
                    {
                        FirstName    = result.GivenName,
                        LastName     = result.Surname,
                        PayId        = new User.Pid(result.SamAccountName),
                        EmailAddress = result.EmailAddress
                    });
                }
            }

            _logger.Trace(LoggerHelper.ExecutedFunctionMessage(users));

            return(users);
        }
コード例 #13
0
        private bool adCheckGroup(String _grp)
        {
            Console.WriteLine("Checking ActiveDirectory Groups: ");
            try
            {
                PrincipalContext ADDomain = new PrincipalContext(ContextType.Domain);
                UserPrincipal    user     = UserPrincipal.FindByIdentity(ADDomain, UserPrincipal.Current.ToString());

                // if found - grab its groups
                if (user != null)
                {
                    PrincipalSearchResult <Principal> groups = user.GetAuthorizationGroups();

                    // iterate over all groups
                    foreach (Principal p in groups)
                    {
                        Console.WriteLine("Group-->: " + p.Name);
                        if (p.Name.ToLower() == _grp.ToLower())
                        {
                            return(true);
                        }
                    }
                }
            }
            catch (Exception e) // evtl. non-AD-User
            {
                Console.WriteLine("AD-Group Check failed: " + e.Message);
            }

            return(false);
        }
コード例 #14
0
ファイル: ADService.cs プロジェクト: jsdelivrbot/test-34
        /*
         * Finds any membership in Prodtracker groups in order to set appropriate claim for incoming user.
         */
        public List <GroupPrincipal> GetGroups(string userName)
        {
            List <GroupPrincipal> result = new List <GroupPrincipal>();

            UserPrincipal user = UserPrincipal.FindByIdentity(DomainContext, userName);

            if (user != null)
            {
                PrincipalSearchResult <Principal> groups = user.GetAuthorizationGroups();

                foreach (Principal p in groups)
                {
                    if (p is GroupPrincipal)
                    {
                        // We're only interested in the application groups.
                        if (p.Name.ToLower().Contains(applicationGroupName.ToLower()) || p.Name.ToLower().Contains(adminGroupIdentifier.ToLower()))
                        {
                            //Log.Info(userName + " is in " + p.Name.ToLower());

                            result.Add((GroupPrincipal)p);
                        }
                    }
                }
            }

            return(result);
        }
        public static User ValidateCredentials(string userName, string password)
        {
            try
            {
                //when connecting to a DC : new PrincipalContext(ContextType.Domain, "ESTAGIOIT", "CN=Users,DC=estagioit,DC=local");
                //optionally a container (as an LDAP path - a "distinguished" name, full path but without any LDAP:// prefix)
                using (var adContext = new PrincipalContext(ContextType.Machine, null))
                {
                    if (adContext.ValidateCredentials(userName, password))
                    {
                        //user
                        UserPrincipal usr = new UserPrincipal(adContext);
                        usr.SamAccountName = userName;
                        var searcher = new PrincipalSearcher(usr);
                        usr = searcher.FindOne() as UserPrincipal;
                        User user = new User();
                        user.WithoutPassword(usr);

                        //roles
                        PrincipalSearchResult <Principal> groups = usr.GetAuthorizationGroups();
                        user.Roles = GetRoles(groups);
                        return(user);
                    }
                }
                return(null);
            }
            catch (Exception ex)
            {
                return(null);
            }
        }
コード例 #16
0
ファイル: Logon.aspx.cs プロジェクト: govtmirror/AWARE
        private List <GroupPrincipal> GetUserGroups(string userName)
        {
            List <GroupPrincipal> principleList = new List <GroupPrincipal>();

            PrincipalContext usersDomain = null;

            try
            {
                usersDomain = new PrincipalContext(ContextType.Domain);
            }
            catch (System.DirectoryServices.Protocols.LdapException ex)
            {
                usersDomain = new PrincipalContext(ContextType.Machine);
            }
            catch (PrincipalServerDownException ex)
            {
                usersDomain = new PrincipalContext(ContextType.Machine);
            }

            UserPrincipal userPrinc = UserPrincipal.FindByIdentity(usersDomain, userName);

            if (userPrinc != null)
            {
                PrincipalSearchResult <Principal> groups = userPrinc.GetAuthorizationGroups();
                foreach (Principal grp in groups)
                {
                    if (grp is GroupPrincipal)
                    {
                        principleList.Add((GroupPrincipal)grp);
                    }
                }
            }

            return(principleList);
        }
コード例 #17
0
        // Get which group they belong to
        public string getAuthorizationGrps(string userName)
        {
            List <string>    grps        = new List <string>();
            string           domain_name = GetSystemDomain();
            PrincipalContext context     = new PrincipalContext(ContextType.Domain, domain_name);;

            try
            {
                var currentUser = UserPrincipal.FindByIdentity(context, IdentityType.SamAccountName, userName);
                RevertToSelf();
                PrincipalSearchResult <Principal> groups = currentUser.GetGroups();
                IEnumerable <string> groupNames          = groups.Select(x => x.SamAccountName);
                foreach (var name in groupNames)
                {
                    grps.Add(name.ToString());
                }
                string groupLists = string.Join(", ", grps);
                return(groupLists);
            }
            catch (Exception ex)
            {
                string error = ex.ToString();
                return(error);
            }
        }
コード例 #18
0
ファイル: ScheduleViewModel.cs プロジェクト: Obilarius/APRS
        /// <summary>
        /// Wenn ein neuer User selektiert wird
        /// </summary>
        public void UserSelectionChanged()
        {
            // Erstellt eine neue Liste mit den neuen Infos
            UserInfos = new ObservableCollection <UserInfoEntry>
            {
                new UserInfoEntry("Name", SelectedUser.DisplayName),
                new UserInfoEntry("Email", SelectedUser.EmailAddress),
                new UserInfoEntry("Letzter Login", SelectedUser.LastLogon.ToString())
            };

            List <GroupPrincipal> tmpList = new List <GroupPrincipal>();;
            // Liest alle Gruppen aus in dennen der SelectedUser Mitglied ist
            PrincipalSearchResult <Principal> grp = SelectedUser.GetGroups();

            // Geht über alle Gruppen und fügt sie zur Liste hinzu
            foreach (var g in grp)
            {
                tmpList.Add(g as GroupPrincipal);
            }
            // Sortiert die Gruppen
            tmpList.Sort((x, y) => x.Name.CompareTo(y.Name));

            // Setzt SelectedUserGroups auf die Ausgelesene Liste
            SelectedUserGroups = new ObservableCollection <GroupPrincipal>(tmpList);
        }
コード例 #19
0
ファイル: frmSearchDialog.cs プロジェクト: ddmunhoz/Seeker
        private void fillListViewResults(PrincipalSearchResult <Principal> results)
        {
            foreach (var userResult in results)
            {
                ListViewItem user           = new ListViewItem();
                string       formatedFolder = "";
                if ((userResult.DistinguishedName != null) && (userResult.DistinguishedName != string.Empty))
                {
                    string userDN = userResult.DistinguishedName.Substring(userResult.DistinguishedName.IndexOf(',') + 1, userResult.DistinguishedName.Length - (userResult.DistinguishedName.IndexOf(',') + 1));
                    formatedFolder = userDN.Replace("CN=", string.Empty).Replace("DC=", string.Empty).Replace("OU=", string.Empty).Replace(",", "/");
                }

                if (lvResults.Items.Count % 2 != 0)
                {
                    user.BackColor = Color.White;
                }
                else
                {
                    user.BackColor = Color.WhiteSmoke;
                }
                user.Tag  = userResult.SamAccountName + "," + formatedFolder;
                user.Text = userResult.Name;
                user.SubItems.Add(userResult.SamAccountName);
                user.SubItems.Add(formatedFolder);
                lvResults.Items.Add(user);
            }
        }
コード例 #20
0
        public bool LoadDomainUser(string domainName, string domainUpn)
        {
            log.WriteLogEntry("Begin LoadUser...");
            bool       result = false;
            DomainUser user   = new DomainUser();

            log.WriteLogEntry(string.Format("Domain name {0} Domain UPN {1}", domainName, domainUpn));
            using (UserContext = new PrincipalContext(ContextType.Domain, domainName))
            {
                UserAccount = new UserPrincipal(UserContext)
                {
                    UserPrincipalName = domainUpn
                };
                using (PrincipalSearcher UserSearch = new PrincipalSearcher())
                {
                    UserSearch.QueryFilter = UserAccount;
                    using (PrincipalSearchResult <Principal> Psr = UserSearch.FindAll())
                    {
                        UserAccount         = (UserPrincipal)Psr.First <Principal>();
                        user.FirstName      = UserAccount.GivenName;
                        user.LastName       = UserAccount.Surname;
                        user.DomainUserName = UserAccount.SamAccountName;
                        user.DomainUpn      = UserAccount.UserPrincipalName;
                        user.UserEmail      = UserAccount.EmailAddress;
                        user.EmployeeID     = UserAccount.EmployeeId;
                        this.CurrentUser    = user;
                        result = true;
                    }
                }
            }
            log.WriteLogEntry("End LoadUser.");
            return(result);
        }
コード例 #21
0
        public List <GroupPrincipal> GetGroups(string userName)
        {
            List <GroupPrincipal> result = new List <GroupPrincipal>();

            // establish domain context
            PrincipalContext yourDomain = new PrincipalContext(ContextType.Domain);

            // find your user
            UserPrincipal user = UserPrincipal.FindByIdentity(yourDomain, userName);

            // if found - grab its groups
            if (user != null)
            {
                PrincipalSearchResult <Principal> groups = user.GetGroups();//user.GetAuthorizationGroups();

                // iterate over all groups
                foreach (Principal p in groups)
                {
                    // make sure to add only group principals
                    if (p is GroupPrincipal)
                    {
                        result.Add((GroupPrincipal)p);
                    }
                }
            }

            return(result);
        }
コード例 #22
0
        protected override Task HandleRequirementAsync(AuthorizationHandlerContext context, IntranetSecurityGroupRequirement requirement)
        {
            var username = context.User.Identity.Name;

            string domain = IPGlobalProperties.GetIPGlobalProperties().DomainName;

            using (var ctx = new PrincipalContext(ContextType.Domain, domain))
            {
                var user = UserPrincipal.FindByIdentity(ctx, username);

                if (user == null)
                {
                    return(Task.CompletedTask);
                }
                else
                {
                    PrincipalSearchResult <Principal> groups = user.GetAuthorizationGroups();

                    // iterate over all groups for user
                    foreach (GroupPrincipal group in groups)
                    {
                        if (requirement.IntranentSecurityGroup == group.Name)
                        {
                            context.Succeed(requirement);
                        }
                    }
                }
            }

            return(Task.CompletedTask);
        }
コード例 #23
0
ファイル: HomeController.cs プロジェクト: AlanDotson/onrr
        private List <GroupPrincipal> GetGroups(string userName)
        {
            var result = new List <GroupPrincipal>();
            var ctx    = GetContext();
            var user   = UserPrincipal.FindByIdentity(ctx, IdentityType.SamAccountName, userName);

            if (user != null)
            {
                PrincipalSearchResult <Principal> groups = user.GetGroups();

                var iterGroup = groups.GetEnumerator();
                using (iterGroup)
                {
                    while (iterGroup.MoveNext())
                    {
                        try
                        {
                            Principal p = iterGroup.Current;
                            result.Add((GroupPrincipal)p);
                        }
                        catch (PrincipalOperationException)
                        {
                            continue;
                        }
                    }
                }
            }

            return(result);
        }
コード例 #24
0
ファイル: Amass.cs プロジェクト: secau-perth/EDD
        public UserObject GetDomainUserInfo(string singledOutUser)
        {
            PrincipalContext insPrincipalContext = new PrincipalContext(ContextType.Domain);
            UserPrincipal    insUserPrincipal    = new UserPrincipal(insPrincipalContext);

            insUserPrincipal.Name = singledOutUser;
            PrincipalSearcher insPrincipalSearcher = new PrincipalSearcher();

            insPrincipalSearcher.QueryFilter = insUserPrincipal;
            PrincipalSearchResult <Principal> results = insPrincipalSearcher.FindAll();
            UserObject singleUser = new UserObject();

            foreach (Principal p in results)
            {
                singleUser.SamAccountName    = p.SamAccountName;
                singleUser.Name              = p.Name;
                singleUser.Description       = p.Description;
                singleUser.DistinguishedName = p.DistinguishedName;
                singleUser.SID = p.Sid.ToString();
                foreach (Principal groupName in p.GetGroups())
                {
                    singleUser.DomainGroups.Add(groupName.ToString());
                }
            }

            return(singleUser);
        }
コード例 #25
0
ファイル: AdminFinder.cs プロジェクト: NuvemNine/ravendb
            private static bool IsAdministratorNoCache(string username)
            {
                PrincipalContext ctx;

                try
                {
                    Domain.GetComputerDomain();
                    try
                    {
                        ctx = new PrincipalContext(ContextType.Domain);
                    }
                    catch (PrincipalServerDownException)
                    {
                        // can't access domain, check local machine instead
                        ctx = new PrincipalContext(ContextType.Machine);
                    }
                }
                catch (ActiveDirectoryObjectNotFoundException)
                {
                    // not in a domain
                    ctx = new PrincipalContext(ContextType.Machine);
                }
                var up = UserPrincipal.FindByIdentity(ctx, IdentityType.SamAccountName, username);

                if (up != null)
                {
                    PrincipalSearchResult <Principal> authGroups = up.GetAuthorizationGroups();
                    return(authGroups.Any(principal =>
                                          principal.Sid.IsWellKnown(WellKnownSidType.BuiltinAdministratorsSid) ||
                                          principal.Sid.IsWellKnown(WellKnownSidType.AccountDomainAdminsSid) ||
                                          principal.Sid.IsWellKnown(WellKnownSidType.AccountAdministratorSid) ||
                                          principal.Sid.IsWellKnown(WellKnownSidType.AccountEnterpriseAdminsSid)));
                }
                return(false);
            }
コード例 #26
0
 private static void PrintRoles(PrincipalSearchResult <Principal> roles)
 {
     foreach (var s in roles)
     {
         Print(string.Format("> {0}", s));
     }
 }
コード例 #27
0
        /// <summary>
        /// Find users by login ID, supports wild card search
        /// </summary>
        /// <param name="samAccountName"></param>
        /// <returns></returns>
        public List <ADUser> SearchUsersByLoginId(string samAccountName)
        {
            PrincipalSearchResult <Principal> result = null;
            List <ADUser> users = new List <ADUser>();

            string username = ConfigurationManager.AppSettings["ADUsername"];
            string password = ConfigurationManager.AppSettings["ADPassword"];

            using (PrincipalContext pc = new PrincipalContext(ContextType.Domain, null, username, password))
            {
                UserPrincipal filter = new UserPrincipal(pc);

                if (!string.IsNullOrEmpty(samAccountName))
                {
                    filter.SamAccountName = samAccountName;
                }

                PrincipalSearcher principalSearcher = new PrincipalSearcher(filter);

                result = principalSearcher.FindAll();

                foreach (UserPrincipal user in result)
                {
                    users.Add(PopulateADUserFields(user));
                }
            }

            return(users);
        }
コード例 #28
0
ファイル: frmLockout.cs プロジェクト: radtek/ADLockAudit
        private bool MemberEnumeration(Domain enumDomain)
        {
            Status("Enumerating member servers");
            try
            {
                PrincipalContext  _pContext   = new PrincipalContext(ContextType.Domain, enumDomain.Name);
                ComputerPrincipal _cPrincipal = new ComputerPrincipal(_pContext);
                PrincipalSearcher _pSearcher  = new PrincipalSearcher();

                _cPrincipal.Name       = "*";
                _pSearcher.QueryFilter = _cPrincipal;

                PrincipalSearchResult <Principal> _pResults = _pSearcher.FindAll();
                foreach (ComputerPrincipal _member in _pResults)
                {
                    if (!checkNode(_DomainControllers, $"{_member.Name}.{enumDomain.Name}"))
                    {
                        _MemberServers.Nodes.Add($"{_member.Name}.{enumDomain.Name}").Tag = _member;
                    }
                }
            }
            catch (Exception _ex)
            {
                Status($"Error enumerating member services - PROVIDE TO SUPPORT - UNKNKOWN ({_ex.GetType().Name}:{_ex.HResult})");
                return(false);
            }
            Status("Enumerated member servers");
            return(true);
        }
コード例 #29
0
        private ClaimsIdentity CreateIdentity(UserPrincipal userPrincipal)
        {
            var identity = new ClaimsIdentity(MyAuthentication.ApplicationCookie, ClaimsIdentity.DefaultNameClaimType, ClaimsIdentity.DefaultRoleClaimType);

            identity.AddClaim(new Claim("http://schemas.microsoft.com/accesscontrolservice/2010/07/claims/identityprovider", "Active Directory"));
            identity.AddClaim(new Claim(ClaimTypes.Name, userPrincipal.SamAccountName));
            identity.AddClaim(new Claim(ClaimTypes.NameIdentifier, userPrincipal.SamAccountName));
            identity.AddClaim(new Claim(ClaimTypes.GivenName, userPrincipal.GivenName));
            identity.AddClaim(new Claim(ClaimTypes.Surname, userPrincipal.Surname));
            if (!String.IsNullOrEmpty(userPrincipal.EmailAddress))
            {
                identity.AddClaim(new Claim(ClaimTypes.Email, userPrincipal.EmailAddress));
            }

            //try
            //{
            PrincipalSearchResult <Principal> groups = userPrincipal.GetGroups();

            foreach (var @group in groups)
            {
                identity.AddClaim(new Claim(ClaimTypes.Role, @group.Name));
            }

            // add your own claims if you need to add more information stored on the cookie

            return(identity);
            //}
            //catch (Exception exception)
            //{
            //return identity;

            //}
        }
コード例 #30
0
        /// <summary>
        /// Returns a list of AD groups a user is a member of
        /// </summary>
        /// <param name="domain"></param>
        /// <param name="username"></param>
        /// <returns></returns>
        private static List <string> GetUsersGroups(string domain, string username)
        {
            List <string> returnMe = new List <string>();

            using (PrincipalContext pc = new PrincipalContext(ContextType.Domain, domain))
            {
                using (UserPrincipal user = UserPrincipal.FindByIdentity(pc, username))
                {
                    if (user != null)
                    {
                        PrincipalSearchResult <Principal> groups = user.GetAuthorizationGroups();

                        foreach (Principal p in groups)
                        {
                            if (p is GroupPrincipal)
                            {
                                returnMe.Add(p.SamAccountName.ToLower());
                            }
                        }
                    }
                }
            }

            return(returnMe);
        }
コード例 #31
0
        // https://stackoverflow.com/questions/3679579/check-for-groups-a-local-user-is-a-member-of/3681442#3681442
        public static List <string> GetUserGroups(string sUserName, string domain)
        {
            List <string> myItems = new List <string>();

            try
            {
                if (Checks.Checks.IsCurrentUserLocal && domain != Checks.Checks.CurrentUserDomainName)
                {
                    return(myItems); //If local user and other domain, do not look
                }

                UserPrincipal oUserPrincipal = GetUser(sUserName, domain);
                if (oUserPrincipal != null)
                {
                    PrincipalSearchResult <Principal> oPrincipalSearchResult = oUserPrincipal.GetGroups();
                    foreach (Principal oResult in oPrincipalSearchResult)
                    {
                        myItems.Add(oResult.Name);
                    }
                }
                else
                {
                    Beaprint.GrayPrint("  [-] Controlled exception, info about " + domain + "\\" + sUserName + " not found");
                }
            }
            catch (Exception ex)
            {
                Beaprint.PrintException(ex.Message);
            }
            return(myItems);
        }
コード例 #32
0
ファイル: PrincipalSearcher.cs プロジェクト: nickchal/pash
		private PrincipalSearchResult<Principal> FindAll(bool returnOne)
		{
			int num;
			if (this.qbeFilter != null)
			{
				if (this.qbeFilter.unpersisted)
				{
					if (!this.HasReferentialPropertiesSet())
					{
						StoreCtx queryCtx = this.ctx.QueryCtx;
						PrincipalSearcher principalSearcher = this;
						if (returnOne)
						{
							num = 1;
						}
						else
						{
							num = -1;
						}
						ResultSet resultSet = queryCtx.Query(principalSearcher, num);
						PrincipalSearchResult<Principal> principals = new PrincipalSearchResult<Principal>(resultSet);
						return principals;
					}
					else
					{
						throw new InvalidOperationException(StringResources.PrincipalSearcherNonReferentialProps);
					}
				}
				else
				{
					throw new InvalidOperationException(StringResources.PrincipalSearcherPersistedPrincipal);
				}
			}
			else
			{
				throw new InvalidOperationException(StringResources.PrincipalSearcherMustSetFilter);
			}
		}
コード例 #33
0
ファイル: AdGroup.cs プロジェクト: UAResLife/AdApiService
        public static List<string> GetAdGroupSamAccountNames(PrincipalSearchResult<Principal> groups)
        {
            List<string> results = new List<string>();

            foreach (Principal p in groups)
            {
                results.Add(p.SamAccountName);
            }

            return results;
        }
コード例 #34
0
ファイル: PrincipalSearcher.cs プロジェクト: chcosta/corefx
        private PrincipalSearchResult<Principal> FindAll(bool returnOne)
        {
            GlobalDebug.WriteLineIf(GlobalDebug.Info, "PrincipalSearcher", "Entering FindAll, returnOne=" + returnOne.ToString());

            if (_qbeFilter == null)
                throw new InvalidOperationException(StringResources.PrincipalSearcherMustSetFilter);
            // Double-check that the Principal isn't persisted.  We don't allow them to assign a persisted
            // Principal as the filter, but they could have persisted it after assigning it to the QueryFilter
            // property.
            if (!_qbeFilter.unpersisted)
                throw new InvalidOperationException(StringResources.PrincipalSearcherPersistedPrincipal);

            // Validate the QBE filter: make sure it doesn't have any non-scalar properties set.
            if (HasReferentialPropertiesSet())
                throw new InvalidOperationException(StringResources.PrincipalSearcherNonReferentialProps);

            GlobalDebug.WriteLineIf(GlobalDebug.Info, "PrincipalSearcher", "FindAll: qbeFilter is non-null and passes");

            ResultSet resultSet = _ctx.QueryCtx.Query(this, returnOne ? 1 : -1);

            PrincipalSearchResult<Principal> fr = new PrincipalSearchResult<Principal>(resultSet);
            return fr;
        }