Java LDAP - Determine if user in a given group?

后端 未结 10 814
时光取名叫无心
时光取名叫无心 2020-12-12 20:18

We logon users to Active Directory via LDAP using the Java LDAP API. We want to enhance our logon functionality to further check if the user is in a given AD group. Does a

10条回答
  •  青春惊慌失措
    2020-12-12 20:54

    I found this useful:

    retrieves-group-membership for Active Directory

    And I have this piece of working code:

    import java.util.Hashtable;
    import javax.naming.CompositeName;
    import javax.naming.Context;
    import javax.naming.Name;
    import javax.naming.NameParser;
    import javax.naming.NamingEnumeration;
    import javax.naming.NamingException;
    import javax.naming.directory.Attribute;
    import javax.naming.directory.Attributes;
    import javax.naming.directory.DirContext;
    import javax.naming.directory.InitialDirContext;
    import javax.naming.directory.SearchControls;
    import javax.naming.directory.SearchResult;
    import javax.naming.ldap.InitialLdapContext;
    import javax.naming.ldap.LdapContext;
    
    public class TestAD1 {
    
        private static String userBase = "DC=SomeName,DC=SomeName,DC=SomeName,DC=SomeName,DC=COM,DC=US";
    
        public static void main(String[] args) {
            TestAD1 tad = new TestAD1();
            try {
                // Create a LDAP Context
                Hashtable env = new Hashtable();
                env.put(Context.INITIAL_CONTEXT_FACTORY, "com.sun.jndi.ldap.LdapCtxFactory");
                env.put(Context.SECURITY_AUTHENTICATION, "simple");
                env.put(Context.SECURITY_PRINCIPAL, "ldap.serviceaccount@domain.com");
                env.put(Context.SECURITY_CREDENTIALS, "drowssap");
                env.put(Context.PROVIDER_URL, "ldap://fully.qualified.server.name:389");
                LdapContext ctx = new InitialLdapContext(env, null);
                InitialDirContext inidircontext = new InitialDirContext(env);
                DirContext dirctx = new InitialLdapContext(env, null);
                System.out.println("Connection Successful.");
    
                // Print all attributes of the name in namespace
                SearchControls sctls = new SearchControls();
                String retatts[] = {"sn", "mail", "displayName", "sAMAccountName"};
                sctls.setReturningAttributes(retatts);
                sctls.setSearchScope(SearchControls.SUBTREE_SCOPE);
                String srchfilter = "(&(objectClass=user)(mail=*))";
                String srchbase = userBase;
                int totalresults = 0;
    
                NamingEnumeration answer = dirctx.search(srchbase, srchfilter, sctls);
                while (answer.hasMoreElements()) {
                    SearchResult sr = (SearchResult) answer.next();
                    totalresults++;
                    System.out.println(">>>  " + sr.getName());
    
                    Attributes attrs = sr.getAttributes();
                    if (answer == null || !answer.hasMore()) {
                        System.out.println("No result found");
                        return;
                    }
    
                    if (attrs != null) {
                        try {
                            System.out.println("    surname: " + attrs.get("sn").get());
                            System.out.println("    Email - ID: " + attrs.get("mail").get());
                            System.out.println("    User - ID: " + attrs.get("displayName").get());
                            System.out.println("    Account Name: " + attrs.get("sAMAccountName").get());
                            tad.GetGroups(inidircontext, attrs.get("sAMAccountName").get().toString());
                        } catch (NullPointerException e) {
                            System.out.println("Error listing attributes..." + e);
    
                        }
                    }
                    System.out.println("Total Results : " + totalresults);
                    // close dir context
                    dirctx.close();
                }
    
                ctx.close();
            } catch (NamingException e) {
                System.out.println("Problem Search Active Directory..." + e);
                //e.printStackTrace();
            }
    
        }
    
        // Get all the groups.
    
        public void GetGroups(InitialDirContext context, String username) throws NamingException {
            String[] attrIdsToSearch = new String[]{"memberOf"};
            String SEARCH_BY_SAM_ACCOUNT_NAME = "(sAMAccountName=%s)";
            String filter = String.format(SEARCH_BY_SAM_ACCOUNT_NAME, username);
            SearchControls constraints = new SearchControls();
            constraints.setSearchScope(SearchControls.SUBTREE_SCOPE);
            constraints.setReturningAttributes(attrIdsToSearch);
            NamingEnumeration results = context.search(userBase, filter, constraints);
            // Fail if no entries found
            if (results == null || !results.hasMore()) {
                System.out.println("No result found");
                return;
            }
            SearchResult result = (SearchResult) results.next();
            Attributes attrs = result.getAttributes();
            Attribute attr = attrs.get(attrIdsToSearch[0]);
    
            NamingEnumeration e = attr.getAll();
            System.out.println(username + " is Member of the following groups  : \n");
            while (e.hasMore()) {
                String value = (String) e.next();
                System.out.println(value);
            }
        }
    
    }
    

提交回复
热议问题