Skip to content

Instantly share code, notes, and snippets.

@lbehnke
Created May 18, 2016 05:39
Show Gist options
  • Save lbehnke/645754368f52def6dfa49aaa8d3a3f8e to your computer and use it in GitHub Desktop.
Save lbehnke/645754368f52def6dfa49aaa8d3a3f8e to your computer and use it in GitHub Desktop.
Read from Microsoft ActiveDirectory
class LdapApp
{
static DirContext ldapContext;
public static void main (String[] args) throws NamingException
{
try
{
Hashtable<String, String> ldapEnv = new Hashtable<String, String>(11);
ldapEnv.put(Context.INITIAL_CONTEXT_FACTORY, "com.sun.jndi.ldap.LdapCtxFactory");
ldapEnv.put(Context.PROVIDER_URL, "ldap://localhost:389");
ldapEnv.put(Context.SECURITY_AUTHENTICATION, "simple");
ldapEnv.put(Context.SECURITY_PRINCIPAL, "cn=administrator,cn=users,ou=dev,dc=de");
ldapEnv.put(Context.SECURITY_CREDENTIALS, "pwd");
ldapEnv.put(Context.SECURITY_PROTOCOL, "simple"); // or SSL
ldapContext = new InitialDirContext(ldapEnv);
/* Define search */
SearchControls search = new SearchControls();
String returnedAtts[]={"sn","givenName", "samAccountName"};
search.setReturningAttributes(returnedAtts);
search.setSearchScope(SearchControls.SUBTREE_SCOPE);
String searchFilter = "(&(objectClass=user))";
String searchBase = "dc=dom,dc=fr";
NamingEnumeration<SearchResult> answer = ldapContext.search(searchBase, searchFilter, searchCtls);
/* Iterate results */
while (answer.hasMoreElements())
{
SearchResult sr = (SearchResult)answer.next();
System.out.println("Name: " + sr.getName());
Attributes attrs = sr.getAttributes();
System.out.println("User login: " + attrs.get("samAccountName"));
}
}
catch (Exception e)
{
e.printStackTrace();
}
finally {
if (ldapContext != null) ldapContext.close();
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment