LDAPContext.search()返回空结果

时间:2017-02-16 14:03:16

标签: java ldap

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

考虑这个在线测试服务,如何检查用户是否存在?

1 个答案:

答案 0 :(得分:1)

您的搜索过滤器使用sAMAccountName属性,但该属性在测试服务器中不可用。请改用uid