Asp.net 中的 Active Directory 性能问题

Active Directory Performance issue in Asp.net

我已经使用活动目录登录

我遇到了一些性能问题

这是我的代码

 public bool IsAuthenticated(String domain, String username, String pwd)
        {

            String domainAndUsername = domain + @"\" + username;
            DirectoryEntry entry = new DirectoryEntry("LDAP://" + _path, domainAndUsername, pwd);

            try
            {   //Bind to the native AdsObject to force authentication.         
                Object obj = entry.NativeObject;

                DirectorySearcher search = new DirectorySearcher(entry);

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

                if (null == result)
                {
                    return false;
                }

                //Update the new path to the user in the directory.
                _path = result.Path;
                _filterAttribute = (String)result.Properties["cn"][0];
            }
            catch (Exception ex)
            {
                throw new Exception("Error authenticating user. " + ex.Message);
            }

            return true;
        }

当我输入正确的用户名和密码时,它运行良好且速度很快。 但是当我输入错误的用户名和密码时,加载速度很慢。


这两行编码

Object obj = entry.NativeObject;
 DirectorySearcher search = new DirectorySearcher(entry);

需要很长时间才能 return 结果,而登录输入是错误的。


所以我的问题是

已经有人在 SO

中问过这个问题

Is using DirectoryServices.NativeObject slow/bad?

但是没有人回答这个问题。请告诉我解决方案:)

它需要很长时间,因为它必须检查每个对象以与输入进行比较,因为它永远找不到正确的对象。

但是,这是在 Active Directory 上对用户进行身份验证的一种不必要的复杂方法。

这要容易得多:

    public bool ValidateCredentials(string domain, string username, string password)
    {
        using (PrincipalContext context = new PrincipalContext(ContextType.Domain, domain))
        {
            return context.ValidateCredentials(username, password);
        }
    }

然后更新值。