.net 如何使用带有用户名而不是 CN 的 LDAP 查询 ActiveDirectory?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/1295157/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-03 13:10:20  来源:igfitidea点击:

How do I query ActiveDirectory using LDAP with a username, not a CN?

.netactive-directoryldap

提问by Robert

If I set the .NET DirectoryEntry.Path to something like:

如果我将 .NET DirectoryEntry.Path 设置为类似:

LDAP://CN=John Smith,OU=Group Name,DC=example,DC=com

Everything works great, and I get the DirectoryEntry I need. However, I don't know the user's true Common Name (CN). I only know their username, "John.Smith".

一切正常,我得到了我需要的 DirectoryEntry。但是,我不知道用户的真实通用名称 (CN)。我只知道他们的用户名,“John.Smith”。

So, how can I query the username? I have tried all the following withoutsuccess:

那么,如何查询用户名呢?我尝试了以下所有方法都没有成功:

LDAP://CN=John.Smith,OU=Group Name,DC=example,DC=com
LDAP://sAMAccountName=John.Smith,OU=Group Name,DC=example,DC=com
LDAP://userPrincipalName=John.Smith,OU=Group Name,DC=example,DC=com
LDAP://[email protected],OU=Group Name,DC=example,DC=com
LDAP://uid=John.Smith,OU=Group Name,DC=example,DC=com
LDAP://o=John.Smith,OU=Group Name,DC=example,DC=com

回答by marc_s

You can't just query by means of creating an LDAP string - you'll need to use code for that.

您不能仅通过创建 LDAP 字符串进行查询 - 您需要为此使用代码。

Something like:

就像是:

DirectoryEntry deRoot = new DirectoryEntry("LDAP://yourserver/CN=Users,dc=YourCompany,dc=com");

DirectorySearcher dsFindUser = new DirectorySearcher(deRoot);
dsFindUser.SearchScope = SearchScope.SubTree;

dsFindUser.PropertiesToLoad.Add("sn"); // surname = last name
dsFindUser.PropertiesToLoad.Add("givenName"); // first name

dsFindUser.Filter = string.Format("(&(objectCategory=Person)(anr={0}))", yourUserName);

SearchResult rseult = dsFindUser.FindOne();

if(result != null)
{
   if(result.Properties["sn"] != null)
   {  
      string lastName = result.Properties["sn"][0].ToString();
   }

   if(result.Properties["givenName"] != null)
   {  
      string lastName = result.Properties["givenName"][0].ToString();
   }
}

The full MSDN documentation on the System.DirectoryServices.DirectorySearcherclass can be found on MSDN - it has lots of additional properties and settings.

关于System.DirectoryServices.DirectorySearcher类的完整 MSDN 文档可以在 MSDN 上找到 - 它有许多附加属性和设置。

If you're on .NET 3.5, things have gotten quite a bit easier with a strongly-typed library of routines for handling users and groups - see this excellent MSDN articleon the topic for more info.

如果您使用的是 .NET 3.5,那么使用用于处理用户和组的强类型例程库,事情就变得容易了许多——有关该主题的更多信息,请参阅这篇优秀的MSDN 文章

Hope this helps

希望这可以帮助

Marc

马克