2008-11-19 46 views
1

我正在嘗試使用我在ADAM中創建的用戶對ADAM進行身份驗證。但是,無論使用哪個密碼(正確或不正確),我的搜索都會返回一個有效的DirectoryEntry對象。我會假設如果密碼無效,那麼搜索將返回一個空對象。我的假設是錯誤的還是在下面的代碼中存在缺陷?ADAM認證 - howto?

DirectoryEntry de = new DirectoryEntry("LDAP://localhost:389/cn=Groups,cn=XXX,cn=YYY,dc=ZZZ"); 
DirectorySearcher deSearch = new DirectorySearcher(); 
deSearch.SearchRoot = de; 
deSearch.Filter = "(&(objectClass=user) (cn=" + userId + "))"; 
SearchResultCollection results = deSearch.FindAll(); 
if (results.Count > 0) 
{ 
    DirectoryEntry d = new DirectoryEntry(results[0].Path, userId, password); 
     if (d != null) 
     DoSomething(); 

} 

回答

0

您需要訪問DirectoryEntry的屬性以確定它是否有效。我通常會檢查Guid是否爲空。

bool valid = false; 
using (DirectoryEntry entry = new DirectoryEntry(results[0].Path, userId, password)) 
{ 
    try 
    { 
     if (entry.Guid != null) 
     { 
      valid = true; 
     } 
    } 
    catch (NullReferenceException) {} 
} 

注意:你也想換你的搜索根目錄條目,搜索在using陳述,或當你這樣做,你不要離開資源使用明確處置。

P.S.當您嘗試訪問無效的目錄條目屬性時,我不確定究竟會拋出哪個異常。一些實驗可能是爲了弄清楚哪個例外。您不希望捕獲所有異常,因爲還有其他問題(例如,目錄服務器不可用),您可能希望以不同的方式處理失敗的身份驗證。

+0

太好了,謝謝。這非常有幫助。 現在我遇到了一個問題,無論是否輸入正確的密碼,我都會收到無效的用戶/密碼。有什麼想法嗎? – user26218 2008-11-19 17:37:04