Я знаю, что этот вопрос задавался раньше, но другие методы не позволяют мне прямо сейчас.
В наших сегодняшних опросах служб Windows AD, учитывая LDAP (то есть LDAP://10.32.16.80) и список пользовательских групп на этом сервере AD для поиска. Он извлекает всех пользователей в этих группах, рекурсивный поиск этих групп для большего количества групп. Затем каждый пользователь добавляется в другой список пользователей, прошедших проверку подлинности.
Эта часть приложения работает успешно. Тем не менее, мы нуждаемся в каждом удобном для пользователя доменном имени (т.е. Части имени пользователя DOMAIN/имени пользователя)
Итак, если есть пользователь, который является частью домена TEST, названный Steve: TEST/steve - это его логин. Я могу найти steve в AD, однако мне также нужен "TEST", который будет храниться вместе с его информацией AD.
Опять же, я могу найти "steve" в порядке, используя поисковик каталога и IP-адрес LDAP, который я даю, но с учетом IP-адреса LDAP, как найти дружественное доменное имя?
Когда я пытаюсь выполнить следующий код, я получаю сообщение об ошибке при попытке получить доступ к "defaultNamingContext":
System.Runtime.InteropServices.COMException(0x8007202A): механизм аутентификации неизвестен.
Вот код:
private string SetCurrentDomain(string server)
{
string result = string.Empty;
try
{
logger.Debug("'SetCurrentDomain'; Instantiating rootDSE LDAP");
DirectoryEntry ldapRoot = new DirectoryEntry(server + "/rootDSE", username, password);
logger.Debug("'SetCurrentDomain'; Successfully instantiated rootDSE LDAP");
logger.Debug("Attempting to retrieve 'defaultNamingContext'...");
string domain = (string)ldapRoot.Properties["defaultNamingContext"][0]; //THIS IS WHERE I HIT THE COMEXCEPTION
logger.Debug("Retrieved 'defaultNamingContext': " + domain);
if (!domain.IsEmpty())
{
logger.Debug("'SetCurrentDomain'; Instantiating partitions/configuration LDAP entry");
DirectoryEntry parts = new DirectoryEntry(server + "/CN=Partitions,CN=Configuration," + domain, username, password);
logger.Debug("'SetCurrentDomain'; Successfully instantiated partitions/configuration LDAP entry");
foreach (DirectoryEntry part in parts.Children)
{
if (part.Properties["nCName"] != null && (string)part.Properties["nCName"][0] != null)
{
logger.Debug("'SetCurrentDomain'; Found property nCName");
if ((string)part.Properties["nCName"][0] == domain)
{
logger.Debug("'SetCurrentDomain'; nCName matched defaultnamingcontext");
result = (string)part.Properties["NetBIOSName"][0];
logger.Debug("'SetCurrentDomain'; Found NetBIOSName (friendly domain name): " + result);
break;
}
}
}
}
logger.Debug("finished setting current domain...");
}
catch (Exception ex)
{
logger.Error("error attempting to set domain:" + ex.ToString());
}
return result;
}
изменить
Я добавил этот примерный метод, чтобы попытаться предложить, но получаю исключение: "Unspecified error", когда я нахожу вызов "FindAll()" на поисковике. Входящая строка: "CN = TEST USER, CN = Пользователи, DC = tempe, DC = ktregression, DC = com"
private string GetUserDomain(string dn)
{
string domain = string.Empty;
string firstPart = dn.Substring(dn.IndexOf("DC="));
string secondPart = "CN=Partitions,CN=Configuration," + firstPart;
DirectoryEntry root = new DirectoryEntry(secondPart, textBox2.Text, textBox3.Text);
DirectorySearcher searcher = new DirectorySearcher(root);
searcher.SearchScope = SearchScope.Subtree;
searcher.ReferralChasing = ReferralChasingOption.All;
searcher.Filter = "(&(nCName=" + firstPart + ")(nETBIOSName=*))";
try
{
SearchResultCollection rs = searcher.FindAll();
if (rs != null)
{
domain = GetProperty(rs[0], "nETBIOSName");
}
}
catch (Exception ex)
{
}
return domain;