简体   繁体   中英

getting user DN with user name LDAP

I want to get user DN with the username provided. What I think is that I want to retrieve all the user data and compare with the username. And now, I have added objectclass in my search filter and I have no idea why is the data is not retrieving. Here are the codes that I currently have.

Hashtable env = new Hashtable();
    env.put(Context.INITIAL_CONTEXT_FACTORY, "com.sun.jndi.ldap.LdapCtxFactory");
    env.put(Context.PROVIDER_URL, url);
    env.put(Context.SECURITY_AUTHENTICATION, "simple");
    env.put(Context.SECURITY_PRINCIPAL, "cn=admin,ou=sa,o=system");
    env.put(Context.SECURITY_CREDENTIALS, "P@ssw0rd");

    try{
    DirContext context = new InitialDirContext(env);
    SearchControls constraints = new SearchControls();
    constraints.setSearchScope(SearchControls.SUBTREE_SCOPE);
    NamingEnumeration result = context.search("", "(objectclass=Person)", constraints);
    while(result.hasMore())
    {
        SearchResult searchResult = (SearchResult) result.next();
        Attributes attrs = searchResult.getAttributes();
        request.setEmail(attrs.get("mail").toString());
        request.setPhoneNumber(attrs.get("personalMobile").toString());
        Attribute ldapattr = attrs.get("photo");
        if(ldapattr != null){
            byte[] photo = (byte[])ldapattr.get();
            request.setPhoto(photo);
        }
    }
    }catch(Exception e){
        System.out.println("can't initialized");
    }
    list.add(request);
    //Specific URL of LDAP with the host and :port 
    return list;
}

Provide a base DN to search. eg ou=users below and add username to filter for faster search Don't get all the user data as you are unnecessarily increasing network traffic and doing additional computational work on the client. LDAP server excels at this kind of searching. CN is indexed by default but givenName may not be indexed; so you might want to add an index for this attribute.

    NamingEnumeration result = context.search("ou=users", 
"(&(objectClass=person)(sAMAccountName=" + userId + "))", constraints);

If you have givenName

NamingEnumeration result = context.search("ou=users", 
    "(&(objectClass=person)(givenName=" + givenName + "))", constraints);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM