[Java] 利用javax.naming.directory 去接駁LDAP

為了中央管理賬戶, 利用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();
		}
}

 

About C.H. Ling 262 Articles
a .net / Java developer from Hong Kong and currently located in United Kingdom. Thanks for Google because it solve many technical problems so I build this blog as return. Besides coding and trying advance technology, hiking and traveling is other favorite to me, so I will write down something what I see and what I feel during it. Happy reading!!!

Be the first to comment

Leave a Reply

Your email address will not be published.


*


This site uses Akismet to reduce spam. Learn how your comment data is processed.