- 浏览: 91575 次
- 性别:
- 来自: 武汉
文章分类
最新评论
-
jinnianshilongnian:
TheMatrix 写道CL0724 写道xiaobadi 写 ...
spring3配置文件中的<context:property-placeholder>标签 -
TheMatrix:
CL0724 写道xiaobadi 写道:<contex ...
spring3配置文件中的<context:property-placeholder>标签 -
hovei:
[b][/b][i][/i][u][/u]引用
[img][ ...
安全测试 关于会话标识未更新的解决方法 -
CL0724:
xiaobadi 写道:<context:propert ...
spring3配置文件中的<context:property-placeholder>标签 -
xiaobadi:
:<context:property-placehold ...
spring3配置文件中的<context:property-placeholder>标签
spring使用ldap
- 博客分类:
- Java编程
为了读取公司域账号,使用上ldap接口,Java编码如下 ;
maven项目添加
如上是获取用户的代码,但是我想校验用户的用户名密码是否正确,经过网上查找资料,spring目前没有找到可以做到的方法,所有,还是使用原生的API,代码如下
附件是spring-ldap-reference.pdf文档,可以再详细研究
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-reference.pdf (196.9 KB)
- 下载次数: 6
发表评论
-
java读写锁ReentrantReadWriteLock的初体验
2015-10-14 23:51 7721业务要求: 消息中间件kafka即时发送消息对象,stor ... -
注解式springMVC的demo
2015-09-14 20:13 1326项目中使用springmvc,使用注解标签,spring版本3 ... -
ArrayList和LinkedList的区别
2014-10-20 15:20 672一般大家都知道ArrayList和LinkedList的大致区 ... -
java 中将以逗号分隔的字符串按照N个一组划分的方法
2013-10-29 23:38 6465import java.util.ArrayList; ... -
java反射demo
2013-05-25 00:53 838/** * */ package *; ... -
java中ArrayList和LinkedList的区别 转自http://pengcqu.iteye.com/blog/502676
2013-05-25 00:50 851JAVA语言中的反射机制: ... -
struts OGNL(转载)
2013-03-14 23:12 779Struts2使用之值栈与OGNL-使用 访问属性 ... -
java禁止不需要的HTTP 方 法
2012-10-30 19:03 2860项目安全扫描,报告: 启用了不安全的HTTP 方法 安全风险 ... -
安全测试 关于会话标识未更新的解决方法
2012-10-30 16:05 25265最近本人搭了一个框架 ... -
java关键字,native,strictfp,transient,volatile (转自http://blog.csdn.net/sodino)
2012-10-29 20:56 862Java关键字(keywords) ... -
Java中各类Cache机制实现解决方案(转自http://www.csdn.net/article/2010-04-09/263704)
2012-10-29 17:37 1184在Java中,不同的类都有自己单独的Cache机制,实现的方法 ... -
Java编程中“为了性能”需做的26件事(转自http://www.csdn.net/article/2012-06-01/2806249)
2012-10-29 17:18 776下面是参考网络资源总 ... -
一些我需要用的资料
2012-10-16 22:51 0flex在线参考资料http://help.adobe.com ... -
Log4j简介(转载自http://www.iteye.com/topic/165955)
2012-10-12 14:36 994Log4j的简介: Log4j是Apache的一个开放源代码 ... -
Log4j入门(转载自http://xuxn.iteye.com/blog/416380)
2012-10-12 14:34 964首先要将 log4j-1.2.8.jar & comm ... -
关于java数据连接池的一些配置(转载自http://qrqzhujinyi.iteye.com/blog/698279)
2012-10-11 14:43 884数据库连接池配置 概述 ... -
JAVA考试知识覆盖要点
2012-09-29 16:14 0JAVA考试知识覆盖要点: (1)常用的集合类,如Set、Ma ... -
Java1.5泛型指南中文版(Java1.5 Generic Tutorial)(转帖)
2012-09-25 10:08 700由于文章字数太多,附上地址吧http://blog.csdn. ... -
关于java泛型的学习
2012-10-09 18:47 1207java中我们经常用泛型的占位符,T E K V的含义 T = ... -
一个生成验证码的类
2012-09-24 11:08 1065package com.huawei.tsm.business ...
相关推荐
使用spring-ldap-core测试链接ldap com.ldap.test.service包下为Junit测试类
Spring Data LDAP API。 Spring Data LDAP 开发文档。 官网 Spring Data LDAP API。
Spring LDAP。 官网 Spring LDAP API。 Spring LDAP 开发文档。
spring_ldap spring_ldap spring_ldap
去掉JAR包了。Spring+LDAP实现单点登录SSO 单点登录 LDAP SPRING
rar包:一个Web工程, 主要有,利用Spring-ldap对LDAP的基本操作(查询,增删改);Extjs实现的对Ldap的树状结构的显示,结构有点类似Softerra LDAP;一个测试类。 pdf:spring-ldap-reference.pdf Extjs.pdf ...
spring-ldap1.3.1,一种框架技术用来实现对ldap服务器增删改查数据的工具包。
Practical Spring LDAP is your guide to developing Java-based enterprise applications using the Spring LDAP Framework. This book explains the purpose and fundamental concepts of LDAP before giving a ...
spring-ldap-core-1.3.0.RELEASE.jar
spring-ldap-1.2.jar jar包
spring_ldap1.3的chm格式api
spring-ldap-core-1.3.0.RC1.jar
spring ldap的使用
spring-ldap-reference spring-ldap-reference spring-ldap-reference
最新spring Ldap jar包 The following distinct jar files are included in the distribution. This list specifies the respective contents and third-party dependencies.
Spring 实现LDAP 域认证,内有个人项目的实例分析,,希望大家参考,也可以给意见
本人亲手所写一个关于spring-ldap完整的例子,包含多种方法的增删改查,有兴趣的朋友可以下载看看,有代码类和用到的相关包
包含spring-ldap的简单操作的例子和EXT结合展示 以及相应的文档
spring-security-ldap-1.3.2
进阶-使用Spring Security3.2搭建LDAP认证授权和Remember-me