我使用下面的代码从Active目录中获取用户的安全组列表,但是我从Active目录中获取用户的所有组,您能否帮助我获取用户的安全组列表来自Active Directory?
public List<string> getSecurityGroup(string userName,SearchInfo searchInfo, Error errorInfo)
{
List<string> groups =new List<string>() ;
try
{
string ldapPath = @"LDAP://" + searchInfo.HostName + @"/" + searchInfo.SearchDN;
DirectoryEntry obEntry = new DirectoryEntry(ldapPath);
DirectorySearcher srch = new DirectorySearcher(obEntry,
"(sAMAccountName=" + userName + ")");
SearchResult res = srch.FindOne();
if (null != res)
{
DirectoryEntry obUser = new DirectoryEntry(res.Path);
// Invoke Groups method.
object obGroups = obUser.Invoke("Groups");
foreach (object ob in (IEnumerable)obGroups)
{
// Create object for each group.
DirectoryEntry obGpEntry = new DirectoryEntry(ob);
groups.Add(obGpEntry.Name);
}
}
}
catch (System.Runtime.InteropServices.ExternalException comException)
{
errorInfo.ErrorCode = comException.ErrorCode;
errorInfo.ErrorMessage = comException.Message;
}
catch (Exception exception)
{
errorInfo.ErrorCode = -1;
errorInfo.ErrorMessage = exception.Message;
}
return groups;
}
答案 0 :(得分:1)
一种方法是查看groupType属性,例如您可以使用以下方法搜索安全组:
(&(objectCategory=group)(groupType:1.2.840.113556.1.4.803:=2147483648))
BTW另一种获取给定用户所属组(直接或间接)的方法是使用搜索过滤器:
(member:1.2.840.113556.1.4.1941:=<user-distinguished-name>)
您可以将其与groupType过滤器结合使用。有关详细信息,请参阅this MSDN article on Search Filter syntax。
<强>更新强>
你能告诉我我必须修改哪部分代码?
以上是一个过滤器,作为参数传递给DirectorySearcher
方法。例如。以下内容应创建一个sAMAccountName
的{{1}}列表,其中userrName
是其成员,直接或间接:
List<string> groups = new List<string>();
using (var root = new DirectoryEntry(ldapPath))
{
using(var srch = new DirectorySearcher(root,
"(sAMAccountName=" + userName + ")"))
{
SearchResult res = srch.FindOne();
if (res != null)
{
string dn = (string) res.Properties["distinguishedName"][0];
string filter = String.Format(CultureInfo.InvariantCulture,
"(&(objectCategory=group)(groupType:1.2.840.113556.1.4.803:=2147483648)(member:1.2.840.113556.1.4.1941:={0}))",
dn);
using (var groupSearch = new DirectorySearcher(root, filter, new[] { "sAMAccountName" }))
{
groupSearch.PageSize = 1000;
using (var resultCollection = groupSearch.FindAll())
{
foreach (SearchResult result in resultCollection)
{
groups.Add((string) result.Properties["sAMAccountName"][0]);
}
}
}
}
}
}
答案 1 :(得分:0)
首先:它看起来很像C#,而不是java。你为什么用标签Java发帖?
其次:在AD中,安全组应属于OU“安全组”。因此,检查每个组的可分辨名称。如果它包含“OU=Security Groups
”,则它应该是一个安全组。
或者,您可以获取组记录并检查sAMAccountType
属性。安全组的值应为0x10000000(十进制268435456)。
编辑: 没有完全流利的C#我不能保证确切的正确性,但也许尝试这样的事情:
foreach (object ob in (IEnumerable)obGroups)
{
// Create object for each group.
DirectoryEntry obGpEntry = new DirectoryEntry(ob);
if (obGpEntry.Path.ToLower().contains("ou=security groups")) {
groups.Add(obGpEntry.Name);
}
}