為了中央管理賬戶, 利用LDAP 在公司內部程式作認證及權限管理是正常事. 而在Java 中, 可以透過內部的library 實現. 在示範中會嘗試駁往ApacheDS.
import java.util.Properties; import javax.naming.Context; import javax.naming.NamingEnumeration; import javax.naming.directory.Attributes; import javax.naming.directory.DirContext; import javax.naming.directory.InitialDirContext; import javax.naming.directory.SearchControls; import javax.naming.directory.SearchResult; public void listUsers() throws NamingException { try { Properties initialProperties = new Properties(); initialProperties.put(Context.INITIAL_CONTEXT_FACTORY,"com.sun.jndi.ldap.LdapCtxFactory"); // Connect to LDAP and specific dc. initialProperties.put(Context.PROVIDER_URL, "ldap://localhost:10389/dc=ldap,dc=sample,dc=local"); // Connected user account and password. initialProperties.put(Context.SECURITY_PRINCIPAL, "uid=chunho.ling,ou=users"); initialProperties.put(Context.SECURITY_CREDENTIALS, "abcd1234"); DirContext context = new InitialDirContext(initialProperties); // Query specific LDAP object class. String searchFilter="(objectClass=inetOrgPerson)"; SearchControls controls=new SearchControls(); controls.setSearchScope(SearchControls.SUBTREE_SCOPE); NamingEnumeration<SearchResult> users=context.search("ou=users", searchFilter, controls); // Loop and list out user name in console. while(users.hasMore()) { SearchResult searchResult=users.next(); Attributes attr=searchResult.getAttributes(); String commonName=attr.get("cn").get(0).toString(); String surnName=attr.get("sn").get(0).toString(); System.out.println("Name = "+commonName); System.out.println("Surname = "+surnName); System.out.println("-------------------------------------------"); } } catch (Exception ex) { ex.printStackTrace(); } }
Leave a Reply