本文介绍了使用C#连接时无法联系LDAP服务器的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我编写了以下代码以连接到LDAP服务器并验证用户凭据.
public static string AuthFunction_One(string identity, string password, string containerString, string adServerName, bool useLDAPS, IdentityType identityType)
{
string failedString = "FAILED";
string successString = "SUCCESS";
string returnValue = failedString;
try
{
PrincipalContext ctx = null;
ctx = new PrincipalContext(ContextType.Domain, "ldap://localhost:10389/dc=example,dc=com", "uid=rish,dc=example,dc=com");
UserPrincipal oUserPrincipal = UserPrincipal.FindByIdentity(ctx, identityType, identity);
PrincipalSearchResult<Principal> oPrincipalSearchResult = oUserPrincipal.GetGroups();
if (ctx.ValidateCredentials(identity, password))
{
return successString;
}
else
{
return failedString;
}
}
catch (Exception ex)
{
NLogHelper.GetInstance().Log("ADUtilityClass", "AuthFunction_One", NLog.LogLevel.Debug, "Error in function. Ex: " + ex.ToString());
return failedString;
}
}
这引发了以下异常. >
This is throwing the below exception.
Exception: Exception thrown:
'System.DirectoryServices.AccountManagement.PrincipalServerDownException' in System.DirectoryServices.AccountManagement.dll ("The server could not be contacted.")
当我尝试通过LDAP资源管理器进行连接时,它确实可以连接.以下是我在此处使用的配置.
userdn -> uid=rish,dc=example,dc=com
basedn -> dc=example,dc=com
password -> secret
servername -> localhost
port -> 10389
version -> 3
我在C#代码中做错了什么?任何帮助将不胜感激.
推荐答案
根据您的描述,我创建了一个演示并从侧面再现了您的问题, PrincipalContext 与仅AD 一起使用效果很好.如果您的目录是OpenLDAP/其他目录,请尝试以下代码:
Based on your description, I create a demo and reproduce your issue on my side, it seems thatPrincipalContext works well with AD only. If your directory is OpenLDAP/ any other, then try below code:
try
{
LdapConnection ldapConnection;
string ldapServer = "ldap://localhost:389/dc=example,dc=com";
NetworkCredential credential = new NetworkCredential("username", "password", "domain");
// Create the new LDAP connection
ldapConnection = new LdapConnection(ldapServer);
ldapConnection.Credential = credential;
Console.WriteLine("LdapConnection is created successfully.");
}
catch (Exception e)
{
Console.WriteLine("\r\nUnexpected exception occurred:\r\n\t" + e.GetType() + ":" + e.Message);
}
或像这样使用DirectoryEntry:
Or use DirectoryEntry like this:
DirectoryEntry directoryEntry = new DirectoryEntry("LDAP://example.com", "username", "password");
最诚挚的问候,
吴可乐
这篇关于使用C#连接时无法联系LDAP服务器的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!