DirectorySearcher始终返回空结果

时间:2019-03-21 18:52:28

标签: c# asp.net-mvc active-directory

我有针对AD在PowerShell上运行的这段代码,它可以正常工作,它会返回用户

$de = New-Object -TypeName System.DirectoryServices.DirectoryEntry - 
ArgumentList "LDAP://DC=organizationname,DC=com", "username", "password", 
"Secure"
$ds = New-Object -TypeName System.DirectoryServices.DirectorySearcher - 
ArgumentList $de, "(&(objectClass=user)(anr=myusername))", 
@("sAMAccountName", "mail", "displayName"), "Subtree"
$ds.FindAll()

但是当我使用DirectorySearcher在asp.net mvc上运行相同的代码时,它总是返回空结果。

可能是什么问题?我该如何调试?

string username = ConfigurationManager.AppSettings["ADUsername"];
string password = ConfigurationManager.AppSettings["ADPassword"];
string displayName = ConfigurationManager.AppSettings["ADDisplayName"];

using (var de = new DirectoryEntry(adUsersContainer, username, password, AuthenticationTypes.Secure))
{
    IList<User> items = new List<User>();
    string[] props = { "sAMAccountName", "mail", displayName };

    using (var ds = new DirectorySearcher(de, "(&(objectClass=user)(anr=" + anr + "))", props, SearchScope.Subtree))
    {
        ds.PageSize = 1000;
        IEnumerable<SearchResult> results = SafeFindAll(ds);

        foreach (SearchResult result in results)
        {
            var user = new User
                    {
                        Username = GetPropertyValue(result.Properties, "sAMAccountName"),//;//[0].ToString(),
                        Email = GetPropertyValue(result.Properties, "mail"),
                        DisplayName = GetPropertyValue(result.Properties, displayName)
                    };

            if (!string.IsNullOrWhiteSpace(user.Email))
            {
                items.Add(user);
            }
        }
    }

    return items;
}

这是一个Intranet应用程序,托管且应与Windows身份验证一起使用,因此基本上登录到其计算机上的用户应该能够访问网站而无需登录,但:

  1. 他们不断获得登录提示
  2. 并且当我们尝试从AD中提取用户时(我们可以从Identity中获取用户-见下文-),但仍然返回空结果。

代码:

string identityName = User.Identity.Name;
int index = identityName.LastIndexOf('\\');
string username = index >= 0 ? identityName.Substring(index + 1) : identityName;

有何想法?

0 个答案:

没有答案