我是 AD 编程的新手,但经过几周的研究,我发现了以下三种使用帐户名作为搜索参数在 Active Directory 中搜索用户的方法:
选项 1 - FindByIdentity
Dim ctx As New PrincipalContext(ContextType.Domain, Environment.MachineName)
Dim u As UserPrincipal = UserPrincipal.FindByIdentity(ctx, IdentityType.SamAccountName, "MYDOMAIN\Administrator")
If u Is Nothing Then
Trace.Warn("No user found.")
Else
Trace.Warn("Name=" & u.Name)
Trace.Warn("DisplayName=" & u.DisplayName)
Trace.Warn("DistinguishedName=" & u.DistinguishedName)
Trace.Warn("EmployeeId=" & u.EmployeeId)
Trace.Warn("EmailAddress=" & u.EmailAddress)
End If
选项 2 - DirectorySearcher
Dim connPath As String = "LDAP://" & Environment.MachineName
Dim de As New DirectoryEntry(connPath)
Dim ds As New DirectorySearcher(de)
ds.Filter = String.Format("(&(objectClass=user)(anr={0}))", Split(User.Identity.Name, "\")(1))
ds.PropertiesToLoad.Add("name")
ds.PropertiesToLoad.Add("displayName")
ds.PropertiesToLoad.Add("distinguishedName")
ds.PropertiesToLoad.Add("employeeId")
ds.PropertiesToLoad.Add("mail")
Dim src As SearchResult = ds.FindOne()
If src Is Nothing Then
Trace.Warn("No user found.")
Else
For Each propertyKey As String In src.Properties.PropertyNames
Dim valueCollection As ResultPropertyValueCollection = src.Properties(propertyKey)
For Each propertyValue As Object In valueCollection
Trace.Warn(propertyKey & "=" & propertyValue.ToString)
Next
Next
End If
选项 3 - PrincipalSearcher
Dim ctx2 As New PrincipalContext(ContextType.Domain, Environment.MachineName)
Dim sp As New UserPrincipal(ctx2)
sp.SamAccountName = "MYDOMAIN\Administrator"
Dim s As New PrincipalSearcher
s.QueryFilter = sp
Dim p2 As UserPrincipal = s.FindOne()
If p2 Is Nothing Then
Trace.Warn("No user found.")
Else
Trace.Warn(p2.Name)
Trace.Warn(p2.DisplayName)
Trace.Warn(p2.DistinguishedName)
Trace.Warn(p2.EmployeeId)
Trace.Warn(p2.EmailAddress)
End If
所有这三种方法都返回相同的结果,但我想知道是否有任何特定方法比其他方法更好或更差?
选项 1 或 3 似乎是最好的,因为它们提供了强类型的属性名称,但我可能错了吗?我的总体目标是在网站上使用 Windows 身份验证时根据通过 Web 浏览器传递的用户主体值在 AD 中找到单个用户(例如“MYDOMAIN\MyUserAccountName”)