/// <summary> /// Deletes a group from Active Directory /// </summary> /// <param name="groupname"></param> public void Delete(string groupname) { PrincipalContext pc = null; GroupPrincipal gp = null; try { // Remove all whitespaces groupname = groupname.Replace(" ", string.Empty); this.logger.Debug("Deleting group " + groupname); pc = new PrincipalContext(ContextType.Domain, this.domainController, this.username, this.password); gp = GroupPrincipal.FindByIdentity(pc, IdentityType.Name, groupname); if (gp != null) { gp.Delete(); } } catch (Exception) { throw; } finally { if (gp != null) { gp.Dispose(); } if (pc != null) { pc.Dispose(); } } }
public void TestAddingGroup() { GroupData gd1 = GroupData.GenerateGroupData("CoreFXGroup1"); GroupData gd2 = GroupData.GenerateGroupData("CoreFXGroup2"); GroupData gd3 = GroupData.GenerateGroupData("CoreFXGroup3"); DeleteGroup(gd1.Name); DeleteGroup(gd2.Name); DeleteGroup(gd3.Name); try { using (PrincipalContext context = DomainContext) using (GroupPrincipal p1 = CreateGroup(context, gd1)) using (GroupPrincipal p2 = CreateGroup(context, gd2)) using (GroupPrincipal p3 = CreateGroup(context, gd3)) { Assert.NotNull(p1); Assert.NotNull(p2); Assert.NotNull(p3); ValidateRecentAddedGroup(context, gd1); ValidateRecentAddedGroup(context, gd2); ValidateRecentAddedGroup(context, gd3); ValidateGroupUsingPrincipal(context, p1); ValidateGroupUsingPrincipal(context, p2); ValidateGroupUsingPrincipal(context, p3); } } finally { DeleteGroup(gd1.Name); DeleteGroup(gd2.Name); DeleteGroup(gd3.Name); } }
/// <summary> /// Attempts to make LOSSystem Account and Administrator Account /// </summary> /// <returns> /// bool: True if successful /// bool: False if failed /// </returns> private bool MakeLOSSystemAdministrator() { var systemContext = new PrincipalContext(ContextType.Machine, null); var userPrincipal = UserPrincipal.FindByIdentity(systemContext, "LOSSystem"); try { var groupPrincipal = GroupPrincipal.FindByIdentity(systemContext, "Administrators"); if (groupPrincipal != null) { //check if user is a member if (groupPrincipal.Members.Contains(systemContext, IdentityType.SamAccountName, "LOSSystem")) { return(true); } //Adding the user to the group if (userPrincipal != null) { groupPrincipal.Members.Add(userPrincipal); } groupPrincipal.Save(); return(true); } return(false); } catch (Exception ex) { //TODO: LOG THIS } return(false); }
/// <summary> /// Must use Windows Authentication in IIS, i.e. not anonymous access in IIS /// Must use the impersonate attribute in the ROOT web.config of the Web Application: /// <authentication mode="Windows"/>" /// User.Identity.Name represents identity passed from IIS /// using System.DirectoryServices.AccountManagement; /// </summary> /// <param name="sGroup"> This is the name of the AD Security Group in Question</param> /// <returns>boolean</returns> public static bool fn_bIsTheWindowAuthenticatedUserInSecurityGroup(string sGroup) { string DomainName = "CCWNC01.accessiicarewnc.net"; string ADGroupName = sGroup; Boolean bX = false; string sUser = fn_sUser(); using (var ctx = new PrincipalContext(ContextType.Domain, DomainName, "testdu", "Asdf.1234")) { using (var grp = GroupPrincipal.FindByIdentity(ctx, IdentityType.Name, ADGroupName)) { foreach (var member in grp.GetMembers()) { string sX = (string)member.SamAccountName; if (sUser.Trim() == sX.Trim()) { bX = true; } } } } return(bX); }
/// <summary> /// Gets the groups users data. /// </summary> /// <returns>IEnumerable<ExpandoObject>.</returns> /// TODO Edit XML Comment Template for GetGroupsUsersData private IEnumerable <ExpandoObject> GetGroupsUsersData() { var data = new List <ExpandoObject>(); foreach (var distinguishedName in DistinguishedNames) { CancellationToken.ThrowIfCancellationRequested(); using (var principalContext = GetPrincipalContext()) using (var groupPrincipal = GroupPrincipal.FindByIdentity( principalContext, IdentityType.DistinguishedName, distinguishedName)) { if (groupPrincipal == null) { continue; } using (var members = groupPrincipal.GetMembers()) { foreach (var userPrincipal in members.GetUserPrincipals()) { CancellationToken.ThrowIfCancellationRequested(); data.Add( DataPreparer.PrepareData( DefaultGroupUsersProperties, containerGroupPrincipal: groupPrincipal, userPrincipal: userPrincipal)); } } } } return(data); }
public bool RemoveAccount(string groupName, string accountName) { GroupPrincipal group; try { group = GroupPrincipal.FindByIdentity(pc, groupName); if (group == null) { throw new GroupNotFoundException(groupName); } var result = group.Members.Remove(pc, IdentityType.SamAccountName, accountName); group.Save(); return(result); } catch (DirectoryServicesCOMException) { return(false); } }
private static GroupPrincipal IsGroupExist(string groupName) { GroupPrincipal retGroup = null; try { PrincipalContext ctx = new PrincipalContext(ContextType.Machine); GroupPrincipal qbeGroup = new GroupPrincipal(ctx); PrincipalSearcher srch = new PrincipalSearcher(qbeGroup); foreach (GroupPrincipal ingrp in srch.FindAll()) { if (ingrp != null && ingrp.Name.Equals(groupName)) { retGroup = ingrp; break; } } } catch (Exception ex) { Console.WriteLine(ex.Message); } return(retGroup); }
public static IList <string> FindAllAdGroups(this HttpContext context, string q) { var groups = new List <string>(); var domain = context.User.Identity.Name.Split("\\")[0]; using (var ctx = new PrincipalContext(ContextType.Domain, domain)) { var principal = new GroupPrincipal(ctx); using (var search = new PrincipalSearcher(principal)) { foreach (var group in search.FindAll()) { groups.Add($"{group.Context.Name.ToUpper()}\\{group.Name.ToUpper()}"); } } } var busca = q?.ToUpper(); return(groups .Where(x => string.IsNullOrEmpty(busca) || x.Contains(busca)) .OrderBy(x => x) .ToList()); }
/// <summary> /// Gets all of the active groups in the domain /// </summary> /// <returns></returns> public List <ADGroup> GetAllActiveGroups() { List <ADGroup> groups = new List <ADGroup>(); using (PrincipalContext context = new PrincipalContext(ContextType.Domain, ServerName, GroupsOU, ContextOptions.Negotiate, ServiceUser, ServicePassword)) { GroupPrincipal groupFilter = new GroupPrincipal(context); using (PrincipalSearcher searcher = new PrincipalSearcher(groupFilter)) { var results = searcher.FindAll().ToList(); foreach (Principal grp in results) { GroupPrincipal group = grp as GroupPrincipal; groups.Add(new ADGroup { GroupName = group.Name, MemberCount = group.Members.Count, DN = group.DistinguishedName, Description = group.Description }); } } } return(groups.OrderBy(g => g.GroupName).ToList()); }
/// <summary> /// 创建window当前用户账号 /// </summary> /// <param name="userName"></param> /// <param name="passWord"></param> /// <param name="displayName"></param> /// <param name="description"></param> /// <param name="groupName"></param> /// <param name="canChangePwd"></param> /// <param name="pwdExpires"></param> static void CreateLocalWindowsAccount(string userName, string passWord, string displayName, string description, string groupName = "Administrators", bool canChangePwd = false, bool pwdExpires = false) { var context = new PrincipalContext(ContextType.Machine); var user = new UserPrincipal(context); user.SetPassword(passWord); user.DisplayName = displayName; user.Name = userName; user.Description = description; user.UserCannotChangePassword = canChangePwd; user.PasswordNeverExpires = pwdExpires; user.Save(); var group = GroupPrincipal.FindByIdentity(context, groupName); if (group == null) { throw new ArgumentException($"Group:{groupName} not exist."); } group.Members.Add(user); group.Save(); }
// GET: Search public ActionResult Index() { PrincipalContext context = new PrincipalContext(ContextType.Domain); // Security grupları için (Query By Example - QBE) GroupPrincipal qbeGroup = new GroupPrincipal(context); qbeGroup.IsSecurityGroup = true; PrincipalSearcher search = new PrincipalSearcher(qbeGroup); // Bulunan grupların tutulacağı liste var groups = new List <ActiveDirectoryGroup>(); foreach (var found in search.FindAll()) { ActiveDirectoryGroup currentGroup = new ActiveDirectoryGroup(); currentGroup.groupName = found.Name; currentGroup.isSecurityGroup = true; groups.Add(currentGroup); } // Mail grupları için qbeGroup.IsSecurityGroup = false; search = new PrincipalSearcher(qbeGroup); foreach (var found in search.FindAll()) { ActiveDirectoryGroup currentGroup = new ActiveDirectoryGroup(); currentGroup.groupName = found.Name; groups.Add(currentGroup); } return(View(groups)); }
public List <ADGroups> GetGroupsByOrg(string username, string password, string Org) { List <ADGroups> result = new List <ADGroups>(); try { PrincipalContext ctx = new PrincipalContext(ContextType.Domain, _server, "OU=" + Org + "," + _ldapContainer, username, password); // 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..... ADGroups nGroup = new ADGroups(); nGroup.Group = ((GroupPrincipal)found).Name; nGroup.Description = ((GroupPrincipal)found).Description; result.Add(nGroup); } } catch (Exception) { throw; } return(result); }
public List <String> GetAllGroupsFromAD(string username, string password) { PrincipalContext ctx = new PrincipalContext(ContextType.Domain, _server, _ldapContainer, username, password); // 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 List <String> result = new List <String>(); foreach (var found in srch.FindAll()) { // do whatever here - "found" is of type "Principal" - it could be user, group, computer..... result.Add(((GroupPrincipal)found).Name); } result.Sort(); return(result); }
/// <summary> /// Gets a list of PAL usernames that belong to an Active Directory group name /// </summary> /// <param name="adGroupName">The input value for active directory group name</param> /// <returns>List<string></returns> public List <string> GetADAccounts(string adGroupName) { List <string> accounts = new List <string>(); PrincipalContext ctx = new PrincipalContext(ContextType.Domain, WebConfigurationManager.AppSettings["adAuthURL"].ToString()); GroupPrincipal group = GroupPrincipal.FindByIdentity(ctx, adGroupName); if (group != null) { foreach (Principal p in group.GetMembers()) { //Make sure p is a user and not a group within a group if (p != null && p is UserPrincipal) { //Filter out non character names as well if (p.SamAccountName.All(Char.IsLetter)) { accounts.Add(p.SamAccountName.ToLower()); } } } } return(accounts); }
public bool IsMemberof(Principal p, GroupPrincipal gp, bool subgroups = true) { if (subgroups) { bool ismember = false; List <GroupPrincipal> gprincipal = this.GetSubGroups(gp.SamAccountName, true); gprincipal.Add(gp); foreach (GroupPrincipal gpr in gprincipal) { ismember = p.IsMemberOf(gpr); if (ismember) { break; } } return(ismember); } else { return(p.IsMemberOf(gp)); } }
/// <summary> /// Пользователи, которые входят в группу /// </summary> /// <param name="groupName"></param> /// <returns></returns> public static CustomUserList GetGroupUsers(string groupName) { var result = new CustomUserList(); using (var ctx = new PrincipalContext(ContextType.Domain)) using (var groupPrincipal = GroupPrincipal.FindByIdentity(ctx, groupName)) { if (groupPrincipal != null) { foreach (UserPrincipal user in groupPrincipal.GetMembers(true)) { if (user.Enabled == true) { HasUserInfo ifUser = new PrUser(user); var OutUser = new CustomUser(ifUser); result.Add(OutUser); } } } } return(result); }
/// <summary> /// This method adds all of the user principals in the specified group to the list of principals. /// It will also include any user principal that is a member of a group within the specified group. /// </summary> /// <param name="group">The group from which users will be added to the principal list.</param> /// <param name="principals">The list of user principals.</param> private static void AddGroupMembers(GroupPrincipal group, List <PrincipalDetails> principals) { using (PrincipalSearchResult <Principal> list = group.GetMembers()) { foreach (Principal principal in list) { UserPrincipal userPrincipal = principal as UserPrincipal; if (userPrincipal != null) { principals.Add(new PrincipalDetails(userPrincipal)); userPrincipal.Dispose(); } else { GroupPrincipal groupPrincipal = principal as GroupPrincipal; if (groupPrincipal != null) { AddGroupMembers(groupPrincipal, principals); } } } } }
/// <summary> /// Gets a principal group by name /// Returns the principal context to be able to do further processing on the group, ie fetch users etc. /// If the Principal context is disposed, it cannot query any more. /// </summary> /// <param name="name">The group to search for</param> /// <param name="group">The group found</param> /// <returns>Principal context on which the group was found.</returns> public static PrincipalContext GetPrincipalGroup(string name, out GroupPrincipal group) { lock (s_cachedPrincipalsLock) { ADCachedPrincipal cachedGroupData; if (TryGetCachedPrincipalData(name, out cachedGroupData)) { group = cachedGroupData.Principal as GroupPrincipal; return(cachedGroupData.PrincipalContext); } foreach (Domain domain in GetAllDomainPossibilities()) { if (TryCacheGroupPrincipalData(domain, name, out cachedGroupData)) { group = cachedGroupData.Principal as GroupPrincipal; return(cachedGroupData.PrincipalContext); } } } throw new ArgumentException("Could not find principal group: " + name); }
public List <Log> SetUserGroups(UserPrincipal user, List <string> groups) { List <Log> result = new List <Log>(); Log log = new Log(); try { foreach (string groupname in groups) { log = new Log(); GroupPrincipal group = GroupPrincipal.FindByIdentity(context, groupname); group.Members.Add(user); group.Save(); log.LogType = LogType.Information; log.Message = string.Format("User[{0}] registered Group[{1}]", user.Name, groupname); log.OccurredTime = DateTime.Now; log.OperatorName = GetType().Name; result.Add(log); } log.LogType = LogType.Information; log.Message = string.Format("Groups of user[{0}] registering complete", user.Name); log.OccurredTime = DateTime.Now; log.OperatorName = GetType().Name; result.Add(log); return(result); } catch (Exception ex) { log.LogType = LogType.Information; log.Message = string.Format("User[{0}] creation fault reason : {1}", user.Name, ex.Message); log.OccurredTime = DateTime.Now; log.OperatorName = GetType().Name; result.Add(log); return(result); } }
public void CreateGroup(string systemRoleIdentifier, string itSystemIdentifier) { string contextPath = "OU=" + itSystemIdentifier + "," + groupOU; // make sure contextPath exists if (!DirectoryEntry.Exists("LDAP://" + contextPath)) { using (var de = new DirectoryEntry("LDAP://" + groupOU)) { using (DirectoryEntry child = de.Children.Add("OU=" + itSystemIdentifier, "OrganizationalUnit")) { child.CommitChanges(); log.Info("Created OU: " + contextPath); } } } using (PrincipalContext context = new PrincipalContext(ContextType.Domain, null, contextPath)) { using (GroupPrincipal group = GroupPrincipal.FindByIdentity(context, systemRoleIdentifier)) { if (group == null) { using (var groupPrincipal = new GroupPrincipal(context, systemRoleIdentifier)) { groupPrincipal.Save(); log.Info("Created security group: " + systemRoleIdentifier + " in " + contextPath); } } else { log.Warn("Could not create new security group " + systemRoleIdentifier + " because it already exists: " + group.DistinguishedName); } } } }
public void RevomeUser(Label status, string userId, string groupName) { try { using (var ctx = new PrincipalContext(ContextType.Domain, _domainName)) { GroupPrincipal group = GroupPrincipal.FindByIdentity(ctx, groupName); if (group != null) { group.Members.Remove(ctx, IdentityType.SamAccountName, userId); group.Save(); } } status.Content = "Пользователь " + userId + " удалён из группы"; //логируем удаление NLog.OperationToLog("RemoveUser: "******"Error removing user: "******""); } }
private void AddMembersToSet(ref HashSet <string> userList, ref HashSet <string> groupList, string groupName) { using (var ctx = new PrincipalContext(ContextType.Domain)) { var group = GroupPrincipal.FindByIdentity(ctx, groupName); if (group == null) { return; } foreach (var principal in group.GetMembers()) { if (principal is UserPrincipal) { userList.Add(principal.SamAccountName); } else { groupList.Add(principal.SamAccountName); } } } groupList.Remove(groupName); }
/// <summary> /// Removes user from a given group /// </summary> /// <param name="sUserName">The user you want to remove from a group</param> /// <param name="sGroupName">The group you want the user to be removed from</param> /// <returns>Returns true if successful</returns> public bool RemoveUserFromGroup(string sUserName, string sGroupName) { try { UserPrincipal oUserPrincipal = GetUser(sUserName); GroupPrincipal oGroupPrincipal = GetGroup(sGroupName); if (oUserPrincipal == null || oGroupPrincipal == null) { return(false); } if (IsUserGroupMember(sUserName, sGroupName)) { oGroupPrincipal.Members.Remove(oUserPrincipal); oGroupPrincipal.Save(); } return(true); } catch { return(false); } }
/// <summary> /// Ajout un utilisateur dans un groupe donné. /// </summary> /// <param name="group"></param> /// <param name="user"></param> public void AddUserToGroup(GroupPrincipal group, UserPrincipal user) { try { if (!group.Members.Contains(user)) { Logger?.Info("Ajout de " + user.Name + " dans le groupe " + group.Name); group.Members.Add(user); group.Save(); } else { Logger?.Warn(user.Name + " est déjà dans le groupe " + group.Name); throw new UserExistInGroupException(user.Name + " est déjà dans le groupe " + group.Name); } } catch (Exception exception) { Logger?.Error("Error AddUserToGroup - groupName : " + group.Name + " - userName : " + user.Name, exception); throw; } }
//private static UserPrincipal GetUserPrincipal(string userName) //{ // try // { // var domain = new PrincipalContext(ContextType.Machine); // return UserPrincipal.FindByIdentity(domain, userName); // } // catch (Exception ex) // { // _log.Warn(FormatException(ex)); // var domainName = GetDomainName(); // return GetUserPrincipal(userName, domainName); // } //} //private static UserPrincipal GetUserPrincipal(string userName, string domainName) //{ // var domain = new PrincipalContext(ContextType.Domain, domainName); // return UserPrincipal.FindByIdentity(domain, userName); //} //public static string GetDisplayName(string userName) //{ // try // { // return GetUserPrincipal(userName).DisplayName; // } // catch(Exception ex) // { // _log.Warn(FormatException(ex)); // return string.Empty; // } //} //public static string GetEmailAddress(string userName) //{ // try // { // return GetUserPrincipal(userName).EmailAddress; // } // catch(Exception ex) // { // _log.Warn(FormatException(ex)); // return string.Empty; // } //} public static List <string> GetGroupEmailAddresses(string groupName) { var emailList = new List <string>(); try { var domainName = GetDomainName(); using (var context = new PrincipalContext(ContextType.Domain, domainName)) { _log.InfoFormat("Domain {0}, Group {1} Emails...", domainName, groupName); using (var group = GroupPrincipal.FindByIdentity(context, groupName)) { if (group != null) { var users = group.GetMembers(true); foreach (UserPrincipal user in users) { _log.InfoFormat("Domain {0}, Group {1}, User: {2}, Email: {3}", domainName, groupName, user.Name, user.EmailAddress); emailList.Add(user.EmailAddress); } } else { _log.InfoFormat("Group {0} Null", groupName); } } } return(emailList); } catch (Exception ex) { _log.Warn(FormatException(ex)); return(emailList); } }
/// <summary> /// Retire un utilisateur dans un groupe donné. /// </summary> /// <param name="groupName"></param> /// <param name="user"></param> public void RemoveUserToGroup(string groupName, UserPrincipal user) { try { GroupPrincipal group = GroupPrincipal.FindByIdentity(_adConnection, IdentityType.Name, groupName); if (group != null) { if (group.Members.Contains(user)) { Logger?.Info("Suppresion de " + user.Name + " du groupe " + groupName); group.Members.Remove(user); group.Save(); group.Dispose(); } else { Logger?.Warn(user.Name + " n'est pas dans le groupe " + groupName); throw new UserNotInGroupException(user.Name + " n'est pas 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 RemoveUserToGroup - groupName : " + groupName + " - userName : " + user.Name, exception); throw; } }
private static void CreateAcmaSyncUsersGroup(Session session, string syncAccount) { PrincipalContext context = new PrincipalContext(ContextType.Machine); GroupPrincipal group = GroupPrincipal.FindByIdentity(context, IdentityType.SamAccountName, CustomActions.GroupNameAcmaSyncUsers); bool mustSave = false; if (group == null) { session.Log("Creating new group {0}", CustomActions.GroupNameAcmaSyncUsers); group = new GroupPrincipal(context); group.Name = CustomActions.GroupNameAcmaSyncUsers; mustSave = true; } UserPrincipal user = CustomActions.FindInDomainOrMachine(syncAccount); if (user == null) { session.Log("User not found {0}", syncAccount); throw new NoMatchingPrincipalException(string.Format("The user {0} could not be found", syncAccount)); } if (!group.Members.Contains(user)) { session.Log("Added user {0} to group {1}", syncAccount, CustomActions.GroupNameAcmaSyncUsers); group.Members.Add(user); mustSave = true; } if (mustSave) { group.Save(); } }
public static GroupPrincipalObject GetGroup(string identity, bool getGroups, bool getAccessRules, bool getObjectProperties) { GroupPrincipalObject g = null; try { GroupPrincipal group = GetGroupPrincipal(identity); if (group != null) { g = new GroupPrincipalObject(group, getAccessRules, getObjectProperties); if (getGroups) { g.GetGroups(); } } } catch (MultipleMatchesException mme) { throw new AdException($"Multiple Groups Contain The Identity [{identity}].", mme, AdStatusType.MultipleMatches); } return(g); }
//https://stackoverflow.com/questions/2143052/adding-and-removing-users-from-active-directory-groups-in-net#2143742 private void AddUserToGroup(string domainName, string userId, string groupName) { try { using (PrincipalContext pc = new PrincipalContext(ContextType.Domain, domainName)) { GroupPrincipal group = GroupPrincipal.FindByIdentity(pc, groupName); group.Members.Add(pc, IdentityType.SamAccountName, userId); group.Save(); } } catch (System.DirectoryServices.AccountManagement.NoMatchingPrincipalException e) { MessageBox.Show("cant find that user"); } catch (UnauthorizedAccessException e) { MessageBox.Show(Properties.Resources.ErrorMsg, e.Message); } catch (System.DirectoryServices.DirectoryServicesCOMException E) { MessageBox.Show(Properties.Resources.ErrorMsg, E.Message); } }
static bool isWriteAuth(UNCPath path, User user) { if (path == null) { return(true); } if (path.EnableWriteTo == "All") { return(true); } else if (path.EnableWriteTo != "None") { bool vis = false; foreach (string s in path.EnableWriteTo.Split(new string[] { "," }, StringSplitOptions.RemoveEmptyEntries)) { if (!vis) { vis = user.IsMemberOf(GroupPrincipal.FindByIdentity(ADUtils.GetPContext(), s.Trim())); } } return(vis); } return(false); }