2017-02-16 131 views
4

使用類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/

考慮到這一在線測試服務,我怎麼能檢查用戶是否存在?

+0

我已經創建了一個樣本。它可以幫助你:https://github.com/shardayyyy/ldap/blob/1d7ef92334c529b25f3cf4ecd5d1e90d8e2139dc/src/LDAPTest.java – ziLk

回答

1

您的搜索過濾器使用sAMAccountName屬性,但該屬性在測試服務器中不可用。改爲使用uid

+0

看來我的查詢無法找到與給定的搜索過濾器的任何用戶。但它不適用於「sAMAccountName」和「uid」。 – bahtiyartan

+0

看着服務器,我發現一些記錄的條目已經消失。特別是ou節點是空的。不過,您可以在搜索庫中找到條目dc = example,dc = com。這就是爲什麼你總是應該使用LDAP瀏覽器來檢查你的結果。 – marabu

+0

是的,它的工作原理。用 「DC =例如,DC = COM」 作爲搜索庫和 「(&(objectClass的=人)(UID =黎曼))」 爲濾波器。謝謝。 – bahtiyartan