Get groups using ldap in java

How can I get specific user groups using Active Directory? I get all the groups, but I want to get the groups the user is a member of

  public static String ldapUri = "ldap://pdc.example.com:389";
  public static String usersContainer = "cn=users,dc=example,dc=com";  
  public ArrayList<String> getUserGroups(String email, String password){
    ArrayList<String> list = new   ArrayList<String>();
       Hashtable env = new Hashtable();
    env.put(Context.INITIAL_CONTEXT_FACTORY, "com.sun.jndi.ldap.LdapCtxFactory");
    env.put(Context.PROVIDER_URL, ldapUri);
    env.put(Context.SECURITY_PRINCIPAL, email);
    env.put(Context.SECURITY_CREDENTIALS, password);
    try {
        DirContext ctx = new InitialDirContext(env);
        SearchControls ctls = new SearchControls();
        String[] attrIDs = { "cn" };
        ctls.setReturningAttributes(attrIDs);
        ctls.setSearchScope(SearchControls.ONELEVEL_SCOPE);

        NamingEnumeration answer = ctx.search(usersContainer, "     (objectclass=group)", ctls);
        while (answer.hasMore()) {
        SearchResult rslt = (SearchResult) answer.next();
        Attributes attrs = rslt.getAttributes();
        String groups = attrs.get("cn").toString();
        String [] groupname = groups.split(":");
        String userGroup = groupname[1];
        System.out.println(attrs.get("cn"));
        }
        ctx.close();
        } catch (NamingException e) {
        e.printStackTrace();
    }
    return list;
  }
+4
source share
2 answers

I get all user groups using this

String[] attrIDs = {"cn"};
ctls.setReturningAttributes(attrIDs);
String[] attributes = {"memberOf"};
ctls.setReturningAttributes(attributes);
NamingEnumeration<?> answer = ctx.search(usersContainer, "(&(objectclass=user)(sAMAccountName=userName))", ctls);
+5
source

If you are using Active Directory. User has attribute 'memberOf'; run a search query for a specific user and include the "memberOf" attributes in the returned attributes.

String[] attrIDs = { "cn", "memberOf" };
ctls.setReturningAttributes(attrIDs);
ctls.setSearchScope(SearchControls.ONELEVEL_SCOPE);

NamingEnumeration answer = ctx.search(usersContainer, "(&(objectclass=person)(cn=*sahi*))", ctls);
Attribute

'memberOf' contains the groups to which the user belongs.

+2
source

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


All Articles