bekirsevki
bekirsevki

Reputation: 321

Getting user info from LDAP by using JAVA

For LDAP, I use LDAP test server namely as Forumsys and we can see users and groups of Forumsys LDAP in the link.

I want to get users' info from their groups. I watched some videos about LDAP on JAVA and tried to do. However, I cannot get them. My code returns null.

How can I solve it? Where is my problem in getting the users' and groups' information?

This my code:

import javax.naming.*;
import javax.naming.directory.*;

import java.util.Hashtable;



public class LDAPV2 {
    public static void main(String[] args) throws NamingException{
        Hashtable <String,String> env = new Hashtable<>();
        env.put(Context.INITIAL_CONTEXT_FACTORY,"com.sun.jndi.ldap.LdapCtxFactory");
        env.put(Context.PROVIDER_URL,"ldap://ldap.forumsys.com:389/dc=example,dc=com");
        env.put(Context.SECURITY_AUTHENTICATION, "simple");
        env.put(Context.SECURITY_PRINCIPAL, "uid=boyle,dc=example,dc=com");
        env.put(Context.SECURITY_CREDENTIALS, "password");

        DirContext context = new InitialDirContext(env);
        DirContext groupCx = (DirContext) context.lookup("ou=chemists");


        NamingEnumeration <Binding> groups = groupCx.listBindings("");
        while (groups.hasMore()){
            String bindingName = groups.next().getName();
            Attributes groupAttributes = groupCx.getAttributes(bindingName);
            Attribute groupName=groupAttributes.get("cn");
            System.out.println(groupName);
        }
    }
}

Upvotes: 2

Views: 11169

Answers (1)

user207421
user207421

Reputation: 310850

ou=chemists is empty in the directory you're looking up. So it has no child bindings, so the while loop never executes.

It does however have some attributes, which you can print with:

    Attributes groupAttributes = groupCx.getAttributes("");
    Attribute groupName = groupAttributes.get("uniqueMember");
    System.out.println(groupName);

Upvotes: 2

Related Questions