简体   繁体   中英

System.DirectoryServices is slow

I am working on to authenticate user using my company AD. This code is working but taking more than 25-30 seconds to return DirectorySearcher results. What can I do to improve its response time?

public bool ADauthentication(string userName,string password)
        {
            try
            {
                string domain = ConfigurationManager.AppSettings["DirectoryDomain"];
                string path = ConfigurationManager.AppSettings["DirectoryPath"];
                string domainAndUserName = domain + @"\" + userName;
                DirectoryEntry entry = new DirectoryEntry(path+"CN=Users,DC=myDomain,DC=com", userName, password);
                entry.AuthenticationType = AuthenticationTypes.Secure;
                DirectorySearcher search = new DirectorySearcher(entry);
                search.Filter = "(SAMAccountName=" + userName+")";
                search.PropertiesToLoad.Add("CN");
                SearchResult result = search.FindOne();
                if (result == null)
                {
                    return false;
                }
                return true;
            }
            catch(Exception ex)
            {
                log.Error($"Error: {ex.ToString()}");
                return false;
            }
        }

I faced similar issue with AD but i solved this problem by caching the results. You can create some background process to sync AD and your data source as well.

Use the System.DirectoryServices.AccountManagement namespace instead:

https://msdn.microsoft.com/en-us/library/bb154889(v=vs.110).aspx

using (var context = new PrincipalContext(ContextType.Domain))
{
    return context.ValidateCredentials(username, password);
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM