LDAPContext.search () returns an empty result

Using the LDAPContext class, I am looking for a specific user and trying to get if it exists. But the method search()returns an empty answer.

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;
}

During testing, I use the ldap online service: http://www.forumsys.com/tutorials/integration-how-to/ldap/online-ldap-test-server/

Given this online testing service, how can I check if a user exists?

+4
source share
1 answer

Your search filter uses an attribute sAMAccountName, but this attribute is not available on the test server. Use instead uid.

+1
source

Source: https://habr.com/ru/post/1669935/


All Articles