5
我有一個應用程序使用LDAP和簡單數據庫身份驗證來登錄用戶。只有當用戶不在LDAP上下文中時,應用程序纔會檢查他是否存在於數據庫中。所以我需要一種方法來檢查用戶是否存在LDAP中,而不知道密碼。我提到用戶名是獨一無二的。我該如何檢查給定的用戶名是否存在?
我使用此代碼,如果我有一個正確的用戶名和密碼,它的工作原理。如果密碼或用戶名錯誤,我會得到一個異常。如果我可以得到不同的例外,那麼這將是理想的,如果用戶名不存在,其他如果提供的密碼錯誤。
String username = "test";
String password = "pass";
Hashtable<String, String> environment = new Hashtable<String, String>();
environment.put(Context.INITIAL_CONTEXT_FACTORY, "com.sun.jndi.ldap.LdapCtxFactory");
environment.put(Context.PROVIDER_URL, "ldap://server.example.com:389");
environment.put(Context.SECURITY_AUTHENTICATION, "simple");
String user = username + "@example.com";
environment.put(Context.SECURITY_PRINCIPAL, user);
environment.put(Context.SECURITY_CREDENTIALS, password);
try
{
DirContext context = new InitialDirContext(environment);
String searchBase = "DC=server,DC=example,DC=COM";
String FILTER = "(&(objectClass=user)(objectCategory=person)((sAMAccountName=" + username + ")))";
SearchControls ctls = new SearchControls();
ctls.setSearchScope(SearchControls.SUBTREE_SCOPE);
NamingEnumeration<SearchResult> answer = context.search(searchBase, FILTER, ctls);
SearchResult result = answer.next();
Attribute email = result.getAttributes().get("mail");
Attribute cn = result.getAttributes().get("cn");
System.out.println(cn + " : " + email);
context.close();
}
catch (AuthenticationException a)
{
Logger.getLogger().info("Authentication failed: " + a.getExplanation());
}
catch (NamingException e)
{
Logger.getLogger().info("Failed to bind to LDAP: " + e.getExplanation());
}
謝謝。這是唯一的方法?爲了進行搜索,必須登錄嗎? – radonys
也許不是,我不知道。我只是解釋爲什麼*您的*代碼需要用戶的密碼來檢查它是否存在於LDAP中。 –
一些管理員將允許匿名搜索。請諮詢您的目錄服務器管理員。 –