Wednesday 20 November 2013

Pulling LDAP attributes out of WLS Active Directory Provider

I recently had to connect to the WLS Active Directory Provider in order to execute some custom Java logic. During my research I happened upon the following blog entry Creating Utilities to Manipulate Users in #Weblogic Using #JMX and #MBeans Which worked perfectly for pulling down usernames and user groups but it seemed to be lacking with respect to pulled down LDAP attributes. I mucked around and came up with the following solution.

To pull the LDAP providers hostname out of the WLS Authentication Provider

Add a method at the bottom of the Utilities class
        public static String getUserDetail(String user, String detail) {
         

            try {
                // Set up the environment for creating the initial context
                Hashtable env = new Hashtable();
                env.put(Context.INITIAL_CONTEXT_FACTORY,
                    "com.sun.jndi.ldap.LdapCtxFactory");
                //CREATE LDAP CONNECTION
                env.put(Context.PROVIDER_URL, "ldap://"+connection.getAttribute(defaultAuthenticator, "Host")+":389/");

                // Authenticate
                env.put(Context.SECURITY_AUTHENTICATION, "simple");
                // PULL PRINCIPAL FROM WLS
                env.put(Context.SECURITY_PRINCIPAL, connection.getAttribute(defaultAuthenticator, "Principal"));
                // UNFORTUNATELY HAD TO HARDCODE CREDENTIAL CAN POSSIBLY MOVE TO CONFIG or WEB.XML
                env.put(Context.SECURITY_CREDENTIALS, "Credential");
                DirContext ctx = new InitialDirContext(env);
                String[] attrIDs = { "sAMAccountName", "cn", "title", "mailnickname", "mail", "manager", "department", "telephoneNumber" };
                SearchControls ctls = new SearchControls();
                ctls.setReturningAttributes(attrIDs);
                ctls.setSearchScope(SearchControls.SUBTREE_SCOPE);
                NamingEnumeration<SearchResult> answer = ctx.search("LDAP OU", "(&(objectCategory=person)(objectClass=user)(sAMAccountName="+user+"))", ctls);
                while (answer.hasMore()) {
                SearchResult sr = (SearchResult) answer.next();
                    return sr.getAttributes().get(detail).toString();
                }


            } catch (Exception e) {
                e.printStackTrace();
            }
            return null;
        }

and voila! We now have a method for pulling out user attributes (mail, manager, title etc) I believe there may be a better way that utilizes JPS which would hopefully circumvent the inclusion of the Credential in my method.

No comments:

Post a Comment