Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

read LDAP with Java

Tags:

java

ldap

I need an efficient way to read all users from LDAP. I have a super/root password in Java

All I need is just to list the names.

All ideas are appreciated.

like image 805
Adnan Avatar asked Oct 14 '22 04:10

Adnan


1 Answers

You can find a nice code sample here:

Hashtable<String, Object> env = new Hashtable<String, Object>();
env.put(Context.INITIAL_CONTEXT_FACTORY, "com.sun.jndi.ldap.LdapCtxFactory");
env.put(Context.PROVIDER_URL, "ldap://localhost:389/dc=fraglab,dc=net");
env.put(Context.SECURITY_AUTHENTICATION, "simple");
env.put(Context.SECURITY_PRINCIPAL, "cn=admin,dc=fraglab,dc=net");
env.put(Context.SECURITY_CREDENTIALS, "yannis");
DirContext ctx = new InitialDirContext(env);
SearchControls searchControls = new SearchControls();
searchControls.setSearchScope(SearchControls.SUBTREE_SCOPE);
searchControls.setCountLimit(10);
NamingEnumeration<SearchResult> namingEnumeration =
        ctx.search("", "(uid=*)", new Object[]{}, searchControls);
while (namingEnumeration.hasMore()) {
    SearchResult sr = namingEnumeration.next();
    System.out.println("DN: " + sr.getName());
    System.out.println(sr.getAttributes().get("uid"));
    System.out.println("Password:" + new String((byte[]) sr.getAttributes().get("userPassword").get()));
}
ctx.close();

It uses the LDAP Naming Service Provider for the Java Naming and Directory Interface JNDI, and should do what you want with small adaptations (e.g. put the name of you server, at least). The documentation for the ldap provider is quite good, and will help you extend it to your needs.

like image 164
tonio Avatar answered Oct 20 '22 15:10

tonio