spring使用ldap

为了读取公司域账号,使用上ldap接口,Java编码如下 ;
maven项目添加
<dependency>
			<groupId>org.springframework.ldap</groupId>
			<artifactId>spring-ldap-core</artifactId>
			<version>2.0.2.RELEASE</version>
		</dependency>

/**
 * 
 */
package com.howbuy.uaa.ldap;

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

import org.springframework.ldap.core.AuthenticationSource;
import org.springframework.ldap.core.LdapTemplate;
import org.springframework.ldap.core.support.LdapContextSource;

/**
 * @author qiankun.li
 * 
 */
public class UaaLdapTemplate {

	private LDAPAuthentication authentication;

	private static LdapTemplate template;
	
	private Map<String, List<User>> cacheMap = new HashMap<String, List<User>>();
	
	private final String USER_CACHE_KEY = "user_cache_key";

	/**
	 * ldap服务器URL
	 */
	private String url;
	/**
	 * baseDn
	 */
	private String baseDn;
	/**
	 * ldap服务器账号
	 */
	private String principal;
	/**
	 * ldap服务器密码
	 */
	private String credentials;

	void init() {
		LdapContextSource cs = new LdapContextSource();
		cs.setCacheEnvironmentProperties(false);
		cs.setUrl(url);
		cs.setBase(baseDn);
		cs.setAuthenticationSource(new AuthenticationSource() {
			@Override
			public String getCredentials() {
				return credentials;
			}

			@Override
			public String getPrincipal() {
				return principal;
			}
		});
		template = new LdapTemplate(cs);
	}

	/**获取所有的用户数据
	 * @param isFromCache 是否从本地缓存取数据 true/false
	 * @return
	 */
	public List<User> getAllUser(boolean isFromCache) {
		List<User> result = null;
		boolean isFromLocal = false;
		if(isFromCache){
			result = cacheMap.get(USER_CACHE_KEY);
			if(null==result){
				isFromLocal = true;
			}
		}else{
			isFromLocal = true;
		}
		if(isFromLocal){
			result = new ArrayList<User>();
			String baseCeo = "OU=CEO";
			String base_hk = "OU=staff-hk,OU=howbuy-hk";
			String base_pd = "OU=staff-pd,OU=howbuy-pd";
			List<User> ceo = template.search(baseCeo, "(objectclass=user)",
					new UserMapper());
			List<User> hk = template.search(base_hk, "(objectclass=user)",
					new UserMapper());
			List<User> pd = template.search(base_pd, "(objectclass=user)",
					new UserMapper());
			
			result.addAll(ceo);
			result.addAll(hk);
			result.addAll(pd);
			putUsersToCache(result);
		}
		return result;
	}

	private void putUsersToCache(List<User> result){
		cacheMap.put(USER_CACHE_KEY, result);
		System.out.println("put  key ["+USER_CACHE_KEY+"] value into localCache successed");
	}
	
	/**
	 * 判断用户是否合法,当用户名密码都正确的时候返回true,否则false
	 * @param UID
	 * @param password
	 * @return
	 */
	public boolean authenricate(String UID, String password) {
		return authentication.authenricate(UID, password);
	}

	public String getUrl() {
		return url;
	}

	public void setUrl(String url) {
		this.url = url;
	}

	public String getBaseDn() {
		return baseDn;
	}

	public void setBaseDn(String baseDn) {
		this.baseDn = baseDn;
	}

	public String getPrincipal() {
		return principal;
	}

	public void setPrincipal(String principal) {
		this.principal = principal;
	}

	public String getCredentials() {
		return credentials;
	}

	public void setCredentials(String credentials) {
		this.credentials = credentials;
	}

	public LDAPAuthentication getAuthentication() {
		return authentication;
	}

	public void setAuthentication(LDAPAuthentication authentication) {
		this.authentication = authentication;
	}

}

如上是获取用户的代码,但是我想校验用户的用户名密码是否正确,经过网上查找资料,spring目前没有找到可以做到的方法,所有,还是使用原生的API,代码如下
package com.howbuy.uaa.ldap;

import java.util.Hashtable;

import javax.naming.AuthenticationException;
import javax.naming.Context;
import javax.naming.NamingEnumeration;
import javax.naming.NamingException;
import javax.naming.directory.SearchControls;
import javax.naming.directory.SearchResult;
import javax.naming.ldap.Control;
import javax.naming.ldap.InitialLdapContext;
import javax.naming.ldap.LdapContext;

import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

public class LDAPAuthentication {
	private static final Logger LOGGER = LoggerFactory
			.getLogger(LDAPAuthentication.class);

	private String url;
	private String baseDn;
	private String principal;
	private String credentials;
	private String factory = "com.sun.jndi.ldap.LdapCtxFactory";
	private LdapContext ctx = null;
	private final Control[] connCtls = null;

	private void LDAP_connect() throws Exception {
		if (null == ctx) {
			Hashtable<String, String> env = new Hashtable<String, String>();
			env.put(Context.INITIAL_CONTEXT_FACTORY, factory);
			env.put(Context.PROVIDER_URL, url + baseDn);
			env.put(Context.SECURITY_AUTHENTICATION, "simple");

			env.put(Context.SECURITY_PRINCIPAL, principal);
			env.put(Context.SECURITY_CREDENTIALS, credentials);
			// 此处若不指定用户名和密码,则自动转换为匿名登录
			try {
				ctx = new InitialLdapContext(env, connCtls);
			} catch (javax.naming.AuthenticationException e) {
				throw e;
			} catch (Exception e) {
				throw e;
			}
		}
	}

	private String getUserDN(String uid) throws Exception {
		String userDN = "";
		LDAP_connect();
		try {
			SearchControls constraints = new SearchControls();
			constraints.setSearchScope(SearchControls.SUBTREE_SCOPE);
			NamingEnumeration<SearchResult> en = ctx.search("","sAMAccountName=" + uid, constraints);
			if (en == null || !en.hasMoreElements()) {
				LOGGER.warn("未找到用户:" + uid);
				return userDN;
			}
			// maybe more than one element
			while (en != null && en.hasMoreElements()) {
				Object obj = en.nextElement();
				if (obj instanceof SearchResult) {
					SearchResult si = (SearchResult) obj;
					userDN += si.getName();
					userDN += "," + baseDn;
				}
			}
		} catch (Exception e) {
			LOGGER.error("查找用户[" + uid + "]时产生异常", e.getMessage());
		}
		return userDN;
	}

	public boolean authenricate(String UID, String password) {
		boolean valide = false;
		String userDN = "";
		try {
			userDN = getUserDN(UID);
			if(StringUtils.isNotBlank(userDN)){
				LOGGER.info("userDN:" + userDN);
				ctx.addToEnvironment(Context.SECURITY_PRINCIPAL, userDN);
				ctx.addToEnvironment(Context.SECURITY_CREDENTIALS, password);
				ctx.reconnect(connCtls);
				LOGGER.info(userDN + ",验证通过");
				valide = true;
			}
		} catch (AuthenticationException e) {
			LOGGER.info(userDN + ",验证失败", e.getMessage());
			valide = false;
		} catch (NamingException e) {
			LOGGER.info(userDN + ",验证失败", e.getMessage());
			valide = false;
		} catch (Exception e) {
			LOGGER.info(userDN + ",验证失败", e.getMessage());
		}
		
		try {
			ctx.close();
		} catch (NamingException e) {
			LOGGER.info("关闭LdapContext对象失败", e.getMessage());
		}finally{
			if(null!=ctx){
				ctx=null;
			}
		}
		
		return valide;
	}

	public String getUrl() {
		return url;
	}

	public void setUrl(String url) {
		this.url = url;
	}

	public String getBaseDn() {
		return baseDn;
	}

	public void setBaseDn(String baseDn) {
		this.baseDn = baseDn;
	}

	public String getPrincipal() {
		return principal;
	}

	public void setPrincipal(String principal) {
		this.principal = principal;
	}

	public String getCredentials() {
		return credentials;
	}

	public void setCredentials(String credentials) {
		this.credentials = credentials;
	}

}
package com.howbuy.uaa.ldap;

import java.util.List;

import javax.naming.NamingException;
import javax.naming.directory.Attribute;
import javax.naming.directory.Attributes;

import org.springframework.ldap.core.AttributesMapper;

public class UserMapper implements AttributesMapper<User> {

	@Override
	public User mapFromAttributes(Attributes attributes) throws NamingException {

		User user = new User();
		Attribute attributeCn = attributes.get("cn");
		if (null != attributeCn) {
			user.setUserName(attributeCn.get().toString());
		}
		Attribute attributeAcc = attributes.get("sAMAccountName");
		if (null != attributeAcc) {
			user.setAccount(attributeAcc.get().toString());
		}
		Attribute attributeMail = attributes.get("mail");
		if (null != attributeMail) {
			user.setEmail(attributeMail.get().toString());
		}
		Attribute attributeUid = attributes.get("member");
		if (null != attributeUid) {
			int size = attributeUid.size();
			List<String> memberList = user.getMemberList();
			for (int i = 0; i < size; i++) {
				String ms = attributeUid.get(i).toString();
				memberList.add(ms);
			}
		}
		
		Attribute attributeDistinguishedName = attributes.get("distinguishedName");
		if(null!=attributeDistinguishedName){
			user.setDistinguishedName(attributeDistinguishedName.get().toString());
		}else{
			return null;
		}
		return user;
	}

}
/**
 * 
 */
package com.howbuy.uaa.ldap;

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

/**
 * @author qiankun.li
 * 
 */
public class User {

	/**
	 * 域账号
	 */
	private String account;
	
	/**
	 * 中文名称
	 */
	private String userName;
	
	/**
	 * email
	 */
	private String email;
	
	/**
	 * 详细Dn
	 */
	private String distinguishedName;

	private List<String> memberList = new ArrayList<String>(0);

	public String getUserName() {
		return userName;
	}

	public void setUserName(String userName) {
		this.userName = userName;
	}

	public List<String> getMemberList() {
		return memberList;
	}

	public void setMemberList(List<String> memberList) {
		this.memberList = memberList;
	}

	public String getEmail() {
		return email;
	}

	public void setEmail(String email) {
		this.email = email;
	}

	public String getAccount() {
		return account;
	}

	public void setAccount(String account) {
		this.account = account;
	}

	public String getDistinguishedName() {
		return distinguishedName;
	}

	public void setDistinguishedName(String distinguishedName) {
		this.distinguishedName = distinguishedName;
	}

}
结合起来使用,ok,
附件是spring-ldap-reference.pdf文档,可以再详细研究

你可能感兴趣的:(spring使用ldap)