深入剖析VB.NET驗證LDAP用戶身份
VB.NET對于開發(fā)人員來說是一個功能非常強(qiáng)大的開發(fā)語言。它的功能特點非常突出,比如不能夠提供一個安全性非常高的開發(fā)環(huán)境等。前幾天花了兩天時間研究如何實現(xiàn)VB.NET驗證LDAP用戶身份,看了一些java和vb的代碼,碰了不少釘子,試驗再試驗,終于搞定,與大家分享... #t#
首先,我要講的LDAP不是微軟的Active Directory目錄服務(wù),而是運行在SUN One上面的目錄服務(wù)。
請看VB.NET驗證LDAP用戶身份的代碼(部分敏感信息刪節(jié)):
- Private Sub btnTest_Click()Sub btnTest_
Click(ByVal sender As System.Object,
ByVal e As System.EventArgs) Handles
btnTest.Click - Dim LoginName As String = txtUser.Text
- Dim LoginPwd As String = txtPwd.Text
- If LoginPwd = "" Then
- txtResult.Text = "* Password can not be blank."
- Exit Sub
- End If
- Dim myDirectorySearcher As DirectorySearcher
- Dim mySearchResult As SearchResult
- Dim myDirectoryEntry As DirectoryEntry
- Dim UserName As String
- txtResult.Text = ""
- Try
- If myDirectoryEntry.Exists("LDAP:
//ldapserver.com/uid=" & LoginName & ",
ou=people,ou=intranet,dc=yourdomainname,
dc=com") Then - Try
- 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) - myDirectorySearcher = New Directory
Searcher(myDirectoryEntry) - myDirectorySearcher.Filter = "
(uid=" & txtUser.Text & ")" - myDirectorySearcher.PropertiesToLoad.
Add("DisplayLastName") - myDirectorySearcher.PropertiesToLoad.
Add("DisplayFirstName") - mySearchResult = myDirectorySearcher.FindOne
- If mySearchResult Is Nothing Then
- txtResult.Text += "* Login failed."
- Else
- txtResult.Text += ">>> Login passed!" & vbCrLf
- UserName = mySearchResult.GetDirectory
Entry().Properties("DisplayFirstName").
Value & " " & mySearchResult.GetDirectory
Entry().Properties("DisplayLastName").Value - txtResult.Text += UserName & vbCrLf
- End If
- Catch ex As Exception
- txtResult.Text += "* Login failed." &
vbCrLf & ex.Message - End Try
- Else
- txtResult.Text += "* Invalid user login name."
- End If
- Catch ex As Exception
- txtResult.Text += "* Can not access the
LDAP server." & vbCrLf & ex.Message - End Try
- End Sub
這里要說明一下:
1、必須檢驗密碼不能為空,否則會造成驗證有誤,即空密碼能通過驗證,不知道為什么。
2、LDAP://......這最前面的四個字母LDAP必須大寫!否則報未知錯誤,不知道為什么,還得我走了一段彎路。
3、ldapserver.com需要替換成LDAP服務(wù)器的地址。
4、LDAP://......地址后面的參數(shù),要根據(jù)你要訪問的LDAP的設(shè)置而定。
5、如果密碼不對,會引發(fā)異常,所以我在異常處理中捕獲,但是不知道這樣是否正確。
6、If mySearchResult Is Nothing Then 這句我覺得是廢話,好像怎么也不會為True,如果密碼不對,會引發(fā)異常的,但是不放心還是加上這句,可能是我的判斷邏輯有問題。
總之,這段VB.NET驗證LDAP用戶身份的代碼肯定不是最***的代碼,但是確實是可以完成任務(wù)的代碼,歡迎大家指正。