如何编写LDAP查询以测试用户是否为组成员? [英] How to write LDAP query to test if user is member of a group?
问题描述
我想编写一个LDAP查询,以测试用户(sAMAccountName)是否是特定组的成员.是否可以这样做,以便我得到0或1个结果记录?
我想我可以为用户获取所有组并测试每个组是否匹配,但是我想知道是否可以将其打包到一个LDAP表达式中.
有什么想法吗?
谢谢
您应该可以在此处使用以下过滤器创建查询:
(&(objectClass=user)(sAMAccountName=yourUserName)
(memberof=CN=YourGroup,OU=Users,DC=YourDomain,DC=com))
,当您在LDAP服务器上运行该命令时,如果得到结果,则您的用户"yourUserName"确实是"CN = YourGroup,OU = Users,DC = YourDomain,DC = com
尝试看看是否可行!
如果您使用C#/VB.Net和System.DirectoryServices,则此代码段将达到目的:
DirectoryEntry rootEntry = new DirectoryEntry("LDAP://dc=yourcompany,dc=com");
DirectorySearcher srch = new DirectorySearcher(rootEntry);
srch.SearchScope = SearchScope.Subtree;
srch.Filter = "(&(objectClass=user)(sAMAccountName=yourusername)(memberOf=CN=yourgroup,OU=yourOU,DC=yourcompany,DC=com))";
SearchResultCollection res = srch.FindAll();
if(res == null || res.Count <= 0) {
Console.WriteLine("This user is *NOT* member of that group");
} else {
Console.WriteLine("This user is INDEED a member of that group");
}
警告:仅测试直接的组成员身份,而不会测试您域中所谓的主要组"(通常为"cn = Users")的成员身份.它不处理嵌套成员资格,例如用户A是组A的成员,而组A也是组B的成员-用户A确实也是组B的成员这一事实在这里没有得到体现.
马克
I want to write an LDAP query which tests whether a user (sAMAccountName) is a member of a particular group. Is it possible to do that so that I get either 0 or 1 result records?
I guess I can get all groups for the user and test each one for a match but I was wondering if I could pack it into one LDAP expression.
Any ideas?
Thanks
You should be able to create a query with this filter here:
(&(objectClass=user)(sAMAccountName=yourUserName)
(memberof=CN=YourGroup,OU=Users,DC=YourDomain,DC=com))
and when you run that against your LDAP server, if you get a result, your user "yourUserName" is indeed a member of the group "CN=YourGroup,OU=Users,DC=YourDomain,DC=com
Try and see if this works!
If you use C# / VB.Net and System.DirectoryServices, this snippet should do the trick:
DirectoryEntry rootEntry = new DirectoryEntry("LDAP://dc=yourcompany,dc=com");
DirectorySearcher srch = new DirectorySearcher(rootEntry);
srch.SearchScope = SearchScope.Subtree;
srch.Filter = "(&(objectClass=user)(sAMAccountName=yourusername)(memberOf=CN=yourgroup,OU=yourOU,DC=yourcompany,DC=com))";
SearchResultCollection res = srch.FindAll();
if(res == null || res.Count <= 0) {
Console.WriteLine("This user is *NOT* member of that group");
} else {
Console.WriteLine("This user is INDEED a member of that group");
}
Word of caution: this will only test for immediate group memberships, and it will not test for membership in what is called the "primary group" (usually "cn=Users") in your domain. It does not handle nested memberships, e.g. User A is member of Group A which is member of Group B - that fact that User A is really a member of Group B as well doesn't get reflected here.
Marc
这篇关于如何编写LDAP查询以测试用户是否为组成员?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!