Created
June 7, 2017 09:49
-
-
Save amsz/a204d5e60c6743d2d36a9845482453ed to your computer and use it in GitHub Desktop.
LDAP for AD
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import javax.naming.Context; | |
import javax.naming.NamingEnumeration; | |
import javax.naming.NamingException; | |
import javax.naming.directory.*; | |
import java.util.Hashtable; | |
public class TestApp { | |
public static void main(String[] args) { | |
Hashtable<String, String> env = new Hashtable<>(); | |
env.put(Context.INITIAL_CONTEXT_FACTORY, "com.sun.jndi.ldap.LdapCtxFactory"); | |
env.put(Context.PROVIDER_URL, "ldap://192.168.2.2:389"); | |
env.put(Context.SECURITY_AUTHENTICATION, "simple"); | |
env.put(Context.SECURITY_PRINCIPAL, "username"); | |
env.put(Context.SECURITY_CREDENTIALS, "password"); | |
try { | |
DirContext ctx = new InitialDirContext(env); | |
SearchControls sc = new SearchControls(); | |
sc.setSearchScope(SearchControls.ONELEVEL_SCOPE); | |
NamingEnumeration ne = ctx.search("CN=Users,DC=company,DC=com", "objectClass=*", sc); | |
while (ne.hasMore()) { | |
SearchResult result = (SearchResult) ne.next(); | |
Attributes attributes = result.getAttributes(); | |
System.out.println("id=" + parse(attributes.get("samaccountname"))); | |
System.out.println("name=" + parse(attributes.get("cn"))); | |
System.out.println("first_name=" + parse(attributes.get("givenname"))); | |
System.out.println("last_name=" + parse(attributes.get("sn"))); | |
System.out.println("======================="); | |
} | |
ctx.close(); | |
} catch (NamingException e) { | |
e.printStackTrace(); | |
} | |
} | |
// sAMAccountType: 805306368 -> 805306368 | |
static String parse(Attribute attribute) { | |
if(attribute == null) { | |
return "N/A"; | |
} | |
String source = attribute.toString(); | |
int idx = source.indexOf(":"); | |
return source.substring(idx + 1, source.length()).trim(); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment