4
votes

I have a Web application. For LDAP I am using Apache Directive Studio. I want to get all the users and their roles in my application.

I am able to get particular information by using the following code.

    import java.util.Properties;
    import javax.naming.Context;
    import javax.naming.NamingException;
    import javax.naming.directory.Attributes;
    import javax.naming.directory.DirContext;
    import javax.naming.directory.InitialDirContext;

    public class DirectorySample {
        public DirectorySample() {

        }

        public void doLookup() {
            Properties properties = new Properties();
            properties.put(Context.INITIAL_CONTEXT_FACTORY,
                    "com.sun.jndi.ldap.LdapCtxFactory");
            properties.put(Context.PROVIDER_URL, "ldap://localhost:10389");
            try {
                DirContext context = new InitialDirContext(properties);
                Attributes attrs = context.getAttributes("dc=example,dc=com");
                System.out.println("ALL Data: " + attrs.toString());
            } catch (NamingException e) {
                e.printStackTrace();
            }
        }
        public static void main(String[] args) {
            DirectorySample sample = new DirectorySample();
            sample.doLookup();
        }

    }

enter image description here
I want to show all users and roles list, so i need to change query or something else Thanks in Advance.

1
(1) The code you have posted doesn't do any such thing as retrieve a particular user's data. It retrieves the attributes of "dc=example,dc=com", which isn't a user entry at all. (2) Retrieving the data for all users is a potentially enormous query. Why do you think you need to do this?user207421
okay..yes i want all users and roles. can you suggest me query...for that @EJPMitul Maheshwari
The query depends on how you've defined your DIT, which you've given zero information about. For example, what objectClass are you using for users?user207421
Actually i m not much know about ldap, i have added the image of of DIT now you get idea for query @EJPMitul Maheshwari
Actually you haven't answe red my question. Try again.user207421

1 Answers

1
votes

You can use org.apache.directory.ldap.client.api.LdapConnection for easy search.

Once you bind the connection, do search on the connection. Loop through the cursor to get the object you want. The first parameter should match your the DN of the users parent. Below example is just to give you an idea.

EntryCursor cursor = connection.search( "ou=users, dc=example, dc=com", "(objectclass=*)", SearchScope.ONELEVEL, "*" );

    while ( cursor.next() )
    {
        Entry entry = cursor.get();
            //play with the entry
    }