UserPrincipal.FindByIdentity()始终返回null

MSO*_*ACC 5 c# asp.net ldap active-directory principalcontext

我正在使用LdapAuthentication将用户登录到Active Directory.我想找到用户所属的所有组.我使用以下代码:

string adPath = "LDAP://OU=HR Controlled Users,OU=All Users,DC=myDomain,DC=local";
LdapAuthentication adAuth = new LdapAuthentication(adPath);
try
{
    if (true == adAuth.IsAuthenticated("myDomain", txtLoginEmail.Text, txtLoginPassword.Text))
    {
        string email = txtLoginEmail.Text;

        using (PrincipalContext context = new PrincipalContext(ContextType.Domain))
        {
            UserPrincipal user = UserPrincipal.FindByIdentity(context, IdentityType.Name, email);
            foreach (var group in user.GetGroups())
            {
                Console.WriteLine(group.Name);
            }
        }
    }
}
catch(Exception e) { /* Handle Error */ }
Run Code Online (Sandbox Code Playgroud)

我的问题是,当我调用UserPrincipal.FindByIdentity()时,我总是得到一个空值,即使用户身份验证按预期工作.

为什么会这样?代码或我的方法有问题吗?这是在ASP.NET 4.0 WebForms应用程序中运行.

更新:

显然我一直在使用错误的IdentityType(cn).我检查了调试,帐户名称是"UserA".

在此输入图像描述

所以我尝试手动使用以下代码:

UserPrincipal user = UserPrincipal.FindByIdentity(context, IdentityType.Name, "UserA");
Run Code Online (Sandbox Code Playgroud)

但我仍然无效.

更新2(已解决):

这个问题有两个问题.在声明时我需要指定域控制器的名称PrincipalContext.

using (PrincipalContext context = new PrincipalContext(ContextType.Domain, "myDomain"))
{
   // code here...
}
Run Code Online (Sandbox Code Playgroud)

然后,在搜索UserPrincipal我使用错误时IdentityType; 我正在搜索IdentityType.Name- 这是帐户的名称 - 而不是IdentityType.SamAccountName- 这是用户名.

UserPrincipal user = UserPrincipal.FindByIdentity(context, IdentityType.SamAccountName, email);
Run Code Online (Sandbox Code Playgroud)

问题解决了.

Gab*_*uci 8

通过使用IdentityType.Name,您告诉它您传递的值是帐户的名称(cn属性).如果您想通过用户名(sAMAccountNameatrribute)进行匹配,则需要通过IdentityType.SamAccountName.


旧答案:但你似乎在向它发送电子邮件地址.所以这确实总是没有回报.

AD不会将电子邮件地址视为唯一标识符,因此您无法使用FindByIdentity电子邮件地址.

以下是如何通过电子邮件地址进行搜索的示例:http://doogalbellend.blogspot.ca/2012/03/finding-userprincipal-for-email-address.html

  • 因此,您正在调用“UserPrincipal.FindByIdentity(context, IdentityType.SamAccountName, username)”,其中“username”是 sAMAccountName,但您什么也没得到?`context` 是否指向正确的域?(您的环境中是否有多个域?) (2认同)