2017-02-16 109 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