使用類LdapContext的我搜索一個特定的用戶,並設法得到它是否存在。但是search()
方法返回空響應。LDAPContext.search()返回空結果
private int checkUserOnLDAP() {
String strLDAPServer = "ldap://ldap.forumsys.com:389";
String strLDAPPricipal = "cn=read-only-admin,dc=example,dc=com";
String strPassword = "password";
String strSearchBase = "ou=mathematicians,dc=example,dc=com";
String strUserToSearch = "riemann";
Hashtable<String, String> environment = new Hashtable<String, String>();
environment.put(Context.INITIAL_CONTEXT_FACTORY, "com.sun.jndi.ldap.LdapCtxFactory");
environment.put(Context.PROVIDER_URL, strLDAPServer);
environment.put(Context.SECURITY_AUTHENTICATION, "simple");
environment.put(Context.SECURITY_PRINCIPAL, strLDAPPricipal);
environment.put(Context.SECURITY_CREDENTIALS, strPassword);
LdapContext ctxGC = null;
try {
ctxGC = new InitialLdapContext(environment, null);
ctxGC.getAttributes("");
} catch (NamingException e) {
System.err.print("SEARCHER BLOCKED USER");
e.printStackTrace();
} catch (Exception e) {
System.err.print("SEARCHER WRONG PASSWORD");
e.printStackTrace();
}
System.out.println("SEARCHER LOGIN SUCCESSFUL");
System.out.println("NOW TRYING TO SEARCH");
try {
String searchFilter = "(&(objectClass=user)(sAMAccountName=" + strUserToSearch + "))";
String returnedAtts[] = new String[0];
SearchControls searchCtls = new SearchControls();
searchCtls.setReturningAttributes(returnedAtts);
searchCtls.setSearchScope(SearchControls.SUBTREE_SCOPE);
NamingEnumeration<?> answer = ctxGC.search(strSearchBase, searchFilter, searchCtls);
if (answer.hasMoreElements()) {
Object a = answer.nextElement();
System.out.println("SUCCESFULLY, FOUND USER");
return 0;
} else {
System.out.println("ANSWER HAS NO ELEMENTS");
}
} catch (Exception e) {
System.out.println("SEARCH FAILED");
e.printStackTrace();
}
return 0;
}
測試時,我使用網上LDAP服務:http://www.forumsys.com/tutorials/integration-how-to/ldap/online-ldap-test-server/
考慮到這一在線測試服務,我怎麼能檢查用戶是否存在?
我已經創建了一個樣本。它可以幫助你:https://github.com/shardayyyy/ldap/blob/1d7ef92334c529b25f3cf4ecd5d1e90d8e2139dc/src/LDAPTest.java – ziLk