简体   繁体   中英

Get groups and users from LDAP

Hi i am trying to fetch all posixGroup from LDAP and the users in this group. Code below is what i have done so far, it returns me all the groups but i am not sure how to get the users for these groups. Please guide me is this approach good? or should i go by first getting the users and then based on GID get the group name?

public static void main(String[] args) {
        Hashtable env = new Hashtable();
        env.put(Context.INITIAL_CONTEXT_FACTORY,"com.sun.jndi.ldap.LdapCtxFactory");
        env.put(Context.PROVIDER_URL,"ldap://192.168.*.*:389");
        env.put(Context.URL_PKG_PREFIXES, "com.sun.jndi.url"); 
        env.put(Context.REFERRAL, "ignore"); 
        env.put(Context.SECURITY_AUTHENTICATION, "simple"); 
        env.put(Context.SECURITY_PRINCIPAL, "cn=manager,dc=*,dc=*"); 
        env.put(Context.SECURITY_CREDENTIALS, "****");

        DirContext ctx;
        try {
            ctx = new InitialDirContext(env);
        } catch (NamingException e) {
            throw new RuntimeException(e);
        }

        NamingEnumeration results = null;
        try {

            SearchControls controls = new SearchControls();
            controls.setSearchScope(SearchControls.SUBTREE_SCOPE);

            results = ctx.search("ou=path,dc=*,dc=*", "(objectClass=posixGroup)",controls);
            // Go through each item in list
            while (results.hasMore()) {
                SearchResult nc = (SearchResult)results.next();
                Attributes att=     nc.getAttributes();                           
                System.out.println("Group Name "+ att.get("cn").get(0));
                System.out.println("GID "+ att.get("GidNumber").get(0));
            }
        } catch (NameNotFoundException e) {
            System.out.println("Error : "+e);
        } catch (NamingException e) {
            throw new RuntimeException(e);
        } finally {
            if (results != null) {
                try {
                    results.close();
                } catch (Exception e) {
                    System.out.println("Error : "+e);
                }
            }
            if (ctx != null) {
                try {
                    ctx.close();
                } catch (Exception e) {
                    System.out.println("Error : "+e);
                }
            }
        }      

    }

Querying all users in a group

It depends which attribute is used by groups in your directory to denote membership. posixGroup uses memberUid with the username as value (defined in RFC 2307 ). There are other possible attributes (member, uniquemember) and values (DN) so check what your directory uses.

So in order to load all users from a group, you would have to:

  1. Query that group, for example with this filter (&(objectClass=posixGroup)(cn=<group name>))
  2. Iterate through all values of memberUid in the group, for each:
    1. Query the user object with (&(objectClass=posixAccount)(uid=<memberUid>))
    2. Then you can access user attributes like uidNumber .

This is not a very efficient way of doing it because it will generate lots of small queries, but as far as I know, LDAP has no means to join a group entry with the user entries it references in a single result (unlike SQL).

You could optimise it a bit by limiting results to the attributes you actually need: gidNumber for the group query and uidNumber for the user query. Using either SearchControls.setReturningAttributes() or a version of DirContext.search() that takes a attributesToReturn argument. It doesn't reduce the number of queries though, only the volume of data returned.

Some more general notes about LDAP usage

  • If your queries have a large number of results (for example "all users"), you might hit your directory's result size limit (typically 5000) and only get partial results.
  • When modifying group membership information, you have to update both posixAccount and posixGroup objects (unless your directory server does it, but I doubt it will), otherwise it becomes inconsistent.

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