gpt4 book ai didi

c# - 具有C#DirectoryEntry类的多个LDAP连接器

转载 作者:行者123 更新时间:2023-12-03 13:04:40 28 4
gpt4 key购买 nike

我正在使用DirectoryEntry类进行LDAP身份验证。当我使用单个LDAP连接字符串时,它可以正常工作。但是,一旦我开始在多个LDAP连接字符串的多个线程上执行代码,即使用户名和密码正确,它也会开始随机引发身份验证异常。
我正在使用以下代码。

public bool IsAuthenticated(string path, string domain, string group, string username, string pwd)
{
string domainAndUsername = domain + @"\" + username;

LogManager.Application.DebugFormat("Inside IsAuthenticated for User {0} from Domain {1} and Group {2} of Path {3} ", username, domain, group, path);

try
{
using (DirectoryEntry entry = new DirectoryEntry(path, domainAndUsername, pwd))
{

entry.AuthenticationType = AuthenticationTypes.Secure;
entry.RefreshCache();
//Bind to the native AdsObject to force authentication.
object obj = entry.NativeObject;

using (DirectorySearcher search = new DirectorySearcher(entry))
{

search.Filter = "(SAMAccountName=" + username + ")";
search.PropertiesToLoad.Add("cn");
SearchResult result = search.FindOne();

if (null == result)
{
LogManager.Application.ErrorLogFormat("User {0} is not available in Domain {1}", username, domain);
return false;
}
}
LogManager.Application.DebugFormat("User {0} is available in Domain {1}", username, domain);
return true;
}
}
catch (Exception ex)
{
LogManager.Application.ErrorLogFormat("Exception occured while authenticating user {0} : Error {1} ", username, ex.Message);
return false;
}
}

此功能通过ASMX Web服务公开。该Web服务由多个用户同时执行。每个用户都提供路径 (LDAP://{IP}/DC={Domain},DC=COM),域和凭据。因此,同时为多个LDAP连接执行代码。

更新:

这是ASMX Web服务功能,它调用上述功能:
public class ValidateUserService : System.Web.Services.WebService
{

[WebMethod]
public Models.AuthenticationToken IsUserAuthenticated(string username, string password, string partnerName)
{
string path;
string group;
string domain;
// Internal Code to pull the domain name, group and path from the db with help of partnerName.
//each partner will have different path (LDAP conenction string) and domain.
bool isAuthenticated = IsAuthenticated(path, domain, group, username, password);

}
}

我观察到的是,当来自不同AD的多个用户尝试执行此代码时,它会随机引发身份验证错误。
如您所见,代码没有任何静态变量。因此,对于每个调用,它都会创建 DirectoryEntry的新实例。因此,在较高级别,此设置代码应与多个LDAP连接一起使用。

话虽如此,有没有人看到这种行为?在内部,.net框架是否在多个 DirectoryEntry实例之间共享数据?一个进程可以同时具有多个LDAP连接吗?
任何帮助,建议或指示,我们将不胜感激。

最佳答案

我发现了该问题的解决方法,如果其他人遇到相同的问题,则将其发布。我尝试使用以下方法来使用AD/LDAP:

  • 使用DirectoryEntry类
  • 使用LdapConnection和NetworkCredential类
  • 使用PrincipalContext类

  • 我观察到的是,如果应用程序一次与多个AD服务器一起使用并同时打开与多个AD服务器的连接,则DirectoryEntry方法将不起作用。对于有效的凭据,它将引发“未经授权的访问”异常。我的猜测是某些数据/变量是共享的,并且它会尝试针对错误的AD服务器对用户进行身份验证。我研究了汇编代码,并确认它使用了静态变量。这可能是真正的原因,但不是100%肯定。
    如果应用程序需要同时打开到多个AD服务器的连接,我的解决方法是使用其他两种方法。在过去的六个月中,我已经通过大约10个同时连接对其进行了测试,并且工作正常。

    希望如果有人遇到同样的问题,这会有所帮助。

    关于c# - 具有C#DirectoryEntry类的多个LDAP连接器,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29766263/

    28 4 0
    Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
    广告合作:1813099741@qq.com 6ren.com