ldap在项目中的使用

LdapUtils.java

import java.util.Hashtable;

import javax.naming.AuthenticationException;
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.SearchControls;
import javax.naming.directory.SearchResult;
import javax.naming.ldap.InitialLdapContext;

import org.hd.login.model.HDUser;
import org.rd.framework.util.ResourcesUtil;

public class LdapUtils {
	
	
/*

配置信息是从配置文件获取的,下面是在配置文件中的值:
LDAP_URL=ldap://118.23.112.123:389
LDAP_BIND_USER=uid=suolong,cn=users,dc=citics,dc=com
LDAP_BIND_PWD=suolong123
LDAP_BASE_DN=DC=CITICS,DC=COM
LDAP_SECAUTHORITY_DN=dc=citics,dc=com

----------------------------------------------------------

*/
	

	// 设置连接 LDAP的相关信息:

	private Hashtableenv = new Hashtable();
	private String LDAP_URL = ResourcesUtil.getProperties("LDAP_URL"); // LDAP的连接地址
	private String LDAP_BIND_USER = ResourcesUtil.getProperties("LDAP_BIND_USER"); // 用于连接LDAP的BindUser
	// DN,每个应用程序需要一个独立的Binduser,以便将来Audit之用。
	private String LDAP_BIND_PWD = ResourcesUtil.getProperties("LDAP_BIND_PWD"); // BindUser的密码
	private String LDAP_BASE_DN = ResourcesUtil.getProperties("LDAP_BASE_DN"); // BASE DN
	private static InitialLdapContext ldapCtx = null;


	public static LdapUtils ldapUtils;
	// 初始化LDAP Context环境,将其放置到一个Hashtable中。
	public LdapUtils() {
		env.put("java.naming.ldap.version", "3");
		env.put(Context.INITIAL_CONTEXT_FACTORY, "com.sun.jndi.ldap.LdapCtxFactory");
		env.put(Context.SECURITY_AUTHENTICATION, "Simple");
		env.put(Context.PROVIDER_URL, LDAP_URL);
		env.put(Context.SECURITY_PRINCIPAL, LDAP_BIND_USER);
		env.put(Context.SECURITY_CREDENTIALS, LDAP_BIND_PWD);
		env.put(Context.REFERRAL, "follow");
		try {
			ldapCtx = new InitialLdapContext(env, null);

		} catch (NamingException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}
//	static{
//		getInstance();
//	}
//	public static void getInstance(){
//		ldapUtils=new LdapUtils();
//	}
	
	public static LdapUtils getLdapUtils(){
		LdapUtils ll=new LdapUtils(); //以前我写成了单例模式,在实际中发现单例模式有问题,只能改成多例的,每次new出对象
		ldapUtils=ll;
		return ll;
	}

	// 验证密码的函数,如果用户名及密码,比如:username=002794, password = passw0rd.
	public boolean CheckPassword(String username, String password) {
		boolean falg=false;
		// 将要验证的用户名转换为LDAP中的Filter,如:"(&(uid=002794)(objectclass=inetorgperson))"
		String filter = "(&(uid=" + username + ")(objectclass=inetorgperson))";

		// 获得用户的DN
		String dn = getDn(filter);
		if (dn.length() > 0) {
			System.out.println("Get the DN:(" + dn + ")");
		}

		try {
			ldapCtx.addToEnvironment(Context.SECURITY_PRINCIPAL, dn);
			ldapCtx.addToEnvironment(Context.SECURITY_CREDENTIALS, password);
			ldapCtx.reconnect(null);
			// 如果上面reconnect函数没有异常,及认证成功。
			System.out.println(dn + " is authenticated");
			falg=true;
		} catch (NamingException e) {
			System.out.println(e.getMessage());
		}

		return falg;
	}
	
	// 验证密码的函数,如果用户名及密码,比如:username=002794, password = passw0rd.
	public boolean CheckPassword(HDUser hdUser) {
		boolean falg=false;
		String username=hdUser.getUname().trim();
		String password=hdUser.getUpass().trim();
		
		// 将要验证的用户名转换为LDAP中的Filter,如:"(&(uid=002794)(objectclass=inetorgperson))"
		String filter = "(&(uid=" + username + ")(objectclass=inetorgperson))";

		// 获得用户的DN
		String dn = getDn(filter);
		if (dn.length() > 0) {
			System.out.println("Get the DN:(" + dn + ")");
		}

		try {
			ldapCtx.addToEnvironment(Context.SECURITY_PRINCIPAL, dn);
			ldapCtx.addToEnvironment(Context.SECURITY_CREDENTIALS, password);
			ldapCtx.reconnect(null);
			// 如果上面reconnect函数没有异常,及认证成功。
			System.out.println(dn + " is authenticated");
			falg=true;
		} catch (NamingException e) {
			System.out.println(e.getMessage());
		}

		return falg;
	
	}
	//判断是用户不存在还是密码不正确
	public boolean CheckIsHaveUser(HDUser hdUser) {
		boolean falg=false;
		String username=hdUser.getUname().trim();
		String password=hdUser.getUpass().trim();
		
		String filter = "(&(uid=" + username + ")(objectclass=inetorgperson))";

		// 获得用户的DN
		String dn = getDn(filter);
		if (dn.length() > 0) {
			System.out.println("There is the user,and DN:(" + dn + ")");
			falg=true;//存在这个用户
		}
		return falg;
	}

	// 获得用户的DN
	public String getDn(String filter) {
		SearchControls sc = new SearchControls();
		sc.setSearchScope(SearchControls.SUBTREE_SCOPE);
		try {
			NamingEnumeration results = ldapCtx.search(LDAP_BASE_DN, filter, sc);
			if (results.hasMore()) {
				SearchResult sr = results.next();

				// get all attributes.
				Attributes answer = sr.getAttributes();

				for (NamingEnumeration ae = answer.getAll(); ae.hasMore();) {
					Attribute attr = (Attribute) ae.next();
					//System.out.print(attr.getID());
					/* Print each value */
					for (NamingEnumeration e = attr.getAll(); e.hasMore(); System.out.println(attr.getID()+": "+ e.next()))
						;
				}
				return sr.getName() + "," + LDAP_BASE_DN;
			} else {
				return"";
			}

		} catch (NamingException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}

		return"";
	}

	// 关闭LDAP连接。
	public static void close() throws NamingException {
		if(LdapUtils.ldapCtx!=null){
			ldapCtx.close();
		}
	}

	// 获得指定DN的所有属性。
	public void printallattrs(String dn) {
		System.out.println("Get ALL Attribute.class.......");
		try {
			NamingEnumeration results = ldapCtx.search(dn, "(objectclass=*)", new SearchControls(SearchControls.ONELEVEL_SCOPE, 0, 0, null, true, true));
			while (results.hasMore()) {
				SearchResult sr = (SearchResult) results.next();
				System.out.println(">>>" + sr.getName());
				Attributes answer = sr.getAttributes();
				for (NamingEnumeration ae = answer.getAll(); ae.hasMore();) {
					Attribute attr = (Attribute) ae.next();
					System.out.println("attribute: " + attr.getID());
					/* Print each value */
					for (NamingEnumeration e = attr.getAll(); e.hasMore(); System.out.println("value: " + e.next()))
						;
				}
			}
		} catch (NamingException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}
	//根据条件查到对应Attributes
	public Attributes getAttributes(String filter) {
		SearchControls sc = new SearchControls();
		sc.setSearchScope(SearchControls.SUBTREE_SCOPE);
		
		NamingEnumeration results;
		try {
			results = ldapCtx.search(LDAP_BASE_DN, filter, sc);
			if (results.hasMore()) {
				SearchResult sr = (SearchResult) results.next();
				// get all attributes.
				Attributes answer = sr.getAttributes();
				return answer;
			}
		} catch (NamingException e) {
			e.printStackTrace();
		}
		return null;
	}
	
	public void getAttributeLsy(String number) {
		try {
			// Name name = new LdapName("cn=aa,cn=users,dc=lcl,dc=com");
			String[] strIds = { "name", "cn" };
			Attributes allAttrs = ldapCtx
					.getAttributes("uid="+number+",cn=users,dc=citics,dc=com");
			if (null == allAttrs) {
				System.out.println("no attributes");
				return;
			}
			for (NamingEnumeration attrs = allAttrs.getAll(); attrs.hasMore();) {
				Attribute attr = (Attribute) attrs.next();
				System.out.println(attr.getID()+":");
				for (NamingEnumeration values = attr.getAll(); values.hasMore();) {
					System.out.println("\tvalue : " + values.next());
				}
			}
			System.out.println("ok");
		} catch (AuthenticationException e) {
			e.printStackTrace();
		} catch (NamingException e) {
			e.printStackTrace();
		}
	}


}


测试类TestMain.java

import java.util.ArrayList;
import java.util.List;

import java.io.IOException;
import java.net.InetAddress;
import java.net.UnknownHostException;

import org.hd.util.IPUtil;
import org.rd.framework.util.ResourcesUtil;

public class TestMain {
	/**
	 * @param args
	 */
	public static void main(String[] args) {
		String password="password";
		String filter = "(&(uid=009xxx)(objectclass=inetorgperson))";
		
		System.out.println("009xxx:"+LdapUtils.getLdapUtils().CheckPassword("009xxx", "ccc"));
		System.out.println("---------------------------------------------------");
		System.out.println("009xxx--attrabutelsy:");
		LdapUtils.getLdapUtils().getAttributeLsy("009xxx");
		System.out.println("---------------------------------------------------");
		System.out.println("009xxx--attrabute:");
		LdapUtils.getLdapUtils().getAttributes(filter);
		System.out.println("---------------------------------------------------");
		
	}
}


控制台打印:(注:打印的有些信息我给修改了涉及到隐私)

labeledURI: -terminal
mobile: 139xxxxxxxx
givenname: yxx
sn: 009xxx
telephoneNumber: 010-8xxxxxxx
uid: 009xxx
objectclass: inetOrgPerson
objectclass: organizationalPerson
objectclass: person
objectclass: top
cn: 张三
employeeNumber: 009xxx
description: 2010-10-29 15:03:07
Get the DN:(uid=009xxx,cn=users,DC=CITICS,DC=COM)
[LDAP: error code 49 - Invalid Credentials]
009xxx:false
---------------------------------------------------
009xxx--attrabutelsy:
labeledURI:
value : -terminal
mobile:
value : 139xxxxxxxx
givenname:
value : yxx
sn:
value : 009xxx
telephoneNumber:
value : 010-8xxxxxxx
uid:
value : 009xxx
objectclass:
value : inetOrgPerson
value : organizationalPerson
value : person
value : top
cn:
value : 张三
employeeNumber:
value : 009xxx
description:
value : 2010-10-29 15:03:07
ok
---------------------------------------------------
009xxx--attrabute:
---------------------------------------------------

你可能感兴趣的:(ldap在项目中的使用)