在C#中,如何访问Active Directory以获取某个用户所属的组列表?
在C#中,如何访问Active Directory以获取某个用户所属的组列表?
用户详细信息的格式如下:
"MYDOMAIN\myuser"
我一直在按照这里的说明进行操作,但只有在表格中有用户详细信息时才能使用它们:
"LDAP://sample.com/CN=MySurname MyFirstname,OU=General,OU=Accounts,DC=sample,DC=com"
所以也许我要问的是,如何从第一个,更短的表格到下面的完全合格的表格?
非常感谢!
这可能有帮助……
using System.Collections; using System.DirectoryServices; /// /// Gets the list of AD groups that a user belongs to /// /// The login name of the user (domain\login or login) /// A comma delimited list of the user's AD groups public static SortedList GetADGroups(string loginName) { if (string.IsNullOrEmpty(loginName)) throw new ArgumentException("The loginName should not be empty"); SortedList ADGroups = new SortedList(); int backSlash = loginName.IndexOf("\\"); string userName = backSlash > 0 ? loginName.Substring(backSlash + 1) : loginName; DirectoryEntry directoryEntry = new DirectoryEntry(); DirectorySearcher directorySearcher = new DirectorySearcher(directoryEntry, "(sAMAccountName=" + userName + ")"); SearchResult searchResult = directorySearcher.FindOne(); if (null != searchResult) { DirectoryEntry userADEntry = new DirectoryEntry(searchResult.Path); // Invoke Groups method. object userADGroups = userADEntry.Invoke("Groups"); foreach (object obj in (IEnumerable)userADGroups) { // Create object for each group. DirectoryEntry groupDirectoryEntry = new DirectoryEntry(obj); string groupName = groupDirectoryEntry.Name.Replace("cn=", string.Empty); groupName = groupName.Replace("CN=", string.Empty); if (!ADGroups.ContainsKey(groupName)) ADGroups.Add(groupName, groupName); } } return ADGroups; }
最后,我不得不从相反的角度接近它,因为我必须从一个单独的(受信任的)森林中validation成员。 所以这是找到给定组成员列表的代码:
/// /// Finds the users in the given group. Eg groupName=My-Group-Name-Blah /// returns an array of users eg: DOMAIN\user /// string[] UsersInGroup(string groupName) { List users = new List (); // First, find the group: string query = string.Format("(CN={0})", groupName); SearchResult searchResult = new DirectorySearcher(query).FindOne(); DirectoryEntry group = new DirectoryEntry(searchResult.Path); // Find all the members foreach (object rawMember in (IEnumerable)group.Invoke("members")) { // Grab this member's SID DirectoryEntry member = new DirectoryEntry(rawMember); byte[] sid = null; foreach (object o in member.Properties["objectSid"]) sid = o as byte[]; // Convert it to a domain\user string try { users.Add( new SecurityIdentifier(sid, 0).Translate(typeof(NTAccount)).ToString()); } catch { } // Some SIDs cannot be discovered - ignore these } return users.ToArray(); }
- 使用PrincipalContext.ValidateCredentials对本地计算机进行身份validation时出错?
- 即使pagesize设置为更大,directorysearcher对象的上限是5000
- 如何将AcquireTokenAsync中收到的令牌与Active Directory一起存储
- 从本地计算机关闭网络确定用户Active Directory组
- C#ADAL AcquireTokenAsync()没有弹出框
- 我如何在.NET中处理Negotiate?
- 使用ASP.NET获取Active Directory信息,无需用户名和密码
- 使用C#从ASP.Net MVC访问Active Directory
- C# – 在活动目录中查找用户管理器