Beispiel #1
0
        /// <summary>
        /// takes list of names of AD Groups and returns info(members etc.) about them
        /// </summary>
        /// <param name="domain"></param>
        /// <param name="group"></param>
        /// <returns></returns>
        static public List <AGroup> getGroupUsers3(List <string> ADgroups)
        {
            List <AGroup> allUsers = new List <AGroup>();

            foreach (string currGroup in ADgroups)
            {
                Console.Write("\n Reading group: " + currGroup + " ...");
                List <User>    members = new List <User>();
                GroupPrincipal grp     = GroupPrincipal.FindByIdentity(principalContext, currGroup);
                if (grp == null)
                {
                    Console.WriteFormatted("\n\t!!!Cannot read group: " + currGroup + " >> passing", Color.Red); continue;
                }
                List <User> gr1   = new List <User>();
                List <User> gr2   = new List <User>();
                var         users = GetGroupMembersName(currGroup);
                //List<Principal> users = grp.GetMembers(true).ToList();
                var task1 = Task.Factory.StartNew(() => gr1 = extractUsers(0, users.Count() / 2, users));
                var task2 = Task.Factory.StartNew(() => gr2 = extractUsers(users.Count() / 2, users.Count(), users));
                Task.WaitAll(task1, task2);
                members.AddRange(gr1);
                members.AddRange(gr2);
                allUsers.Add(new AGroup(members, currGroup));
                grp.Dispose();
                //showList(members, currGroup);
            }
            principalContext.Dispose();
            return(allUsers);
        }
        public static IEnumerable <string> GetUsers(string groupName)
        {
            var members = new Collection <string>();

            using (var ctx = new PrincipalContext(ContextType.Domain, PrincipalHelper.DOMAIN_OFINA))
            {
                GroupPrincipal grp = null;

                try
                {
                    grp = GroupPrincipal.FindByIdentity(ctx, IdentityType.Name, groupName);

                    if (grp == null)
                    {
                        throw new InvalidOperationException(
                                  "We did not find that group in that domain, perhaps the group resides in a different domain?");
                    }
                    else
                    {
                        foreach (var p in grp.GetMembers(true))
                        {
                            members.Add(p.SamAccountName);
                        }
                    }
                }
                finally
                {
                    grp?.Dispose();
                }
            }

            return(members);
        }
        public void GroupPrincipalConstructorTest()
        {
            GroupPrincipal group = new GroupPrincipal(domainContext);

            group.Dispose();
            Assert.Inconclusive("TODO: Implement code to verify target");
        }
Beispiel #4
0
        public void Delete(string groupName)
        {
            GroupPrincipal gp = null;

            try
            {
                if (string.IsNullOrEmpty(groupName))
                {
                    throw new MissingFieldException("Users", "groupName");
                }

                log.DebugFormat("Attempting to delete group {0}", groupName);

                pc = GetPrincipalContext();
                gp = GroupPrincipal.FindByIdentity(pc, IdentityType.Name, groupName);
                if (gp == null)
                {
                    throw new NoMatchingPrincipalException(groupName);
                }

                gp.Delete();
            }
            catch (Exception ex)
            {
                log.ErrorFormat("Error deleting group {0}. Exception: {1}", groupName, ex.ToString());
                throw;
            }
            finally
            {
                if (gp != null)
                {
                    gp.Dispose();
                }
            }
        }
        private bool IsMemberOfADGroup(string userName, string groupName)
        {
            bool isMember = false;

            //List<string> grpMembers = new List<string>();

            using (PrincipalContext context = new PrincipalContext(ContextType.Domain))
            {
                //UserPrincipal user = UserPrincipal.FindByIdentity(context, IdentityType.SamAccountName, sUserName);
                GroupPrincipal group = GroupPrincipal.FindByIdentity(context, IdentityType.Name, groupName);

                if (group != null)
                {
                    foreach (Principal p in group.GetMembers(true))
                    {
                        if (p.SamAccountName.ToUpper() == userName.ToUpper())
                        {
                            isMember = true; break;
                        }
                    }
                }
                group.Dispose();
            }
            return(isMember);
        }
Beispiel #6
0
        public List <String> QueryADGroupMembers(String sGroup)
        {
            List <String> ListADGroupMembers = new List <String>();

            try
            {
                PrincipalContext ctx    = new PrincipalContext(ContextType.Domain, domain);
                GroupPrincipal   grpObj = GroupPrincipal.FindByIdentity(ctx, IdentityType.Name, sGroup);

                if (grpObj != null)
                {
                    foreach (Principal p in grpObj.GetMembers(true))
                    {
                        String sObjName = p.SamAccountName.ToString().Trim();
                        if (sObjName.Substring(sObjName.Length - 1, 1) == "$")
                        {
                            sObjName = sObjName.Substring(0, sObjName.Length - 1);
                        }
                        ListADGroupMembers.Add(sObjName);
                    }
                    grpObj.Dispose();
                    ctx.Dispose();
                }
                return(ListADGroupMembers);
            }
            catch (Exception ex)
            {
                WriteBuffer("Error source: QueryADGroupMembers()" + " " + ex.Message);
                return(ListADGroupMembers);
            }
        }
Beispiel #7
0
        /// <summary>
        /// Returns a list of Users for a specified group.
        /// </summary>
        /// <param name="groupName">The name of the active directory group.</param>
        /// <returns></returns>
        public List <string> ListUsersForGroup(string groupName)
        {
            string        _groupName = string.Empty;
            List <string> _members   = new List <string>();

            // Retrieve the Group principal object for the group you need.
            // This will verify that the group exists on the specific domain.  If gp = null, then it did not find that group.
            _groupName = groupName.ToString();
            GroupPrincipal gp = GroupPrincipal.FindByIdentity(_myContext, _groupName);

            if (gp != null)
            {
                foreach (Principal p in gp.GetMembers(true))
                {
                    _members.Add(p.SamAccountName.ToString());
                }
            }

            if (gp != null)
            {
                gp.Dispose();
            }

            return(_members);
        }
Beispiel #8
0
        /// <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);
        }
Beispiel #9
0
        //Retrieve all groups
        public List <string> GetADGroupsList()
        {
            List <string>    adGroups = new List <string>();
            PrincipalContext context  = GetContext();

            if (context != null)
            {
                GroupPrincipal groups = new GroupPrincipal(context);
                //searcher to search groups
                PrincipalSearcher searcher = new PrincipalSearcher(groups);
                foreach (var found in searcher.FindAll())
                {
                    DirectoryEntry deFound = (DirectoryEntry)found.GetUnderlyingObject() as DirectoryEntry;
                    if ((int)deFound.Properties["samAccountType"].Value == 536870912)
                    {
                        Console.WriteLine("Groups is Alias Object (BuiltIn) and will not be aded to list.");
                    }
                    else
                    {
                        adGroups.Add(found.ToString());
                    }
                }
                adGroups.Sort();
                groups.Dispose();
                searcher.Dispose();
                context.Dispose();
            }
            return(adGroups);
        }
Beispiel #10
0
        public static bool AddUserToGroup(string samAccountName, string groupName, AdAdminConfig config)
        {
            if (IfUserExist(samAccountName, config))
            {
                if (!IfUserExistInGroup(samAccountName, groupName, config))
                {
                    try
                    {
                        PrincipalContext ctx = new PrincipalContext(ContextType.Domain,
                                                                    config.ServerIpOrDomain,
                                                                    config.AdminAccount,
                                                                    config.AdminPwd);
                        // find the group in question
                        GroupPrincipal group = GroupPrincipal.FindByIdentity(ctx, groupName);
                        UserPrincipal  user  = UserPrincipal.FindByIdentity(ctx, samAccountName);
                        group.Members.Add(user);
                        group.Save();
                        group.Dispose();
                        user.Dispose();
                        ctx.Dispose();
                    }
                    catch (Exception ex)
                    {
                        return(false);
                    }

                    return(true);
                }

                return(false);
            }

            return(false);
        }
        /// <summary>
        ///  Makes user with given login name member of group with given name if exists.
        /// </summary>
        /// <param name="groupName">group name</param>
        public void AssignUserGroup(string loginName, string groupName)
        {
            // Find user entry by login name
            UserPrincipal userEntry = UserPrincipal.FindByIdentity(activeDirectoryDomain,
                                                                   IdentityType.SamAccountName,
                                                                   loginName);

            // Search for group with matching name
            PrincipalSearchResult <Principal> activeDirectoryGroups = this.ListGroupsByName(
                this.activeDirectoryDomain, groupName);

            if (activeDirectoryGroups.Count <Principal>() != 0)
            {
                GroupPrincipal group = (GroupPrincipal)activeDirectoryGroups.First <Principal>();

                // make user member of group
                group.Members.Add(userEntry);

                // save changes
                group.Save();
                group.Dispose();
            }
            else
            {
                // throw exception to notify the group does not exists
                throw new ApplicationException("Domain group not found.");
            }

            // dispose the objects
            userEntry.Dispose();
            activeDirectoryGroups.Dispose();
        }
Beispiel #12
0
        public static List <string> GetADSecurityGroupUsers(String sgAlias)
        {
            List <string> userList = new List <string>();

            using (PrincipalContext ctx = new PrincipalContext(ContextType.Domain))
            {
                GroupPrincipal grp = GroupPrincipal.FindByIdentity(ctx, sgAlias);

                if (grp != null)
                {
                    foreach (Principal p in grp.GetMembers(true))
                    {
                        userList.Add(p.SamAccountName);
                        Console.WriteLine(p.SamAccountName);
                    }
                    grp.Dispose();
                    ctx.Dispose();
                }
                else
                {
                    Console.WriteLine("\nWe did not find that group in that domain, perhaps the group resides in a different domain?");
                }
            }

            return(userList);
        }
        public static bool IsUserGroupMember(string userPrincipalName, string groupname, PrincipalContext context)
        {
            GroupPrincipal group = GroupPrincipal.FindByIdentity(context, groupname);

            bool foundUser = false;

            foreach (var member in group.GetMembers(true))
            {
                try
                {
                    if (member.SamAccountName.Equals(userPrincipalName))
                    {
                        foundUser = true;
                        break;
                    }
                }
                catch (Exception)
                {
                    foundUser = false;
                }
            }

            group.Dispose();
            return(foundUser);
        }
        private void EscalateReturn_Load(object sender, EventArgs e)
        {
            string groupName  = "Domain Users";
            string domainName = "192.168.10.5";

            //get AD users
            PrincipalContext ctx = new PrincipalContext(ContextType.Domain, domainName);
            GroupPrincipal   grp = GroupPrincipal.FindByIdentity(ctx, IdentityType.SamAccountName, groupName);

            try
            {
                foreach (Principal p in grp.GetMembers(false))
                {
                    if (p.DisplayName != null)
                    {
                        comboBox1.Items.Add(p.DisplayName);
                    }
                }
                grp.Dispose();
                ctx.Dispose();
            }
            catch
            {
                MessageBox.Show("Server not available. Check internet connection");
            }
            comboBox1.Sorted = true;
        }
        public void ADGetUsersInGroup(string strGroup, List <string> listUserNames)
        {
            try
            {
                PrincipalContext ctx = new PrincipalContext(ContextType.Domain, this.Domain);
                GroupPrincipal   grp = GroupPrincipal.FindByIdentity(ctx, IdentityType.Name, strGroup);

                if (grp != null)
                {
                    foreach (Principal p in grp.GetMembers(true))
                    {
                        listUserNames.Add(p.SamAccountName);
                    }
                    grp.Dispose();
                    ctx.Dispose();
                }
                else
                {
                    MessageBox.Show("The group [" + strGroup + "] was not found in the Active Direcotry.", "ADGetUsersInGroup(): Error Connecting to Active Directory");
                }
            }
            catch (System.Exception x)
            {
                Jrfc.Exception.HandleException(x);
            }
        }
Beispiel #16
0
        private void btnEditGroup_Click(object sender, EventArgs e)
        {
            if (lbGroups.SelectedItem == null)
            {
                MessageBox.Show("Please select a group");
                return;
            }
            GroupPrincipal insGroupPrincipal = (GroupPrincipal)lbGroups.SelectedItem;
            frmProperties  insFrmProperties  = new frmProperties(insGroupPrincipal, ActionTypes.Save);

            insFrmProperties.ShowDialog();
            if (insFrmProperties.DialogResult == DialogResult.OK)
            {
                try
                {
                    insGroupPrincipal.Save();
                    insGroupPrincipal.Dispose();
                    MessageBox.Show("Group updated.");
                }
                catch (Exception ex)
                {
                    MessageBox.Show(ex.Message);
                }

                ListGroups();
            }
        }
Beispiel #17
0
        /// <summary>
        /// Ajout un utilisateur dans un groupe donné.
        /// </summary>
        /// <param name="groupName"></param>
        /// <param name="user"></param>
        public void AddUserToGroup(string groupName, UserPrincipal user)
        {
            try
            {
                GroupPrincipal group = GroupPrincipal.FindByIdentity(_adConnection, IdentityType.Name, groupName);

                if (group != null)
                {
                    if (!group.Members.Contains(user))
                    {
                        Logger?.Info("Ajout de " + user.Name + " dans le groupe " + groupName);
                        group.Members.Add(user);
                        group.Save();
                        group.Dispose();
                    }
                    else
                    {
                        Logger?.Warn(user.Name + " est déjà dans le groupe " + groupName);
                        throw new UserExistInGroupException(user.Name + " est déjà dans le groupe " + groupName);
                    }
                }
                else
                {
                    Logger?.Warn("Le groupe : " + groupName + " n'existe pas !");
                    throw new GroupActiveDirectoryNotExistException("Le groupe : " + groupName + " n'existe pas !");
                }
            }
            catch (Exception exception)
            {
                Logger?.Error("Error AddUserToGroup - groupName : " + groupName
                              + " - userName : " + user.Name, exception);

                throw;
            }
        }
Beispiel #18
0
        /// <summary>
        /// Provides the domain user full details.
        /// </summary>
        /// <param name="domainName">Name of the domain.</param>
        /// <returns></returns>
        public static DataSet ProvideDomainUserFullDetails(string domainName, string sessionID, string userSource, string defaultDepartment, string fullNameAttribute)
        {
            DataSet UsersList = new DataSet();

            UsersList.Tables.Add();
            UsersList.Tables[0].Columns.Add("REC_SYSID", typeof(string));
            UsersList.Tables[0].Columns.Add("USER_ID", typeof(string));
            UsersList.Tables[0].Columns.Add("SESSION_ID", typeof(string));
            UsersList.Tables[0].Columns.Add("USR_SOURCE", typeof(string));
            UsersList.Tables[0].Columns.Add("USR_ROLE", typeof(string));
            UsersList.Tables[0].Columns.Add("DOMAIN", typeof(string));
            UsersList.Tables[0].Columns.Add("FIRST_NAME", typeof(string));
            UsersList.Tables[0].Columns.Add("LAST_NAME", typeof(string));
            UsersList.Tables[0].Columns.Add("EMAIL", typeof(string));
            UsersList.Tables[0].Columns.Add("RESIDENCE_ADDRESS", typeof(string));
            UsersList.Tables[0].Columns.Add("COMPANY", typeof(string));
            UsersList.Tables[0].Columns.Add("STATE", typeof(string));
            UsersList.Tables[0].Columns.Add("COUNTRY", typeof(string));
            UsersList.Tables[0].Columns.Add("PHONE", typeof(string));
            UsersList.Tables[0].Columns.Add("EXTENSION", typeof(string));
            UsersList.Tables[0].Columns.Add("FAX", typeof(string));
            UsersList.Tables[0].Columns.Add("DEPARTMENT", typeof(string));
            UsersList.Tables[0].Columns.Add("USER_NAME", typeof(string));
            UsersList.Tables[0].Columns.Add("CN", typeof(string));
            UsersList.Tables[0].Columns.Add("DISPLAY_NAME", typeof(string));
            UsersList.Tables[0].Columns.Add("FULL_NAME", typeof(string));
            UsersList.Tables[0].Columns.Add("C_DATE", typeof(string));
            UsersList.Tables[0].Columns.Add("REC_ACTIVE", typeof(string));
            UsersList.Tables[0].Columns.Add("AD_PIN", typeof(string));
            UsersList.Tables[0].Columns.Add("AD_CARD", typeof(string));

            string cardValue = "";
            string pinValue  = "";

            int valuesCount          = 0;
            PrincipalContext context = new PrincipalContext(ContextType.Domain, domainName);
            GroupPrincipal   group   = GroupPrincipal.FindByIdentity(context, IdentityType.SamAccountName, Constants.DOMAIN_USERS);

            if (group != null)
            {
                foreach (Principal principal in group.GetMembers(false))
                {
                    string userName = principal.SamAccountName;

                    string department = "";
                    if (string.IsNullOrEmpty(department))
                    {
                        department = defaultDepartment;
                    }


                    UsersList.Tables[0].Rows.Add(valuesCount, principal.SamAccountName, sessionID, userSource, "User", domainName, principal.Name, "", principal.UserPrincipalName, "", "", "", "", "", "", "", department, userName, "", principal.DisplayName, principal.SamAccountName, DateTime.Now.ToString(), "True", pinValue, cardValue);
                    valuesCount++;
                }
                group.Dispose();
                context.Dispose();
            }
            return(UsersList);
        }
Beispiel #19
0
        static void ReaadAD()
        {
            string groupName = "Domain Admins";

            Console.Write("Domain: ");
            string domainName = Console.ReadLine();

            Console.Write("Username: "******"Password: "******"";

            GroupPrincipal grp = GroupPrincipal.FindByIdentity(ctx, IdentityType.SamAccountName, groupName);

            if (grp != null)
            {
                foreach (Principal p in grp.GetMembers(false))
                {
                    Console.WriteLine(p.SamAccountName + " - " + p.DisplayName);
                }


                grp.Dispose();

                //Console.ReadLine();
            }
            else
            {
                Console.WriteLine("\nWe did not find that group in that domain, perhaps the group resides in a different domain?");
                //Console.ReadLine();
            }

            // define a "query-by-example" principal - here, we search for a GroupPrincipal


            UserPrincipal qbeGroup = new UserPrincipal(ctx);

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

            // find all matches
            foreach (UserPrincipal found in srch.FindAll())
            {
                Console.WriteLine(found.Name);

                foreach (GroupPrincipal g in found.GetGroups(ctx))
                {
                    Console.WriteLine("\t{0}", g.Name);
                }

                // do whatever here - "found" is of type "Principal" - it could be user, group, computer.....
            }
        }
Beispiel #20
0
        public List <User> GetUsers(string groupName)
        {
            GroupPrincipal grp = null;

            List <User> users = new List <User>();

            try
            {
                log.DebugFormat("Attempting to retrieve all users that are a direct member of {0}", groupName);

                pc  = GetPrincipalContext();
                grp = GroupPrincipal.FindByIdentity(pc, IdentityType.Name, groupName);
                if (grp == null)
                {
                    throw new NoMatchingPrincipalException(groupName);
                }
                else
                {
                    log.DebugFormat("Found group {0}... Now attempting to retrieve direct members that are users.", groupName);
                    foreach (var obj in grp.GetMembers(false))
                    {
                        log.DebugFormat("Found object {0} of objectClass {1} when retrieving users from {2}", obj.Name, obj.StructuralObjectClass, groupName);

                        if (obj.StructuralObjectClass.IndexOf("user") >= 0)
                        {
                            log.DebugFormat("Object {0} is a user! Adding to our list.", obj.Name);
                            DirectoryEntry userDE = obj.GetUnderlyingObject() as DirectoryEntry;
                            users.Add(new User()
                            {
                                UserGuid          = (Guid)userDE.Properties["objectGUID"].Value,
                                UserPrincipalName = userDE.Properties["UserPrincipalName"].Value.ToString(),
                                Name        = userDE.Properties["Name"].Value.ToString(),
                                DisplayName = userDE.Properties["DisplayName"].Value.ToString()
                            });
                        }
                        else
                        {
                            log.DebugFormat("Object {0} was skipped since it was not a user", obj.Name);
                        }
                    }
                }

                return(users);
            }
            catch (Exception ex)
            {
                log.ErrorFormat("Error retrieving users that are a member of group {0}. Exception: {1}", groupName, ex.ToString());
                throw;
            }
            finally
            {
                if (grp != null)
                {
                    grp.Dispose();
                }
            }
        }
Beispiel #21
0
        //lage ny gruppe
        public bool CreateGroup()
        {
            PrincipalContext ctx = new PrincipalContext(ContextType.Domain, "testdomene.local", "OU=Groups,OU=TEST,DC=testdomene,DC=local");

            GroupPrincipal group = GroupPrincipal.FindByIdentity(ctx, Groupname);

            if (group != null)
            {
                MessageBox.Show("Gruppen finnes allerede i domenet");
                return(false);
            }

            GroupPrincipal grp = new GroupPrincipal(ctx);

            if (Groupname != null && Groupname.Length > 0)
            {
                grp.Name = Groupname;
            }

            if (desc != null && desc.Length > 0)
            {
                grp.Description = desc;
            }

            grp.SamAccountName = "g-" + Groupname;

            grp.GroupScope = (System.DirectoryServices.AccountManagement.GroupScope)Enum.Parse(typeof(GroupScope), GroupScope);

            try
            {
                grp.Save();
            }
            catch (Exception e)
            {
                MessageBox.Show("Kunne ikke opprette gruppen: " + e);
                grp.Dispose();
                return(false);
            }


            grp.Dispose();

            return(true);
        }
Beispiel #22
0
        /// <summary>
        /// Removes a member from a group
        /// </summary>
        /// <param name="groupName"></param>
        /// <param name="objectToRemove"></param>
        /// <param name="objectIdentityType"></param>
        public void RemoveMember(string groupName, string objectToRemove, string objectIdentityType)
        {
            PrincipalContext pc = null;
            GroupPrincipal   gp = null;

            try
            {
                // Replace whitespaces
                groupName      = groupName.Replace(" ", string.Empty);
                objectToRemove = objectToRemove.Replace(" ", string.Empty);

                this.logger.Debug("Attempting to remove " + objectToRemove + " from group " + groupName);

                pc = new PrincipalContext(ContextType.Domain, this.domainController, this.username, this.password);
                gp = GroupPrincipal.FindByIdentity(pc, IdentityType.Name, groupName);
                if (gp != null)
                {
                    this.logger.Debug("Checking to see if " + groupName + " already contains " + objectToRemove + " as a member.");
                    bool isMember = gp.Members.Contains(pc, GetIdentityType(objectIdentityType), objectToRemove);

                    if (isMember)
                    {
                        gp.Members.Remove(pc, GetIdentityType(objectIdentityType), objectToRemove);
                        gp.Save();

                        this.logger.Info("Successfully removed " + objectToRemove + " from group " + groupName);
                    }
                    else
                    {
                        this.logger.Debug("Object " + objectToRemove + " is already not a member of group " + groupName);
                    }
                }
                else
                {
                    throw new Exception("Unable to find the group " + groupName + " in the system.");
                }
            }
            catch (Exception ex)
            {
                this.logger.Error("Error removing member " + objectToRemove + " to group " + groupName, ex);

                throw;
            }
            finally
            {
                if (pc != null)
                {
                    pc.Dispose();
                }

                if (gp != null)
                {
                    gp.Dispose();
                }
            }
        }
Beispiel #23
0
        public Boolean contains(string username)
        {
            // Check grouplist is fresh
            if (groupmtime != File.GetLastWriteTimeUtc(pathgroups))
            {
                ReadInGroupsFile();
            }
            // if the groups file is empty then we always check the passwords
            if (grouplist.Count == 0)
            {
                writeLog("No groups found. User's password will be validated.", EventLogEntryType.Information);
                return(true);
            }

            PrincipalContext ctx      = null;
            GroupPrincipal   groupCtx = null;

            ctx = new System.DirectoryServices.AccountManagement.PrincipalContext(ContextType.Domain);

            foreach (String groupname in grouplist)
            {
                //writeLog("trying [" + groupname + "]", EventLogEntryType.Information);
                groupCtx = GroupPrincipal.FindByIdentity(ctx, groupname);
                if (groupCtx != null)
                {
                    //writeLog("found [" + groupCtx.ToString() + "]. Finding members", EventLogEntryType.Information);
                    foreach (Principal user in groupCtx.GetMembers(true))
                    {
                        if (user.SamAccountName == username)
                        {
                            writeLog("User " + username + " is in restricted group " + groupname + " and their password will be validated.", EventLogEntryType.Information);
                            ctx.Dispose();
                            groupCtx.Dispose();
                            return(true);
                        }
                    }
                    groupCtx.Dispose();
                }
            }
            ctx.Dispose();
            writeLog("User " + username + " is not in a restricted group", EventLogEntryType.Information);
            return(false);
        }
Beispiel #24
0
        /// <summary>
        /// Agrega un grupo dados su nombre y descripción
        /// </summary>
        /// <param name="nombre">Nombre del grupo</param>
        /// <param name="descripción">Descripción del grupo</param>
        public void AgregarGrupo(string nombre, string descripción)
        {
            GroupPrincipal nuevoGrupo = new GroupPrincipal(_dominio);

            nuevoGrupo.Name        = nombre;
            nuevoGrupo.Description = descripción;

            nuevoGrupo.Save();
            nuevoGrupo.Dispose();
        }
Beispiel #25
0
        /// <summary>
        /// Adds access rights to the OU for a specific group
        /// </summary>
        /// <param name="ouDistinguishedName"></param>
        /// <param name="groupName"></param>
        public void AddAccessRights(string ouDistinguishedName, string groupName)
        {
            DirectoryEntry   de = null;
            PrincipalContext pc = null;
            GroupPrincipal   gp = null;

            try
            {
                de = new DirectoryEntry("LDAP://" + this.domainController + "/" + ouDistinguishedName, this.username, this.password);
                pc = new PrincipalContext(ContextType.Domain, this.domainController, this.username, this.password);

                // Search for the group
                gp = GroupPrincipal.FindByIdentity(pc, IdentityType.Name, groupName.Replace(" ", string.Empty));
                if (gp == null)
                {
                    throw new Exception("Unable to find the group  " + groupName + " in the system.");
                }
                else
                {
                    // Add Read Property
                    de.ObjectSecurity.AddAccessRule(new ActiveDirectoryAccessRule(gp.Sid, ActiveDirectoryRights.ReadProperty, AccessControlType.Allow));

                    // Add List Object
                    de.ObjectSecurity.AddAccessRule(new ActiveDirectoryAccessRule(gp.Sid, ActiveDirectoryRights.ListObject, AccessControlType.Allow));

                    // Deny List Content
                    de.ObjectSecurity.AddAccessRule(new ActiveDirectoryAccessRule(gp.Sid, ActiveDirectoryRights.ListChildren, AccessControlType.Deny));

                    de.CommitChanges();
                }
            }
            catch (Exception ex)
            {
                this.logger.Error("Failed to add access rights to organizational unit " + ouDistinguishedName + " for group " + groupName, ex);

                throw;
            }
            finally
            {
                if (gp != null)
                {
                    gp.Dispose();
                }

                if (pc != null)
                {
                    pc.Dispose();
                }

                if (de != null)
                {
                    de.Dispose();
                }
            }
        }
        public void GroupPrincipalConstructorTest()
        {
            if (DomainContext == null)
            {
                return;
            }

            GroupPrincipal group = new GroupPrincipal(DomainContext);

            group.Dispose();
        }
        public void AddRights(string distinguishedName, string groupName)
        {
            GroupPrincipal gp = null;

            try
            {
                if (string.IsNullOrEmpty(distinguishedName))
                {
                    throw new MissingFieldException("OrganizationalUnit", "DistinguishedName");
                }

                if (string.IsNullOrEmpty(groupName))
                {
                    throw new MissingFieldException("OrganizationalUnit", "GroupName");
                }

                log.DebugFormat("Adding rights to {0}", distinguishedName);

                de = GetDirectoryEntry(distinguishedName);
                pc = GetPrincipalContext();

                string nospaceGroup = groupName.Replace(" ", string.Empty);
                log.DebugFormat("Attempting to find group {0}", nospaceGroup);

                gp = GroupPrincipal.FindByIdentity(pc, IdentityType.Name, nospaceGroup);
                de.ObjectSecurity.AddAccessRule(
                    new ActiveDirectoryAccessRule(gp.Sid, ActiveDirectoryRights.ReadProperty, AccessControlType.Allow, ActiveDirectorySecurityInheritance.All));

                de.ObjectSecurity.AddAccessRule(
                    new ActiveDirectoryAccessRule(gp.Sid, ActiveDirectoryRights.ListObject, AccessControlType.Allow, ActiveDirectorySecurityInheritance.All));

                de.ObjectSecurity.AddAccessRule(
                    new ActiveDirectoryAccessRule(gp.Sid, ActiveDirectoryRights.ListChildren, AccessControlType.Deny, ActiveDirectorySecurityInheritance.All));

                de.CommitChanges();
                log.InfoFormat("Successfully adding access rights to {0} for group {1}", distinguishedName, nospaceGroup);
            }
            catch (Exception ex)
            {
                log.ErrorFormat("Error adding rights for {0} to {1}. Exception: {2}", groupName, distinguishedName, ex.ToString());
                throw;
            }
            finally
            {
                if (gp != null)
                {
                    gp.Dispose();
                }
            }
        }
        /// <summary>
        /// Verifies that user is a part of the specified group.
        /// </summary>
        public static bool IsUserInGroup(string username, string groupname)
        {
            PrincipalContext mPrincipalContext = new PrincipalContext(ContextType.Domain, APPSETTINGS.AD_Domain);

            var foundUserInGroup = false;

            GroupPrincipal mGroupPrincipal = null;

            try
            {
                mGroupPrincipal = GroupPrincipal.FindByIdentity(mPrincipalContext, groupname);
            }
            catch (Exception ex)
            {
                throw ex;
            }

            if (mGroupPrincipal != null)
            {
                foreach (var member in mGroupPrincipal.GetMembers(true))
                {
                    try
                    {
                        if (member.SamAccountName.Equals(username))
                        {
                            foundUserInGroup = true;

                            break;
                        }
                    }
                    catch (Exception ex)
                    {
                        throw ex;
                    }
                }
            }

            if (mGroupPrincipal != null)
            {
                mGroupPrincipal.Dispose();
            }

            if (mPrincipalContext != null)
            {
                mPrincipalContext.Dispose();
            }

            return(foundUserInGroup);
        }
        private void AddUserToGroup(ADUser postUser, UserPrincipal newUser)
        {
            GroupPrincipal groupPrincipal = GroupPrincipal.FindByIdentity(RootSearchContext, postUser.Unit);

            if (groupPrincipal == null)
            {
                throw new Exception("Group doesn't exists");
            }
            else
            {
                groupPrincipal.Members.Add(newUser);
                groupPrincipal.Save();
                groupPrincipal.Dispose();
            }
        }
Beispiel #30
0
        /// <summary>
        /// Retire un utilisateur dans un groupe donné.
        /// </summary>
        /// <param name="groupName"></param>
        /// <param name="userName"></param>
        public void RemoveUserToGroup(string groupName, string userName)
        {
            try
            {
                GroupPrincipal group = GroupPrincipal.FindByIdentity(_adConnection, IdentityType.Name, groupName);

                if (group != null)
                {
                    UserPrincipal user = GetUserPrincipal(userName);
                    if (user != null)
                    {
                        if (group.Members.Contains(user))
                        {
                            Logger?.Info("Suppresion de " + userName + " du groupe " + groupName);

                            group.Members.Remove(user);
                            group.Save();
                            group.Dispose();
                        }
                        else
                        {
                            Logger?.Warn(userName + " n'est pas dans le groupe " + groupName);
                            throw new UserNotInGroupException(userName + " n'est pas dans le groupe " + groupName);
                        }
                    }
                    else
                    {
                        Logger?.Warn("L'utilisateur : " + userName + " n'existe pas !");
                        throw new UserNotExistException("L'utilisateur : " + userName + " n'existe pas !");
                    }
                }
                else
                {
                    Logger?.Warn("Le groupe : " + groupName + " n'existe pas !");
                    throw new GroupActiveDirectoryNotExistException("Le groupe : " + groupName + " n'existe pas !");
                }
            }
            catch (Exception exception)
            {
                Logger?.Error("Error RemoveUserToGroup - groupName : " + groupName
                              + " - userName : " + userName, exception);

                throw;
            }
        }