/// <summary> /// Populates the user.Groups collection with those groups that are assigned to the specified user. /// note: Any groups in the user.Groups collection before calling this method will be removed. /// </summary> /// <note> /// A user will also belong to the parents of the group that he/she is assigned to. /// So, also return the parents of assigned groups. /// </note> public int LoadGroupsAssignedToUser(LdapUserInfo user) { user.Groups.Clear(); string filter = $@"(&(objectCategory=group)(member={user.DistinguishedName}))"; SearchResultCollection resList = GetSearchResults(GetRootEntry(), filter, searchSubtrees: true); foreach (SearchResult groupRes in resList) { var entry = groupRes.GetDirectoryEntry(); var group = entry.CopyTo(new LdapGroupInfo()); user.Groups.Add(group); } // Note: AD does not include the primary group in the member list. var primaryGroup = GetGroupBySID(user.PrimaryGroupSID); if (primaryGroup != null) { user.Groups.Add(primaryGroup); } // Load the parent groups. var localGroups = user.Groups.ToArray(); foreach (var group in localGroups) { LoadParentsOfGroup(group, user.Groups); } return(user.Groups.Count); }
public LdapUserInfo(LdapUserInfo entry) : base(entry) { LoginName = entry.LoginName; UserPrincipalName = entry.UserPrincipalName; Email = entry.Email; FirstName = entry.FirstName; MiddleName = entry.MiddleName; LastName = entry.LastName; PrimaryGroupSID = entry.PrimaryGroupSID; LockedOut = entry.LockedOut; Disabled = entry.Disabled; Groups = new LdapGroupCollection(); foreach (LdapGroupInfo group in entry.Groups) { Groups.Add(new LdapGroupInfo(group)); } }
/// <summary> /// Retrieves the specified user information from the LDAP server or null if user is not found. /// </summary> /// <param name="guid">The objectGUID of the user account to be retrieved.</param> /// <param name="loadGroups">Set to ture to load the Groups collection with those groups assigned to the user.</param> public LdapUserInfo GetUserByGuid(Guid guid, bool loadGroups = true) { DirectoryEntry entry = GetEntryByGuid(guid); if (entry == null) { return(null); } else { LdapUserInfo user = entry.CopyTo(new LdapUserInfo()); if (loadGroups) { LoadGroupsAssignedToUser(user); } return(user); } }
/// <summary> /// Use this method to authenticate a specified user with the LDAP server. /// </summary> /// <param name="user">The user account to authenticate.</param> /// <param name="password">The password of the user to authenticate.</param> /// <returns>Returns true if the specified user credentials successfully validate.</returns> public bool AuthenticateUser(LdapUserInfo user, string password) { return(AuthenticateUser(user.LoginName, password)); }