如何连接到活动目录服务器?

时间:2011-05-01 05:50:43

标签: asp.net active-directory

我正在使用以下代码连接到活动目录服务器并检索其用户。

但我的网络服务器不在子域中。我能连接到它吗?

或者我应该包含其IP地址或其他内容?

DirectoryEntry entry = new DirectoryEntry("LDAP://dps.com", "Raymond", "xxxxxxx");

DirectorySearcher mySearcher = new DirectorySearcher(entry);
mySearcher.Filter = ("(&(objectCategory=person)(objectClass=user))");

foreach (SearchResult result in mySearcher.FindAll())
{
   ResultPropertyCollection myResultPropColl = result.Properties;
   DataRow dr=reader.Tables[0].NewRow();
   dr[0]=myResultPropColl["samaccountname"][0].ToString()+"@"+Domain;
   reader.Tables[0].Rows.Add(dr);
   Response.Write(myResultPropColl["samaccountname"][0].ToString());
}

1 个答案:

答案 0 :(得分:6)

如果您使用的是.NET 3.5及更高版本,则应查看System.DirectoryServices.AccountManagement(S.DS.AM)命名空间。在这里阅读所有相关内容:

Managing Directory Security Principals in the .NET Framework 3.5

基本上,您可以定义域上下文并轻松在AD中查找用户和/或组:

// set up domain context - connects to the current default domain
PrincipalContext ctx = new PrincipalContext(ContextType.Domain);

// find user by name
UserPrincipal user = UserPrincipal.FindByIdentity("John Doe");

// find all users in your AD directory - set up a "query-by-example" 
// template to search for; here: a UserPrincipal, which is not locked out
UserPrincipal userTemplate = new UserPrincipal(ctx);
userTemplate.IsAccountLockedOut = false;

// create a PrincipalSearcher, based on that search template
PrincipalSearcher searcher = new PrincipalSearcher(userTemplate);

// enumerate all users that this searcher finds
foreach(Principal foundPrincipal in searcher.FindAll())
{
   UserPrincipal foundUser = (foundPrincipal as UserPrincipal);

   // do something with the userTemplate
}

新的S.DS.AM使得在AD中使用用户和群组变得非常容易:

如果无法升级到S.DS.AM,您需要做的是确保使用正确的LDAP字符串连接到您的服务器。该字符串应该是这样的:

 LDAP://servername/OU=Users,DC=YourCompany,DC=com

servername是可选的 - 您也可以将其保留。但LDAP字符串需要至少由一个DC=xxxxx字符串和可能的其他LDAP段组成。