[Java]Connection to LDAP

เนื่องด้วยวงจรชีวิตการทำงาน หนีไม่พ้นการเข้าไปใช้ข้อมูลใน LDAP Server เพื่อทำการ Authen ต่างๆ เผื่อวันหน้าวันหลังจำไม่ได้ก็เลยมา Note Code ในการ Connect ไปยัง Ldap Server
1. Connect ไปยัง LDAP Server ขั้นตอนนั้นไม่แตกต่างจากการ Connect ไปยัง JNDI เลยครับ เนื่องจาก LDAP เป็น Application Protocol ที่มีลักษณะเป็น Directory services

	
private static DirContext getDirContext() throws NamingException {
	Properties pros = new Properties();
	DirContext dirCtx = null;
	try {
		pros.setProperty(Context.INITIAL_CONTEXT_FACTORY, CONT_FACTORY);
		pros.setProperty(Context.SECURITY_AUTHENTICATION, SE_AUTHEN);
		pros.setProperty(Context.PROVIDER_URL, PROVIDER_URL);
		pros.setProperty(Context.SECURITY_PRINCIPAL, SE_PRINCIPAL);
		pros.setProperty(Context.SECURITY_CREDENTIALS, SE_CREDENTIALS);
		//Optional
		pros.setProperty("com.sun.jndi.ldap.connect.pool", "true");
		pros.setProperty("com.sun.jndi.ldap.connect.pool.initsize", "10");
		pros.setProperty("com.sun.jndi.ldap.connect.pool.maxsize", "100");
		pros.setProperty("com.sun.jndi.ldap.connect.pool.prefsize", "25");

		dirCtx = new InitialDirContext(pros);
	} catch (NamingException ne) {
		//Handle exception
	} catch (Exception e) {
		//Handle exception
	}
	return dirCtx;
}


2. Search or Query ข้อมูล

public static void main(String[] args) {
	//Attr for query
	String[] seekAttrs = { "entrydn", "uid", "sn", "cn"};
	//Create search
	SearchControls searchCtl = new SearchControls();
	searchCtl.setSearchScope(SearchControls.ONELEVEL_SCOPE);
	searchCtl.setReturningAttributes(seekAttrs);
		
	//The name of the context or object to search
	String name = "ou=people,o=example.com,o=ORG";
	//Filter cn start with TA
	String filter = "(&(objectclass=inetOrgPerson)(cn=TA*))";
	NamingEnumeration<SearchResult> namingEnum = null;
	try {
		DirContext dirCtx = getDirContext();			
		namingEnum = dirCtx.search(name, filter, searchCtl);
			
		while (namingEnum.hasMore()) {
			SearchResult searchRs = (SearchResult) namingEnum.next();
			Attributes attrs = searchRs.getAttributes();								
			System.out.println("Name : " + searchRs.getName());
				
			NamingEnumeration namingAttr = attrs.getAll();
			while (namingAttr.hasMoreElements()) {
				Attribute attr = (Attribute) namingAttr.next();
				System.out.println("\tAttribute Id : "+attr.getID());
				System.out.println("\tAttribute Value : "+attr.get(0));
			}
		}			
	} catch (NamingException ne) {
		ne.printStackTrace();
	} catch (Exception e){
		e.printStackTrace();
	}finally{
		if(namingEnum != null){
			try{
				namingEnum.close();
				namingEnum = null;
			}catch (NamingException e){}
		}
	}
}

Code ทั้งหมด

/**
 * File Name : Ldap.java
 * Created Date : Aug 3, 2010 : 8:24:51 AM
 * Copyright © 2010 www.fun4station.com
 */
package com.fun4station.example;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Properties;

import javax.naming.Context;
import javax.naming.NamingEnumeration;
import javax.naming.NamingException;
import javax.naming.directory.Attribute;
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;

/**
 * @Author Supot Saelao 
 * @Version 1.0
 */
public class Ldap {

	private static final String CONT_FACTORY = "com.sun.jndi.ldap.LdapCtxFactory";
	private static final String SE_AUTHEN = "example";
	private static final String PROVIDER_URL = "LDAP://127.0.0.1:455";
	private static final String SE_PRINCIPAL = "cn=Directory Manager";
	private static final String SE_CREDENTIALS = "password";
	
	public static void main(String[] args) {
		//Attr for query
		String[] seekAttrs = { "entrydn", "uid", "sn", "cn"};
		//Create search
		SearchControls searchCtl = new SearchControls();
		searchCtl.setSearchScope(SearchControls.ONELEVEL_SCOPE);
		searchCtl.setReturningAttributes(seekAttrs);
		
		//The name of the context or object to search
		String name = "ou=people,o=example.com,o=ORG";
		//Filter cn start with TA
		String filter = "(&(objectclass=inetOrgPerson)(cn=TA*))";
		NamingEnumeration<SearchResult> namingEnum = null;
		try {
			DirContext dirCtx = getDirContext();			
			namingEnum = dirCtx.search(name, filter, searchCtl);
			
			while (namingEnum.hasMore()) {
				SearchResult searchRs = (SearchResult) namingEnum.next();
				Attributes attrs = searchRs.getAttributes();								
				System.out.println("Name : " + searchRs.getName());
				
				NamingEnumeration namingAttr = attrs.getAll();
				while (namingAttr.hasMoreElements()) {
					Attribute attr = (Attribute) namingAttr.next();
					System.out.println("\tAttribute Id : "+attr.getID());
					System.out.println("\tAttribute Value : "+attr.get(0));
				}
			}			
		} catch (NamingException ne) {
			ne.printStackTrace();
		} catch (Exception e){
			e.printStackTrace();
		}finally{
			if(namingEnum != null){
				try{
					namingEnum.close();
					namingEnum = null;
				}catch (NamingException e){}
			}
		}
	}
	
	private static DirContext getDirContext() throws NamingException {
		Properties pros = new Properties();
		DirContext dirCtx = null;
		try {
			pros.setProperty(Context.INITIAL_CONTEXT_FACTORY, CONT_FACTORY);
			pros.setProperty(Context.SECURITY_AUTHENTICATION, SE_AUTHEN);
			pros.setProperty(Context.PROVIDER_URL, PROVIDER_URL);
			pros.setProperty(Context.SECURITY_PRINCIPAL, SE_PRINCIPAL);
			pros.setProperty(Context.SECURITY_CREDENTIALS, SE_CREDENTIALS);
			//Optional
			pros.setProperty("com.sun.jndi.ldap.connect.pool", "true");
			pros.setProperty("com.sun.jndi.ldap.connect.pool.initsize", "10");
			pros.setProperty("com.sun.jndi.ldap.connect.pool.maxsize", "100");
			pros.setProperty("com.sun.jndi.ldap.connect.pool.prefsize", "25");

			dirCtx = new InitialDirContext(pros);
		} catch (NamingException ne) {
			//Handle exception
		} catch (Exception e) {
			//Handle exception
		}

		return dirCtx;
	}
}

หมายเหตุ : เป็นเพียงตัวอย่างง่ายๆ เท่านั้น กรุณาอ่านเอกสาร หรือ Link เพิ่ีมเติมเพื่อความเข้าใจ
ข้อมูลเพิ่มเติม
Tips for LDAP Users
Introduction to LDAP
Lightweight Directory Access Protocol (LDAP)
OpenLDAP
LDAP Function For PHP

  1. No comments yet.

  1. No trackbacks yet.