UserPrincipal.FindByIdentity()始终返回null

我正在使用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 */ } 

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

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

更新:

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

在此处输入图像描述

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

 UserPrincipal user = UserPrincipal.FindByIdentity(context, IdentityType.Name, "UserA"); 

但我仍然无效。

更新2(已解决):

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

 using (PrincipalContext context = new PrincipalContext(ContextType.Domain, "myDomain")) { // code here... } 

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

 UserPrincipal user = UserPrincipal.FindByIdentity(context, IdentityType.SamAccountName, email); 

问题解决了。

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


旧答案 :但您似乎正在向其发送电子邮件地址。 所以这确实总是什么也没有回报。

AD不会将电子邮件地址视为唯一标识符,因此您不能将FindByIdentity与电子邮件地址一起使用。

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