我正在编写一个 LDAP 接口(interface),对于给定组的 objectguid
,必须返回这些组中所有用户的列表以及用户的 SID。
对于给定组的 objectguid
,下面的代码返回该组中的用户。然而它们的形式都是...
CN=Chad Hutchins,OU=Contractors,DC=RM,DC=LOCAL
...但我需要用户的 SID 与上面的字符串。有没有办法从组开始并查询该组中的所有用户来获取用户的SID?
using System.DirectoryServices;
public void GetUsers(Guid groupId, string domain, string username, string password)
{
var rootEntry = new DirectoryEntry("LDAP://" + domain);
rootEntry.Username = username;
rootEntry.Password = password;
var searcher = new DirectorySearcher(rootEntry);
searcher.Filter = @"(objectguid=" + ConvertGuidToOctectString(groupId) + ")";
var groupResult = searcher.FindOne();
foreach (DictionaryEntry prop in groupResult.Properties)
{
var key = (string)prop.Key;
switch (key)
{
case "member":
foreach (string name in groupResult.Properties[key])
Console.WriteLine(name);
break;
}
}
}
private string ConvertGuidToOctectString(Guid guid)
{
var byteGuid = guid.ToByteArray();
var queryGuid = string.Empty;
foreach (var b in byteGuid)
{
queryGuid += @"\" + b.ToString("x2");
}
return queryGuid;
}
最佳答案
关于如何检索用户SIDs
,您几乎没有选择来自特定group
。
使用
GroupPrincipal
在AccountManagement
命名空间。public static List<string> GetUsersFromGroupByGroupID(string ID) { using (PrincipalContext ctx = new PrincipalContext(ContextType.Domain, "yourdomain.com") { using (GroupPrincipal group = GroupPrincipal.FindByIdentity(ctx, IdentityType.Guid, ID)) { if (group != null) { List<string> memberSIDs = new List<string>(); var members = group.GetMembers(true); foreach(var member in members) { memberSIDs.Add(member.Sid.ToString()); } return memberSIDs; } } } return null; }
您可以存储
DistinguishedName
您查询中的所有用户的数量为List<string>
然后查找用户SID
使用UserPrincipal
类。public static List<string> GetUserSIDs(List<string>userDNs) { List<string> userSIDs = new List<string>(); using (PrincipalContext ctx = new PrincipalContext(ContextType.Domain, "yourdomain.com")) { foreach(string userDN in userDNs) { using (UserPrincipal user = UserPrincipal.FindByIdentity(ctx, IdentityType.DistinguishedName, userDN)) { if (user != null) { userSIDs.Add(user.Sid.ToString()); } } } } return userSIDs; }
最后一个选项您仍然可以获得
DistiniguishedName
的列表根据您的查询,仍然使用DirectoryEntry
using (DirectoryEntry entry = new DirectoryEntry("LDAP://userDistinguishedName") { var userSID = entry.Properties["objectSID"][0]; }
注意*在这种情况下userSID
将返回为 byte[] array
.
关于.net - LDAP 查询返回组中的所有用户,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36699793/