首页 > 解决方案 > 无法使用 c# 从活动目录中获取用户属性详细信息

问题描述

我正在尝试使用具有连接到 Active Directory 的完全访问权限的服务帐户凭据连接到 Active Directory,但无法加载用户的属性详细信息。

当我使用“miminstall”帐户登录时会发生这种情况,该帐户无权从 AD 中获取用户详细信息,但在我的应用程序中,我已经传递了在 AD 中具有访问权限的帐户的凭据。

当我使用对 Active Directory 具有完全连接访问权限的不同用户 (adma) 运行 Visual Studio 时,我能够毫无问题地连接和获取用户详细信息。

即使在代码中传递了 adma 帐户凭据,我也不知道为什么会发生这种情况。

public string getADattributes(string DN, string operation)
        {        
            string path = "LDAP://xyz.com";

            DirectoryEntry directoryEntry = new DirectoryEntry(path, "xyz\\adma", "abc", AuthenticationTypes.Secure);
            using (directoryEntry)
            {
                DirectorySearcher objDSearcher = new DirectorySearcher();
                objDSearcher.Filter = "(distinguishedName=" + DN + ")";//search user in AD using DN
                objDSearcher.PropertiesToLoad.Add("whenCreated");
                objDSearcher.PropertiesToLoad.Add("whenChanged");
                objDSearcher.PropertiesToLoad.Add("EmployeeID");
                objDSearcher.SearchScope = SearchScope.Subtree;
                SearchResult result = objDSearcher.FindOne();
                if (result != null)//if count!=0 that means user exist in ad
                {
                    string createdDate = "";
                    string modifiedDate = "";
                    string employeeID = "";
                    if (result.Properties["whenCreated"].Count >0)
                    {
                       //able to come inside if statement when running visual studio using adma account but not when runnning with login account i.e., miminstall
                        createdDate = result.Properties["whenCreated"][0].ToString();
                    }
                    if(result.Properties["whenChanged"].Count>0)
                    {
                        modifiedDate = result.Properties["whenChanged"][0].ToString();
                    }
                    if(result.Properties["EmployeeID"].Count > 0)
                    {
                        employeeID = result.Properties["EmployeeID"][0].ToString();
                    }


                }
                return null;
            }
}

标签: c#.netactive-directory

解决方案


除非这是一次性任务,否则通常会在任务计划程序或 IIS 下的 webapp 中创建任务。

如果这是一个控制台应用程序,请在任务计划程序下添加一个新任务,设置操作以运行您的应用程序(为其提供应用程序 exe 的路径),并将任务用户设置为“adma”

如果它是 webapp 的一部分,请在 IIS 中创建一个新的应用程序池。然后右键单击新创建的应用程序池,转到高级设置 > 身份并提供“adma”的凭据。然后将此应用程序池分配给您的 webapp。

如果这不是计划任务或 web 应用程序,以及偶尔的按需运行,我相信添加模拟将是您的最佳选择。看到这个


推荐阅读