Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
Java Active Directory Browser
package org.mule.example.echo;
import java.util.ArrayList;
import java.util.Hashtable;
import java.util.List;
import javax.naming.Context;
import javax.naming.NamingEnumeration;
import javax.naming.directory.Attribute;
import javax.naming.directory.Attributes;
import javax.naming.directory.SearchControls;
import javax.naming.directory.SearchResult;
import javax.naming.ldap.InitialLdapContext;
import javax.naming.ldap.LdapContext;
import org.mule.example.echo.dto.User;
public class ActiveDirectoryBrowser {
private String ldapUrl;
private String principle;
private String password;
private String organizationalUnit;
public ActiveDirectoryBrowser(String ldapUrl, String principle, String password, String organizationalUnit) {
this.ldapUrl = ldapUrl;
this.principle = principle;
this.password = password;
this.organizationalUnit = organizationalUnit;
}
public List<String> getUserGroups(User user) throws Exception {
List<String> groups = new ArrayList<String>();
String returnedAtts[] = { "tokenGroups" };
SearchControls searchContext = new SearchControls(SearchControls.OBJECT_SCOPE,0,0,returnedAtts,false,false);
//paceholder for an LDAP filter that will store SIDs of the groups the user belongs to
StringBuffer groupsSearchFilter = new StringBuffer();
groupsSearchFilter.append("(|");
LdapContext ctx = null;
try {
ctx = new InitialLdapContext(getConnectionSettings(), null);
NamingEnumeration<SearchResult> results = ctx.search(user.DN,"(&(objectClass=user))", searchContext);
while (results.hasMoreElements()) {
SearchResult item = results.next();
Attributes metadata = item.getAttributes();
Attribute attribute = metadata.get("tokenGroups");
NamingEnumeration<?> tokens = attribute.getAll();
while (tokens.hasMore()) {
byte[] sid = (byte[])tokens.next();
groupsSearchFilter.append("(objectSid=" + binarySidToStringSid(sid) + ")");
}
}
groupsSearchFilter.append(")");
// get names of the groups
SearchControls groupsSearchCtls = new SearchControls();
groupsSearchCtls.setSearchScope(SearchControls.SUBTREE_SCOPE);
String groupsReturnedAtts[]={"sAMAccountName"};
groupsSearchCtls.setReturningAttributes(groupsReturnedAtts);
NamingEnumeration<?> groupsAnswer = ctx.search(organizationalUnit, groupsSearchFilter.toString(), groupsSearchCtls);
while (groupsAnswer.hasMoreElements()) {
SearchResult sr = (SearchResult)groupsAnswer.next();
Attributes attrs = sr.getAttributes();
if (attrs != null) {
groups.add(String.valueOf(attrs.get("sAMAccountName").get()));
}
}
} finally {
if (ctx != null) {
ctx.close();
}
}
return groups;
}
public List<User> getUser(String query) throws Exception {
String returnedAtts[] = { "distinguishedName", "sAMAccountName", "userPrincipalName", "displayName", "cn", "sn", "givenName", "mail", "department", "company", "manager", "telephoneNumber" };
SearchControls searchContext = new SearchControls(SearchControls.SUBTREE_SCOPE,0,0,returnedAtts,false,false);
List<User> users = new ArrayList<User>();
LdapContext ctx = null;
try {
ctx = new InitialLdapContext(getConnectionSettings(), null);
NamingEnumeration<SearchResult> results = ctx.search(this.organizationalUnit,"(&(objectClass=user)" + query + ")", searchContext);
while (results.hasMoreElements()) {
SearchResult item = results.next();
Attributes metadata = item.getAttributes();
NamingEnumeration<String> attributes = metadata.getIDs();
List<String> availableValues = new ArrayList<String>();
while (attributes.hasMoreElements()) {
availableValues.add(attributes.next());
}
User u = new User();
u.CommonName = availableValues.contains("cn") ? String.valueOf(metadata.get("cn").get()) : "";
u.Company = availableValues.contains("company") ? String.valueOf(metadata.get("company").get()) : "";
u.Department = availableValues.contains("department") ? String.valueOf(metadata.get("department").get()) : "";
u.DN = availableValues.contains("distinguishedName") ? String.valueOf(metadata.get("distinguishedName").get()) : "";
u.Email = availableValues.contains("mail") ? String.valueOf(metadata.get("mail").get()) : "";
u.FamilyName = availableValues.contains("sn") ? String.valueOf(metadata.get("sn").get()) : "";
u.GivenName = availableValues.contains("givenName") ? String.valueOf(metadata.get("givenName").get()) : "";
u.Manager = availableValues.contains("manager") ? String.valueOf(metadata.get("manager").get()) : "";
u.Phone = availableValues.contains("telephoneNumber") ? String.valueOf(metadata.get("telephoneNumber").get()) : "";
u.UserId = availableValues.contains("sAMAccountName") ? String.valueOf(metadata.get("sAMAccountName").get()) : "";
String[] strings = u.DN.split(",");
for (String string : strings) {
u.Organization.add(string);
}
users.add(u);
}
} finally {
if (ctx != null) {
ctx.close();
}
}
return users;
}
private Hashtable<String, String> getConnectionSettings() {
Hashtable<String, String> env = new Hashtable<String, String>();
env.put(Context.INITIAL_CONTEXT_FACTORY, "com.sun.jndi.ldap.LdapCtxFactory");
env.put(Context.PROVIDER_URL, ldapUrl);
env.put(Context.SECURITY_AUTHENTICATION, "simple");
env.put(Context.SECURITY_PRINCIPAL, principle);
env.put(Context.SECURITY_CREDENTIALS, password);
env.put("java.naming.ldap.attributes.binary", "tokenGroups");
return env;
}
private static String binarySidToStringSid(byte[] SID) {
String strSID = "";
// convert the SID into string format
long version;
long authority;
long count;
long rid;
strSID = "S";
version = SID[0];
strSID = strSID + "-" + Long.toString(version);
authority = SID[4];
for (int i = 0; i < 4; i++) {
authority <<= 8;
authority += SID[4 + i] & 0xFF;
}
strSID = strSID + "-" + Long.toString(authority);
count = SID[2];
count <<= 8;
count += SID[1] & 0xFF;
for (int j = 0; j < count; j++) {
rid = SID[11 + (j * 4)] & 0xFF;
for (int k = 1; k < 4; k++) {
rid <<= 8;
rid += SID[11 - k + (j * 4)] & 0xFF;
}
strSID = strSID + "-" + Long.toString(rid);
}
return strSID;
}
}
@terrancesnyder
Copy link
Author

terrancesnyder commented Oct 17, 2011

Test case...

    @Test
    public void testConnection() throws Exception {
        ActiveDirectoryBrowser ad = new ActiveDirectoryBrowser("ldap://itcontoso.com", "<user>@itcontoso.com", "<password>", "DC=itcontoso,DC=com");

        List<User> list = ad.getUser("(sAMAccountName=NEST*)");
        for (User user : list) {
            System.out.println(user.UserId + " (" + user.DN + ") " + StringUtils.collectionToCommaDelimitedString(user.Organization));
            List<String> groups = ad.getUserGroups(user);
            for (String string : groups) {
                System.out.println("\t " + string);
            }
        }
    }

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment