千家信息网

VB.NET如何验证LDAP用户身份

发表于:2024-09-26 作者:千家信息网编辑
千家信息网最后更新 2024年09月26日,这篇文章主要为大家展示了"VB.NET如何验证LDAP用户身份",内容简而易懂,条理清晰,希望能够帮助大家解决疑惑,下面让小编带领大家一起研究并学习一下"VB.NET如何验证LDAP用户身份"这篇文章
千家信息网最后更新 2024年09月26日VB.NET如何验证LDAP用户身份

这篇文章主要为大家展示了"VB.NET如何验证LDAP用户身份",内容简而易懂,条理清晰,希望能够帮助大家解决疑惑,下面让小编带领大家一起研究并学习一下"VB.NET如何验证LDAP用户身份"这篇文章吧。

首先,我要讲的LDAP不是微软的Active Directory目录服务,而是运行在SUN One上面的目录服务。

请看VB.NET验证LDAP用户身份的代码(部分敏感信息删节):

  1. Private Sub btnTest_Click()Sub btnTest_
    Click(ByVal sender As System.Object,
    ByVal e As System.EventArgs) Handles
    btnTest.Click

  2. Dim LoginName As String = txtUser.Text

  3. Dim LoginPwd As String = txtPwd.Text

  4. If LoginPwd = "" Then

  5. txtResult.Text = "* Password can not be blank."

  6. Exit Sub

  7. End If

  8. Dim myDirectorySearcher As DirectorySearcher

  9. Dim mySearchResult As SearchResult

  10. Dim myDirectoryEntry As DirectoryEntry

  11. Dim UserName As String

  12. txtResult.Text = ""

  13. Try

  14. If myDirectoryEntry.Exists("LDAP:
    //ldapserver.com/uid=" & LoginName & ",
    ou=people,ou=intranet,dc=yourdomainname,
    dc=com") Then

  15. Try

  16. myDirectoryEntry = New DirectoryEntry
    ("LDAP://ldapserver.com/ou=people,
    ou=intranet,dc=yourdomainname,dc=com",
    "uid=" & LoginName & ",ou=people,ou=intranet,
    dc=yourdomainname,dc=com", LoginPwd,
    AuthenticationTypes.ServerBind)

  17. myDirectorySearcher = New Directory
    Searcher(myDirectoryEntry)

  18. myDirectorySearcher.Filter = "
    (uid="
    & txtUser.Text & ")"

  19. myDirectorySearcher.PropertiesToLoad.
    Add("DisplayLastName")

  20. myDirectorySearcher.PropertiesToLoad.
    Add("DisplayFirstName")

  21. mySearchResult = myDirectorySearcher.FindOne

  22. If mySearchResult Is Nothing Then

  23. txtResult.Text += "* Login failed."

  24. Else

  25. txtResult.Text += ">>> Login passed!" & vbCrLf

  26. UserName = mySearchResult.GetDirectory
    Entry().Properties("DisplayFirstName").
    Value & " " & mySearchResult.GetDirectory
    Entry().Properties("DisplayLastName").Value

  27. txtResult.Text += UserName & vbCrLf

  28. End If

  29. Catch ex As Exception

  30. txtResult.Text += "* Login failed." &
    vbCrLf & ex.Message

  31. End Try

  32. Else

  33. txtResult.Text += "* Invalid user login name."

  34. End If

  35. Catch ex As Exception

  36. txtResult.Text += "* Can not access the
    LDAP server." & vbCrLf & ex.Message

  37. End Try

  38. End Sub

这里要说明一下:

1、必须检验密码不能为空,否则会造成验证有误,即空密码能通过验证,不知道为什么。

2、LDAP://......这最前面的四个字母LDAP必须大写!否则报未知错误,不知道为什么,还得我走了一段弯路。

3、ldapserver.com需要替换成LDAP服务器的地址。

4、LDAP://......地址后面的参数,要根据你要访问的LDAP的设置而定。

5、如果密码不对,会引发异常,所以我在异常处理中捕获,但是不知道这样是否正确。

6、If mySearchResult Is Nothing Then 这句我觉得是废话,好像怎么也不会为True,如果密码不对,会引发异常的,但是不放心还是加上这句,可能是我的判断逻辑有问题。

以上是"VB.NET如何验证LDAP用户身份"这篇文章的所有内容,感谢各位的阅读!相信大家都有了一定的了解,希望分享的内容对大家有所帮助,如果还想学习更多知识,欢迎关注行业资讯频道!

0