我需要检查此用户是否存在于AD中。所以我尝试使用PrincipalContext建立与安全LDAP的连接。我不确定我使用的方法是否是最佳做法? 在某些计算机中,它可以使用普通LDAP建立连接,但无法使用安全LDAP
建立连接Module Module1
Sub Main()
Console.Write("user name:")
Dim username As String = Console.ReadLine()
Console.Write("domain:")
Dim domain As String = Console.ReadLine()
Console.WriteLine("try connecting LDAP...")
If ConnectionLDAP(username, domain) Then
Console.WriteLine("successful")
Else
Console.WriteLine("failed")
End If
Console.WriteLine("try connecting secure LDAP...")
If SecureConnectionLDAP(username, domain & ":636") Then
Console.WriteLine("successful")
Else
Console.WriteLine("failed")
End If
Console.ReadKey()
End Sub
Function ConnectionLDAP(ByVal userName As String, ByVal domain As String) As Boolean
Dim result As Boolean
Try
Dim d As DirectoryServices.ActiveDirectory.Domain = DirectoryServices.ActiveDirectory.Domain.GetDomain(New DirectoryContext(DirectoryContextType.Domain, domain))
Dim container As String = ""
For Each i As String In d.Name.Split(".")
container &= "DC=" & i & ","
Next
If container(container.Length - 1) = "," Then container = container.Remove(container.Length - 1)
Using domainContext = New PrincipalContext(ContextType.Domain, domain, container, ContextOptions.Negotiate Or ContextOptions.Signing Or ContextOptions.Sealing)
Using foundUser = UserPrincipal.FindByIdentity(domainContext, IdentityType.SamAccountName, userName)
If foundUser Is Nothing Then
result = False
Else
result = True
End If
End Using
End Using
Catch ex As Exception
' errMsgReturn = "The LDAP server could not be contacted."
result = False
End Try
Return result
End Function
Function SecureConnectionLDAP(ByVal userName As String, ByVal domain As String) As Boolean
Dim result As Boolean
Try
Dim d As DirectoryServices.ActiveDirectory.Domain = DirectoryServices.ActiveDirectory.Domain.GetDomain(New DirectoryContext(DirectoryContextType.Domain, domain))
Dim container As String = ""
For Each i As String In d.Name.Split(".")
container &= "DC=" & i & ","
Next
If container(container.Length - 1) = "," Then container = container.Remove(container.Length - 1)
Using domainContext = New PrincipalContext(ContextType.Domain, domain, container, ContextOptions.Negotiate Or ContextOptions.Signing Or ContextOptions.Sealing Or ContextOptions.SecureSocketLayer)
Using foundUser = UserPrincipal.FindByIdentity(domainContext, IdentityType.SamAccountName, userName)
If foundUser Is Nothing Then
result = False
Else
result = True
End If
End Using
End Using
Catch ex As Exception
' errMsgReturn = "The LDAP server could not be contacted."
result = False
End Try
Return result
End Function
End Module