public void DisplayNameIsLoadedOnSearch()
 {
     using (searchRoot = new DirectoryEntry())
     using (sut = new PrincipalSearcher(searchRoot))
     {
         Assert.IsTrue(sut.PropertiesToLoad.Contains("displayName"));
     }
 }
 public void MemberPropertyIsLoadedOnSearch()
 {
     using (searchRoot = new DirectoryEntry())
     using (sut = new PrincipalSearcher(searchRoot))
     {
         Assert.IsTrue(sut.PropertiesToLoad.Contains("Member"));
     }
 }
 public virtual IReadOnlyCollection<IPrincipal> SearchPrincipals(string ldapFilter, ICollection<string> additionalPropertyNames = null)
 {
     using (DirectoryEntry domainEntry = new DirectoryEntry(domainPath.GetPathWithProtocol()))
     using (PrincipalSearcher searcher = new PrincipalSearcher(domainEntry, additionalPropertyNames))
     {
         return searcher.FindPrincipals(ldapFilter);
     }
 }
 public virtual IPrincipal GetPrincipal(string accountName, ICollection<string> additionalPropertyNames = null)
 {
     using (DirectoryEntry domainEntry = new DirectoryEntry(domainPath.GetPathWithProtocol()))
     using (PrincipalSearcher searcher = new PrincipalSearcher(domainEntry, additionalPropertyNames))
     {
         return searcher.FindPrincipal(accountName);
     }
 }
 public void AdditionalPropertiesAreLoadedOnSearch()
 {
     var properties = new[] { "Prop1", "Prop2" };
     
     using (searchRoot = new DirectoryEntry())
     using (sut = new PrincipalSearcher(searchRoot, properties))
     {
         Assert.IsTrue(sut.PropertiesToLoad.Contains("Prop1"));
         Assert.IsTrue(sut.PropertiesToLoad.Contains("Prop2"));
     }
 }
        public virtual IReadOnlyCollection<IPrincipal> GetGroupMembers(string groupName, bool recursive, ICollection<string> additionalPropertyNames = null)
        {
            List<IPrincipal> result = new List<IPrincipal>();

            using (DirectoryEntry domainEntry = new DirectoryEntry(domainPath.GetPathWithProtocol()))
            using (PrincipalSearcher principalSearcher = new PrincipalSearcher(domainEntry))
            {
                Principal groupPrincipal = principalSearcher.FindPrincipal(groupName);
                result.AddRange(ResolveMembers(groupPrincipal, recursive, additionalPropertyNames));
            }

            return result;
        }
示例#7
0
        // TODO: update to search in domain of logged-in user
        public static String GetActiveDirectoryUserEmail(string domainQualifiedSAMAccountName, LoginViewModel clientId)
        {
            var    splitUserName  = domainQualifiedSAMAccountName.Split(new char[] { '\\' });
            var    samAccountName = splitUserName[splitUserName.Length - 1];
            String email          = null;

            try
            {
                logger.Debug("Find users and groups in domain of " + clientId.UserName);
                PrincipalContext adController = new PrincipalContext(ContextType.Domain, clientId.DomainName, clientId.UserName, clientId.Password);


                // Could be a user or a group:
                UserPrincipal user = new UserPrincipal(adController);
                user.SamAccountName = samAccountName;
                PrincipalSearcher usrSrch          = new PrincipalSearcher(user);
                Principal         userSearchResult = usrSrch.FindOne();

                if (userSearchResult == null)
                {
                    GroupPrincipal grp = new GroupPrincipal(adController);
                    grp.SamAccountName = samAccountName;
                    PrincipalSearcher grpSrch = new PrincipalSearcher(grp);
                    userSearchResult = grpSrch.FindOne();
                }

                if (userSearchResult == null)
                {
                    logger.Error("Could not find Principal in AD for " + domainQualifiedSAMAccountName);
                    return(email);
                }

                DirectoryEntry dirEntry = (DirectoryEntry)userSearchResult.GetUnderlyingObject();
                // TODO:  is this property guaranteed to be present, e.g. if I create a user called donall, will the email property still be present?
                email = dirEntry.Properties["mail"] == null ? null : (string)(dirEntry.Properties["mail"].Value);

                if (email == null)
                {
                    logger.Info("No email for user" + domainQualifiedSAMAccountName);
                }
            }
            catch (System.Exception ex)
            {
                var errmsg = "Problem searching for users. Details: " + ex.Message;
                logger.Error(errmsg);
            }
            return(email);
        }
        public async Task <IActionResult> ConfirmReset(IFormCollection form)
        {
            if (form["new"] == form["repeat"] && !string.IsNullOrEmpty(form["new"]))
            {
                Alue71UserPrincipal model = new Alue71UserPrincipal(_context);
                model.SamAccountName = form["account"];

                PrincipalSearcher   searcher = new PrincipalSearcher(model);
                Alue71UserPrincipal user     = (Alue71UserPrincipal)searcher.FindOne();

                if (_DbContext.Resets.Count(r => r.code == form["code"]) == 1)
                {
                    try
                    {
                        user.SetPassword(form["new"]);
                        ViewBag.message = "Salasana vaihdettu";
                        _DbContext.Resets.Remove(_DbContext.Resets.First(r => r.code == form["code"]));
                        await _DbContext.SaveChangesAsync();

                        return(RedirectToAction("Index"));
                    }
                    catch (Exception ex)
                    {
                        ViewBag.message = ex.Message;
                        return(View(new PasswordReset()
                        {
                            code = form["code"], user = form["account"]
                        }));
                    }
                }
                else
                {
                    ViewBag.message = "Virheellinen koodi";
                    return(View(new PasswordReset()
                    {
                        code = form["code"], user = form["account"]
                    }));
                }
            }
            else
            {
                ViewBag.message = "Tarkista salasana";
                return(View(new PasswordReset()
                {
                    code = form["code"], user = form["account"]
                }));
            }
        }
示例#9
0
        public override ResultWrangler ProcessQuery()
        {
            if (this._authenticator?.State != AuthState.Authorised)
            {
                this._returnwrangler = null;
                return(null);
            }

            //Now go through the management objects return from WMI, and add the relevant values to the wrangler.
            //New sublists are created for each management object in the wrangler.
            try
            {
                if (this._processed == true)
                {
                    this._processingwrangler = this._processingwrangler.Clone();
                }

                using (PrincipalContext context = new PrincipalContext(ContextType.Domain, this._authenticator.Domain, this._baseou, this._authenticator.UsernameSource.Username, this._authenticator.PasswordSource.Password))
                {
                    GroupPrincipal groups = new GroupPrincipal(context, "*");
                    using (PrincipalSearcher ps = new PrincipalSearcher(groups))
                    {
                        PrincipalSearchResult <Principal> groupresults = ps.FindAll();
                        foreach (Principal group in groupresults)
                        {
                            this.AddPropertiesToWrangler(this._processingwrangler, group, this._propertyTemplates);
                        }
                    }
                }
            }
            catch (Exception e)
            {
                //throw new TsGuiKnownException("Active Directory OU query caused an error", e.Message);
                LoggerFacade.Warn("Active Directory OU groups query caused an error: " + e.Message);
            }

            this._processed = true;
            if (this.ShouldIgnore(this._processingwrangler.GetString()) == false)
            {
                this._returnwrangler = this._processingwrangler;
            }
            else
            {
                this._returnwrangler = null;
            }

            return(this._returnwrangler);
        }
示例#10
0
        void ListUsersDomain()
        {
            //string[] bn = {"otel", "zver"};

            // var
            lstAdUsers = new List <Users>();
            try
            {
                using (var context = new PrincipalContext(ContextType.Domain, Properties.Settings.Default.Domain))// "vents.local"
                {
                    using (var searcher = new PrincipalSearcher(new UserPrincipal(context)))
                    {
                        foreach (var result in searcher.FindAll())
                        {
                            var directoryEntry = result.GetUnderlyingObject() as DirectoryEntry;
                            var objSurveyUsers = new Users();//name   //samAccountName
                            if (directoryEntry != null)
                            {
                                objSurveyUsers.AccountName  = (String)directoryEntry.Properties["samAccountName"].Value;
                                objSurveyUsers.FullUserName = (String)directoryEntry.Properties["displayName"].Value;
                                //objSurveyUsers.FullUserName =  Convert.ToInt32( directoryEntry.Properties["userAccountControl"].Value).ToString();
                                //objSurveyUsers.FullUserName = (String)directoryEntry.Properties["Mail"].Value;
                            }
                            lstAdUsers.Add(objSurveyUsers);
                            //comboBoxOfUsers.Items.Add((String)de.Properties["displayName"].Value);
                        }
                    }
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
            }
            // ListBox rr= new ListBox();
            UsersList.ItemsSource       = lstAdUsers;
            UsersList.Columns[0].Header = "";
            UsersList.Columns[1].Header = "Имя входа"; UsersList.Columns[1].IsReadOnly = true;
            UsersList.Columns[0].CheckAccess(); // UsersList.Columns[1].SortDirection = ListSortDirection.Ascending;
            UsersList.Columns[2].Header = "Полное имя"; UsersList.Columns[2].IsReadOnly = true;
            UsersList.SelectedIndex     = 0;

            //rr.ItemsSource = lstAdUsers;
            //rr.C.Columns[0].Header = "";
            //rr.Columns[1].Header = "Имя входа"; UsersList.Columns[1].IsReadOnly = true;
            //rr.Columns[0].CheckAccess(); // UsersList.Columns[1].SortDirection = ListSortDirection.Ascending;
            //rr.Columns[2].Header = "Полное имя"; UsersList.Columns[2].IsReadOnly = true;
            //rr.SelectedIndex = 0;
        }
示例#11
0
        protected void Page_Load(object sender, EventArgs e)
        {
            try
            {
                string WantedUser = "******";
                //userathtml.Text = Context.User.Identity;
                #region
                string UserNAmes = "";

                using (var context = new PrincipalContext(ContextType.Domain, "nmc-uk.net"))
                {
                    using (var searcher = new PrincipalSearcher(new UserPrincipal(context)))
                    {
                        int cnt = 1;
                        foreach (var result in searcher.FindAll())
                        {
                            DirectoryEntry de = result.GetUnderlyingObject() as DirectoryEntry;
                            WantedUser += (string)de.Properties["givenName"].Value + "/";
                            //Console.WriteLine("First Name: " + de.Properties["givenName"].Value);
                            //Console.WriteLine("SAM account name   : " + de.Properties["samAccountName"].Value);
                            //Console.WriteLine("User principal name: " + de.Properties["userPrincipalName"].Value);
                            //Console.WriteLine();
                            //cnt++;
                        }
                        //UNAMe.Text = UserNAmes;
                        Email.Text = "akjhlghasdgeagrhtrhtrhtrhtrgh";
                        // Console.WriteLine("Total users: " + cnt);
                    }
                }
                #endregion
                IPrincipal p = Thread.CurrentPrincipal;
                IIdentity  i = Thread.CurrentPrincipal.Identity;

                // WantedUser += "UNbyGetCurrUser : "******"<br/>UNbyUser : "******"<br/>UserByUserIdentity : " + User.Identity.Name + "";
                // WantedUser += "<br/>HttpContext.Current.User : "******"<br/> HttpContext.Current.Request.LogonUserIdentity : " + user;
                // WantedUser += "<br/>" + "Thread.CurrentPrincipal.Identity Identity Name: " + i.Name + " <br/>Thread.CurrentPrincipal.Identity.Name :  " + p.Identity.Name;
                UNAMe.Text = WantedUser;
            }
            catch (Exception ex)
            {
                Error.Text = ex.Message;
            }
        }
示例#12
0
            public ReadOnlyCollection <string> Groups()
            {
                PrincipalSearcher principalSearcher = new PrincipalSearcher()
                {
                    QueryFilter = new GroupPrincipal(new PrincipalContext(this._Context))
                };
                PrincipalSearchResult <Principal> principals = principalSearcher.FindAll();
                List <string> strs = new List <string>();

                foreach (Principal principal in principals)
                {
                    strs.Add(principal.SamAccountName);
                }
                strs.Sort();
                return(new ReadOnlyCollection <string>(strs));
            }
示例#13
0
 /// <summary>
 /// Поиск идентификатора группы отдела
 /// </summary>
 /// <param name="nameGroup">Наименование группы</param>
 /// <returns></returns>
 private string FindIdentytyGroup(string nameGroup)
 {
     using (var domain = new GroupPrincipal(new PrincipalContext(ContextType.Domain, "regions.tax.nalog.ru", PathDomainGroup)))
     {
         domain.Description = nameGroup;
         using (var searcher = new PrincipalSearcher(domain))
         {
             var group = searcher.FindOne() as GroupPrincipal;
             if (group != null)
             {
                 return(group.Name);
             }
         }
     }
     return(null);
 }
示例#14
0
        /// <summary>
        /// Gets standard flow
        /// </summary>
        /// <param name="domainName"></param>
        /// <param name="xName"></param>
        /// <param name="newFilterPrincipal"></param>
        /// <param name="ActiveDirectoryUsers"></param>
        /// <returns></returns>
        internal static ICollection <ActiveDirectoryUser> standardFlow(string domainName, string xName, DomainsManager.NewFilterPrincipal newFilterPrincipal, ConcurrentDictionary <string, ActiveDirectoryUser> ActiveDirectoryUsers)
        {
            PrincipalContext principalContext = new PrincipalContext(ContextType.Domain, domainName);

            using (PrincipalSearcher principalSearcher = new PrincipalSearcher((Principal)newFilterPrincipal(principalContext, xName)))
            {
                foreach (UserPrincipal userPrincipal in principalSearcher.FindAll())
                {
                    if (!ActiveDirectoryUsers.ContainsKey(userPrincipal.Sid.Value))
                    {
                        ActiveDirectoryUsers.TryAdd(userPrincipal.Sid.Value, new ActiveDirectoryUser(principalContext.Name, userPrincipal));
                    }
                }
            }
            return(ActiveDirectoryUsers.Values);
        }
示例#15
0
 public IEnumerable <UserPrincipal> GetAllUsers()
 {
     using (var ctx = _directoryContext.LoadAndConnect())
     {
         // Only load users with a display name and valid email addresses
         var filter = new UserPrincipal(ctx)
         {
             DisplayName = "*", EmailAddress = "*@*"
         };
         using (var search = new PrincipalSearcher(filter))
         {
             var users = search.FindAll().OfType <UserPrincipal>();
             return(users.ToList());
         }
     }
 }
示例#16
0
        private SavoniaUserPrincipal FindUserByUsername(string username)
        {
            var context = GetSearchRoot();
            // search model
            SavoniaUserPrincipal up = new SavoniaUserPrincipal(context);

            up.SamAccountName = username;

            // search
            PrincipalSearcher    search = new PrincipalSearcher(up);
            SavoniaUserPrincipal result = (SavoniaUserPrincipal)search.FindOne();

            search.Dispose();

            return(result);
        }
示例#17
0
        private void ListUsers()
        {
            UserPrincipal ObjectUserPrincipal = new UserPrincipal(insPrincipalContext);

            ObjectUserPrincipal.Name = "*";
            PrincipalSearcher ObjectPrincipalSearcher = new PrincipalSearcher();

            ObjectPrincipalSearcher.QueryFilter = ObjectUserPrincipal;
            PrincipalSearchResult <Principal> SearchResults = ObjectPrincipalSearcher.FindAll();

            ADUsersComboBox.Items.Clear();
            foreach (Principal p in SearchResults)
            {
                ADUsersComboBox.Items.Add(p);
            }
        }
示例#18
0
        //if you want to get all Groups of Specific OU you have to add OU Name in Context
        public static List <ADGroup> GetallGroups()
        {
            List <ADGroup> AdGroups        = new List <ADGroup>();
            var            ctx             = new PrincipalContext(ContextType.Domain, "MBS", "OU=DevOU,DC=MBS,DC=com");
            GroupPrincipal _groupPrincipal = new GroupPrincipal(ctx);

            PrincipalSearcher srch = new PrincipalSearcher(_groupPrincipal);

            foreach (var found in srch.FindAll())
            {
                AdGroups.Add(new ADGroup {
                    GroupName = found.ToString()
                });
            }
            return(AdGroups);
        }
示例#19
0
        private void button1_Click(object sender, EventArgs e)
        {
            PrincipalContext ctx = new PrincipalContext(ContextType.Machine);

            // define a "query-by-example" principal - here, we search for a GroupPrincipal
            GroupPrincipal qbeGroup = new GroupPrincipal(ctx);

            // create your principal searcher passing in the QBE principal
            PrincipalSearcher srch = new PrincipalSearcher(qbeGroup);

            // find all matches
            foreach (var found in srch.FindAll())
            {
                // do whatever here - "found" is of type "Principal" - it could be user, group, computer.....
            }
        }
示例#20
0
 /// <summary>
 /// Проверка компьютера в домене есть или нет
 /// </summary>
 /// <param name="nameComputer">Имя компьютера</param>
 /// <returns></returns>
 private bool IsCheckComputer(string nameComputer)
 {
     using (var computer = new ComputerPrincipal(new PrincipalContext(ContextType.Domain)))
     {
         computer.Name = nameComputer;
         using (var searcher = new PrincipalSearcher(computer))
         {
             var user = searcher.FindOne() as ComputerPrincipal;
             if (user != null)
             {
                 return(true);
             }
         }
     }
     return(false);
 }
示例#21
0
 public void Test()
 {
     using (var users = new UserPrincipal(new PrincipalContext(ContextType.Domain)))
     {
         users.SamAccountName = "7751-00-451";
         using (var searcher = new PrincipalSearcher(users))
         {
             if (searcher.FindOne() is UserPrincipal user)
             {
                 var fullPath = user.DistinguishedName.Replace("\\", "").Split(',').Where(x => x.Contains("OU=")).Reverse().Aggregate(
                     (element, next) => element + (string.IsNullOrWhiteSpace(element) ? string.Empty : "/") + next).Replace("OU=", "");
                 //return fullPath;
             }
         }
     }
 }
示例#22
0
        private Principal SearchForComputer(string computerName)
        {
            ComputerPrincipal computerQuery = new ComputerPrincipal(GetLdapPrincipalContext());

            computerQuery.Name = computerName;

            PrincipalSearcher searchForComputer = new PrincipalSearcher(computerQuery);
            Principal         searchResult      = searchForComputer.FindOne();

            if (searchResult != null)
            {
                return(searchResult);
            }

            throw new ObjectNotFoundException("Could not find computer with name: " + computerName);
        }
示例#23
0
        public List <User> GetMatchingUsersFromDomain(string searchString)
        {
            try
            {
                List <User>        userList = new List <User>();
                TodoItemRepository repo     = new TodoItemRepository();
                using (var pc = new PrincipalContext(ContextType.Domain, _domain))
                {
                    UserPrincipal qbeUser = new UserPrincipal(pc);
                    qbeUser.DisplayName = string.Format("*{0}*", searchString);
                    PrincipalSearcher srch = new PrincipalSearcher(qbeUser);
                    foreach (var found in srch.FindAll())
                    {
                        UserPrincipal user = (found as UserPrincipal);
                        if (user != null)
                        {
                            //Infusion hack: remove users that start with ext- or that have - or _ in their username
                            if (user.SamAccountName.Contains("-") || user.SamAccountName.Contains("_"))
                            {
                                continue;
                            }
                            User dbUser = repo.Query <User>().FirstOrDefault(u => u.Username == user.SamAccountName);
                            if (dbUser == null)
                            {
                                dbUser = new DomanUserLoginProvider(_domain).CreateUser(user.SamAccountName);
                                if (!string.IsNullOrEmpty(dbUser.Firstname) && !string.IsNullOrEmpty(dbUser.Lastname) && !string.IsNullOrEmpty(dbUser.Username))
                                {
                                    repo.Add <User>(dbUser);
                                }
                            }
                            if (!string.IsNullOrEmpty(dbUser.Firstname) && !string.IsNullOrEmpty(dbUser.Lastname) && !string.IsNullOrEmpty(dbUser.Username))
                            {
                                userList.Add(dbUser);
                            }
                        }
                    }
                }

                repo.SaveChanges();
                return(userList);
            }
            catch (Exception ex)
            {
                Log.Error("Cannot connect to domain", ex);
                return(null);
            }
        }
示例#24
0
 private static void DownloadAdsGroups()
 {
     using (var context = new OnlineFilesEntities())
         using (PrincipalContext ctx = new PrincipalContext(ContextType.Domain))
             using (var groupPrincipal = new GroupPrincipalEx(ctx))
                 using (PrincipalSearcher search = new PrincipalSearcher(groupPrincipal))
                 {
                     int max = search.FindAll().Count();
                     int c   = 0;
                     foreach (var gp in search.FindAll().Select(found => found as GroupPrincipalEx))
                     {
                         Console.WriteLine("Processing " + c + " of " + max);
                         c++;
                         if (gp != null)
                         {
                             if (gp.IsSecurityGroup != true && gp.GroupScope == GroupScope.Local)
                             {
                                 continue;
                             }
                             var so = context.SecurityObjects.FirstOrDefault(d => d.ActiveDirectoryId == gp.Guid);
                             if (so == null)
                             {
                                 so = new SecurityObject
                                 {
                                     ActiveDirectoryId = gp.Guid,
                                     FullName          = gp.Name,
                                     Username          = gp.SamAccountName,
                                     EmailAddress      = gp.EmailAddress ?? "",
                                     IsGroup           = true,
                                     LastLogInOn       = DateTime.Now,
                                     IsActive          = true,
                                     HomeFolder        = null
                                 };
                                 context.SecurityObjects.Add(so);
                             }
                             else
                             {
                                 so.IsGroup      = true;
                                 so.FullName     = gp.Name;
                                 so.Username     = gp.SamAccountName;
                                 so.EmailAddress = gp.EmailAddress ?? "";
                             }
                         }
                         context.SaveChanges();
                     }
                 }
 }
        public async Task <TaskResult> CreateAsync(User user)
        {
            // get DB user
            var dbUser = await _context.User.FirstOrDefaultAsync(i => i.EmailAddress == user.EmailAddress);

            if (dbUser != null)
            {
                return(dbUser.IsActive
                    ? new TaskResult(false, "The user exits and is active")
                    : new TaskResult(false, "The exists but is inactive"));
            }

            // get AD user
            UserPrincipal adUser;

            using (var adContext = new PrincipalContext(ContextType.Domain, _activeDirectorySettings.Domain))
                using (var searcher = new PrincipalSearcher())
                {
                    searcher.QueryFilter = new UserPrincipal(adContext)
                    {
                        EmailAddress = user.EmailAddress
                    };
                    adUser = (UserPrincipal)searcher.FindOne();
                }

            if (adUser == null)
            {
                new TaskResult(false, "The AD user not found");
            }
            if (adUser.Enabled == false)
            {
                new TaskResult(false, "The AD user is not active");
            }

            // add DB User if needed
            await _context.User.AddAsync(new DbUser()
            {
                FirstName    = user.FirstName,
                LastName     = user.LastName,
                EmailAddress = user.EmailAddress,
                IsActive     = true
            });

            await _context.SaveChangesAsync();

            return(new TaskResult(true));
        }
        /// <summary>
        /// Get a group in a principal context
        /// </summary>
        /// <param name="groupName">The group name or identifier</param>
        /// <param name="pc">The principal context</param>
        /// <returns></returns>
        private static GroupPrincipal FindGroup(string groupName, PrincipalContext pc)
        {
            GroupPrincipal    group;
            PrincipalSearcher searcher;

            var parsedName = new FqdnNameParser(groupName);

            // Search by SamGroupName
            if (!string.IsNullOrWhiteSpace(parsedName.SamAccountName))
            {
                group = new GroupPrincipal(pc);
                group.SamAccountName = parsedName.SamAccountName;
                searcher             = new PrincipalSearcher(group);
                group = searcher.FindOne() as GroupPrincipal;

                if (group != null)
                {
                    return(group);
                }
            }

            // Search by name (original approach, backwards compatiblity)
            if (!string.IsNullOrWhiteSpace(parsedName.SamAccountName))
            {
                group      = new GroupPrincipal(pc);
                group.Name = parsedName.SamAccountName;
                searcher   = new PrincipalSearcher(group);
                group      = searcher.FindOne() as GroupPrincipal;

                if (group != null)
                {
                    return(group);
                }
            }

            if (parsedName.Sid != null)
            {
                group = GroupPrincipal.FindByIdentity(pc, IdentityType.Sid, parsedName.Sid.ToString());

                if (group != null)
                {
                    return(group);
                }
            }

            return(null);
        }
示例#27
0
        /// <summary>
        /// Создает список локальных или доменных пользователей
        /// </summary>
        /// <param name="contextType">Значение перечисления ContextType - задает расположение учетных записей: Локальная или Доменная</param>
        /// <param name="OUName">Название Organizational Unit для доменных учетных записей</param>
        public List <WindowsAccount> GetUsers(PrincipalContext context, string prefix)
        {
            using var searcher = new PrincipalSearcher(new UserPrincipal(context));

            try
            {
                return(searcher
                       .FindAll()
                       .Select(x => new WindowsAccount(x.Name, $"{prefix}\\{x.SamAccountName}", x.Sid.ToString()))
                       .OrderBy(x => x.Name)
                       .ToList());
            }
            catch
            { }

            return(new List <WindowsAccount>());
        }
        public IList <ExternalSecurityGroup> FindGroups(string name)
        {
            if (!configurationStore.GetAreSecurityGroupsEnabled())
            {
                return(new List <ExternalSecurityGroup>());
            }

            var    results = new List <ExternalSecurityGroup>();
            string domain;
            string username;

            credentialNormalizer.NormalizeCredentials(name, out username, out domain);
            using (var context = contextProvider.GetContext(domain))
            {
                var searcher = new PrincipalSearcher();
                searcher.QueryFilter = new GroupPrincipal(context)
                {
                    Name = name + "*"
                };

                var iterGroup = searcher.FindAll().GetEnumerator();
                using (iterGroup)
                {
                    while (iterGroup.MoveNext())
                    {
                        try
                        {
                            var p = iterGroup.Current as GroupPrincipal;
                            if (p == null || !(p.IsSecurityGroup ?? false))
                            {
                                continue;
                            }

                            results.Add(new ExternalSecurityGroup {
                                Id = p.Sid.ToString(), DisplayName = p.Name
                            });
                        }
                        catch (NoMatchingPrincipalException)
                        {
                        }
                    }
                }
            }

            return(results.OrderBy(o => o.DisplayName).ToList());
        }
示例#29
0
        /// <summary>
        /// Retourne les informations pour un nom de groupe.
        /// </summary>
        /// <param name="groupName"></param>
        /// <returns></returns>
        public Task <List <GroupPrincipal> > GetGroupsByName(string groupName)
        {
            return(Task.Factory.StartNew(() =>
            {
                GroupPrincipal groupPrincipal = new GroupPrincipal(_adConnection);
                groupPrincipal.Name = groupName;


                PrincipalSearcher searcher = new PrincipalSearcher(groupPrincipal);
                searcher.QueryFilter = groupPrincipal;


                var result = searcher.FindAll().Cast <GroupPrincipal>();

                return result.ToList();
            }));
        }
        public List <ActiveDirectoryUsersVM> GetAllActiveUsers(string EmployeeName = "")
        {
            ActivDirectoryusers = new List <ActiveDirectoryUsersVM>();
            UserPrincipal userPrincipal = new UserPrincipal(Context);

            //UserService sUser = null;
            //SystemUsers = sUser.UserAccount();

            using (var searcher = new PrincipalSearcher(userPrincipal))
            {
                foreach (var result in searcher.FindAll())
                {
                    DirectoryEntry de = result.GetUnderlyingObject() as DirectoryEntry;

                    string aDEmployeeName = de.Properties["cn"].Value.ToString();
                    string aDuserName     = de.Properties["sAMAccountName"].Value.ToString();
                    string email          = "";

                    if (de.Properties["mail"] != null &&

                        de.Properties["mail"].Count > 0)
                    {
                        email = de.Properties["mail"].Value.ToString();
                    }



                    //bool isAvaliable = false;
                    //int ID = 0;
                    //var EmployeeInfo = SystemUsers.Where(s => s.UserName.Contains(aDuserName));

                    //if (EmployeeInfo.Select(s => s.UserName).Any())
                    //{
                    //    isAvaliable = true;
                    //    ID = EmployeeInfo.Select(s => s.ID).First();
                    //}
                    ActivDirectoryusers.Add(new ActiveDirectoryUsersVM()
                    {
                        Name = aDEmployeeName, Email = email
                    });
                }
            }
            SaveEmployeesData(ActivDirectoryusers.ToList());

            return(ActivDirectoryusers.ToList());
        }
示例#31
0
        public Principal findUser(People person)
        {
            Principal        user;
            PrincipalContext ouContex = new PrincipalContext(ContextType.Domain,
                                                             Domain,
                                                             "*****@*****.**",
                                                             "Rrhh1234");

            ouContex.ValidateCredentials("ADMNALRRHH", "Rrhh1234");
            UserPrincipal up = new UserPrincipal(ouContex);

            up.EmployeeId = person.CUNI;
            PrincipalSearcher ps = new PrincipalSearcher(up);

            user = (UserPrincipal)ps.FindOne();
            return(user);
        }
示例#32
0
        /// <summary>
        /// This method retrieves the list of users using the specified SearchFilter durin
        /// the last number of days from the date that this is called on.
        /// </summary>
        /// <param name="day">The number of days to go back on and check to see what users
        /// were created during this time frame.</param>
        /// <returns></returns>
        public List <ADUser> GetUsersByCriteria(AdvancedSearchFilter filter, DateTime day)
        {
            List <ADUser> users = new List <ADUser>();

            using (PrincipalContext context = new PrincipalContext(ContextType.Domain, ServerName, null, ContextOptions.Negotiate, ServiceUser, ServicePassword))
            {
                using (ADUser userFilter = new ADUser(context))
                {
                    switch (filter)
                    {
                    case AdvancedSearchFilter.DateCreated:
                        userFilter.MyAdvancedFilters.CreatedInTheLastDays(day, MatchType.GreaterThanOrEquals);
                        break;

                    case AdvancedSearchFilter.WhenChanged:
                        userFilter.MyAdvancedFilters.WhenChangedInLastDays(day, MatchType.GreaterThanOrEquals);
                        break;

                    default:
                        break;
                    }

                    using (PrincipalSearcher searcher = new PrincipalSearcher(userFilter))
                    {
                        ((DirectorySearcher)searcher.GetUnderlyingSearcher()).PageSize = 1000;
                        var searchResults = searcher.FindAll().ToList();

                        foreach (Principal user in searchResults)
                        {
                            ADUser usr = user as ADUser;

                            // We are filtering out users who don't have a first name
                            // Though this has the issue of filtering out accounts
                            if (String.IsNullOrEmpty(usr.GivenName))
                            {
                                continue;
                            }

                            users.Add(usr);
                        }
                    }
                }
            }

            return(users.OrderByDescending(u => u.WhenChanged).ToList());
        }
示例#33
0
        public object Main()
        {
            PrincipalContext context = new PrincipalContext(ContextType.Domain, "YOURDOMAIN", "OU=Ingegneria,DC=xxx,DC=xxx");

            //Searching for a UserPrincipal
            UserPrincipal demoUser = new UserPrincipal(context);

            demoUser.GivenName = "s*";


            // creating your principal searcher
            PrincipalSearcher srch = new PrincipalSearcher(demoUser);

            var result = srch.FindAll();

            return(result);
        }
示例#34
0
 private void buttonX1_Click(object sender, EventArgs e)
 {
     using (var context = new PrincipalContext(ContextType.Domain, textBoxX1.Text))
     {
         using (var searcher = new PrincipalSearcher(new UserPrincipal(context)))
         {
             foreach (var result in searcher.FindAll())
             {
                 DirectoryEntry de = result.GetUnderlyingObject() as DirectoryEntry;
                 richTextBox1.AppendText("First Name: " + de.Properties["givenName"].Value);
                 richTextBox1.AppendText("Last Name : " + de.Properties["sn"].Value);
                 richTextBox1.AppendText("SAM account name   : " + de.Properties["samAccountName"].Value);
                 richTextBox1.AppendText("User principal name: " + de.Properties["userPrincipalName"].Value);
             }
         }
     }
 }
示例#35
0
        public IHttpActionResult GetUsers(HttpRequestMessage request)
        {
            IEnumerable <string> headerValues = request.Headers.GetValues("App");
            var id  = headerValues.FirstOrDefault();
            int cnt = 0;

            if (id == "CryoLife App")
            {
                var           context = new PrincipalContext(ContextType.Domain, "cryolife.com");
                UserPrincipal qbeUser = new UserPrincipal(context);
                qbeUser.Enabled = true; //only enabled users
                // qbeUser.PasswordNeverExpires = false; //not ALWAYS service accounts !!
                //qbeUser.GivenName = "Steve";
                PrincipalSearcher srch = new PrincipalSearcher(qbeUser);
                //IMPORTANT
                // set the PageSize on the underlying DirectorySearcher to get all entries
                ((DirectorySearcher)srch.GetUnderlyingSearcher()).PageSize = 500;

                foreach (UserPrincipal result in srch.FindAll())
                {
                    if (
                        result != null &&
                        result.DisplayName != null &&
                        result.EmailAddress != null &&
                        result.GivenName != null &&
                        result.GivenName != result.DisplayName
                        )
                    {
                        cnt++;
                        userNames.Add(
                            new ADUser()
                        {
                            ADFullName     = result.Name,
                            ADEmailAddress = result.EmailAddress
                        }
                            );
                    }
                }
                //SORT THIS INFORMATION
                List <ADUser> SortedList = userNames.OrderBy(o => o.ADFullName).ToList();

                return(Ok(SortedList));
            }

            return(NotFound());
        }
        private Principal GetPrincipalForLogon(string racfId, PrincipalContext principal = null)
        {
            var principalContext = principal ?? new PrincipalContext(ContextType.Domain,
                                                                     Properties.Settings.Default.ActiveDirectoryDomain,
                                                                     Properties.Settings.Default.ADContainer);

            var userQuery = new UserPrincipal(principalContext)
            {
                SamAccountName = racfId
            };
            var principalSearcher = new PrincipalSearcher {
                QueryFilter = userQuery
            };
            var searchResults = principalSearcher.FindOne();

            return(searchResults);
        }