1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 |
class cLdapAD { static DirContext mocLdapContext; public static void main (String[] args) throws NamingException { try { Hashtable<String, String> loLdapEnv = new Hashtable<String, String>(15); loLdapEnv.put(Context.INITIAL_CONTEXT_FACTORY, "com.sun.jndi.ldap.LdapCtxFactory"); // ldapEnv.put(Context.PROVIDER_URL, "ldap://ldap.kutayzorlu.com:389"); loLdapEnv.put(Context.PROVIDER_URL, "ldap://dom.fr:389"); loLdapEnv.put(Context.SECURITY_AUTHENTICATION, "simple"); //loLdapEnv.put(Context.SECURITY_PRINCIPAL, "cn=admin,cn=users,dc=kutayzorlu,dc=com"); loLdapEnv.put(Context.SECURITY_PRINCIPAL, "cn=Berliner str,ou=OwnerU,dc=Berlin,dc=com"); loLdapEnv.put(Context.SECURITY_CREDENTIALS, "pwd"); //loLdapEnv.put(Context.SECURITY_PROTOCOL, "ssl"); //loLdapEnv.put(Context.SECURITY_PROTOCOL, "simple"); mocLdapContext = new InitialDirContext(loLdapEnv); // Create the search controls SearchControls searchCtls = new SearchControls(); //Specify the attributes to return String returnedAtts[]={"sn","name Given By User", "samAccountName"}; searchCtls.setReturningAttributes(returnedAtts); //Specify the search scope searchCtls.setSearchScope(SearchControls.SUBTREE_SCOPE); //specify the LDAP search filter String searchFilter = "(&(objectClass=user))"; //Specify the Base for the search String searchBase = "dc=Berlin,dc=com"; //initialize counter to total the results int totalResults = 0; // Search for objects using the filter NamingEnumeration<SearchResult> answer = ldapContext.search(searchBase, searchFilter, searchCtls); //Loop through the search results while (answer.hasMoreElements()) { SearchResult sr = (SearchResult)answer.next(); totalResults++; System.out.println(">" + sr.getName()); Attributes attrs = sr.getAttributes(); System.out.println(">>" + attrs.get("samAccountName")); } System.out.println("Total results: " + totalResults); mocLdapContext.close(); } catch (Exception e) { System.out.println(" Search error: " + e); e.printStackTrace(); System.exit(-1); } } } |
Reference Book :
javaxt.com/wiki/Tutorials/Windows/How_to_Authenticate_Users_with_Active_Directory