---
title: "spring使用ldap"
author: "charsli"
date: "2015-09-14T13:42:14Z"
tags: []
categories: ["互联网"]
slug: "spring-ldap"
draft: false
lastmod: "2015-09-14T13:48:46Z"
id: 2243217
url: "https://charsli.iteye.com/blog/2243217"
---

为了读取公司域账号，使用上ldap接口，Java编码如下 ； maven项目添加 \[code="java"] org.springframework.ldap spring-ldap-core 2.0.2.RELEASE \[/code] \[code="java"]/\** * \*/ 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&gt; cacheMap = new HashMap&gt;(); 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 getAllUser(boolean isFromCache) { List 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(); String baseCeo = "OU=CEO"; String base\_hk = "OU=staff-hk,OU=howbuy-hk"; String base\_pd = "OU=staff-pd,OU=howbuy-pd"; List ceo = template.search(baseCeo, "(objectclass=user)", new UserMapper()); List hk = template.search(base\_hk, "(objectclass=user)", new UserMapper()); List 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 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; } } \[/code] 如上是获取用户的代码，但是我想校验用户的用户名密码是否正确，经过网上查找资料，spring目前没有找到可以做到的方法，所有，还是使用原生的API，代码如下\[code="java"]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 env = new Hashtable(); 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 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; } } \[/code]\[code="java"]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 { @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 memberList = user.getMemberList(); for (int i = 0; i &lt; 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; } } \[/code]\[code="java"]/\** * \*/ 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 memberList = new ArrayList(0); public String getUserName() { return userName; } public void setUserName(String userName) { this.userName = userName; } public List getMemberList() { return memberList; } public void setMemberList(List 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; } } \[/code]结合起来使用，ok， 附件是spring-ldap-reference.pdf文档，可以再详细研究