失眠网,内容丰富有趣,生活中的好帮手!
失眠网 > java 操作 ldap_JAVA操作LDAP总结

java 操作 ldap_JAVA操作LDAP总结

时间:2022-07-29 05:31:39

相关推荐

java 操作 ldap_JAVA操作LDAP总结

一、LDAP概念

LDAP的全称为Lightweight Directory Access Protocol(轻量级目录访问协议), 基于X.500标准, 支持 TCP/IP。

LDAP目录为数据库,通过LDAP服务器(相当于DBMS)处理查询和更新, 以树状的层次结构来存储数据,相对关系型数据库, LDAP主要是优化数据读取的性能,适用于比较少改变、跨平台的信息。

二、Softerra LDAP Administrator

下载安装软件,并配置LDAP

DN:Distinguished Name 唯一标识一条记录的路径,Base DN为基准DN,指定LDAP search的起始DN,即从哪个DN下开始搜索,RDN为叶子结点本身的名字。

DC:Domain Component 一条记录所属区域

OU:Organization Unit 组织单元

CN/UID:一条记录的名字/ID

三、在JAVA中应用LDAP

1、spring配置文件

2、JAVA代码

普通版:

package com.test.dao;

import java.beans.PropertyDescriptor;

import java.lang.reflect.Field;

import java.lang.reflect.InvocationTargetException;

import java.lang.reflect.Method;

import java.util.ArrayList;

import java.util.List;

import javax.naming.Name;

import javax.naming.NamingEnumeration;

import javax.naming.NamingException;

import javax.naming.directory.Attribute;

import javax.naming.directory.Attributes;

import javax.naming.directory.BasicAttribute;

import javax.naming.directory.BasicAttributes;

import javax.naming.directory.ModificationItem;

import mons.beanutils.BeanUtils;

import org.springframework.beans.factory.annotation.Autowired;

import org.springframework.dao.EmptyResultDataAccessException;

import org.springframework.ldap.core.ContextMapper;

import org.springframework.ldap.core.DirContextAdapter;

import org.springframework.ldap.core.DirContextOperations;

import org.springframework.ldap.core.DistinguishedName;

import org.springframework.ldap.core.LdapTemplate;

import org.springframework.ldap.core.support.AbstractContextMapper;

import org.springframework.ldap.filter.AndFilter;

import org.springframework.ldap.filter.EqualsFilter;

import org.springframework.ldap.filter.OrFilter;

import org.ponent;

import com.surekam.model.Person;

import com.surekam.utils.DateCl;

import com.surekam.utils.StringUtil;

@Component

public class UserDAOL {

@Autowired

private LdapTemplate ldapTemplate;

/**

*

* @Description: 添加

*

*/

public boolean addPerson(Person person) {

boolean flag = false;

Name dn = buildUDn(person.getUid());

Attributes buildAddAttributes = buildAddAttributes(person);

ldapTemplate.bind(dn, null, buildAddAttributes);

flag = true;

return flag;

}

/**

*

* @Description: 修改

*

*/

public boolean updatePerson(Person person) {

boolean flag = false;

Name dn = buildUDn(person.getUid());

ModificationItem[] modificationItem = buildModifyAttributes(person);

ldapTemplate.modifyAttributes(dn, modificationItem);

flag = true;

return flag;

}

/**

*

* 多条件获取用户

*

*/

public List getPersonByOu(String ou, String level) {

AndFilter filter = new AndFilter();

OrFilter orFilter1 = new OrFilter();

if ("处级干部".equals(level)) {

orFilter1.or(new EqualsFilter("cuadministrativelevels", "aa"));

orFilter1.or(new EqualsFilter("cuadministrativelevels", "bb"));

orFilter1.or(new EqualsFilter("cuadministrativelevels", "cc"));

orFilter1.or(new EqualsFilter("cuadministrativelevels", "dd"));

}

if ("普通员工".equals(level)) {

orFilter1.or(new EqualsFilter("cuadministrativelevels", "ee"));

orFilter1.or(new EqualsFilter("cuadministrativelevels", "ff"));

orFilter1.or(new EqualsFilter("cuadministrativelevels", "gg"));

}

OrFilter orFilter2 = new OrFilter();

orFilter2.or(new EqualsFilter("departmentnumber", ou));

orFilter2.or(new EqualsFilter("cutransferdnumber", ou));

filter.and(orFilter2);

filter.and(orFilter1);

System.out.println(filter.toString());

List list = ldapTemplate.search("cn=users,dc=hq", filter

.encode(), new PersonContextMapper());

return list;

}

/**

*

* 生成用户DN

*

* @return uid=123455,cn=users,dc=hq

*/

private Name buildUDn(String urdn) {

DistinguishedName dn = new DistinguishedName("");

dn.add("dc", "hq");

dn.add("cn", "users");

dn.add("uid", urdn);

return dn;

}

/**

*

* 组织查询结果

*

*/

public static class PersonContextMapper implements ContextMapper {

public Object mapFromContext(Object ctx) {

if (ctx == null)

return new Person();

DirContextAdapter context = (DirContextAdapter) ctx;

Person per = new Person();

Attributes attrs = context.getAttributes();

NamingEnumeration results = attrs.getAll();

Class c = per.getClass();

while (results.hasMoreElements()) {

try {

Attribute attr = (Attribute) results.next();

String value = attr.get().toString();

if (StringUtil.isNotEmpty(value)) {

String fieldName = attr.getID();

if ("objectclass".equals(fieldName.toLowerCase())) {

continue;

}

Field field = c.getDeclaredField(fieldName

.toLowerCase());

Class fieldClazz = field.getType();

/*

* 如果属性条数大于1,那就是多值属性 attr.getAttributeDefinition()

* 获取多值属性的方法没找到

*/

if (fieldClazz.isAssignableFrom(List.class)) { // 属性值数大于1

NamingEnumeration values = attr.getAll(); // 获取所有值

// LDAP中的多值属性只会是String类型

List list = new ArrayList();

while (values.hasMoreElements()) {

list.add(values.next().toString());

}

BeanUtils.setProperty(per, fieldName.toLowerCase(),

list);

} else {

// 普通属性

BeanUtils.setProperty(per, fieldName.toLowerCase(),

value);

}

}

} catch (IllegalAccessException e) {

e.printStackTrace();

} catch (InvocationTargetException e) {

e.printStackTrace();

} catch (NamingException e) {

e.printStackTrace();

} catch (SecurityException e) {

// TODO Auto-generated catch block

e.printStackTrace();

} catch (NoSuchFieldException e) {

// TODO Auto-generated catch block

e.printStackTrace();

}

}

per.setDn(context.getNameInNamespace());

return per;

}

}

/**

*

* 组织添加数据数据

*

*/

@SuppressWarnings("unchecked")

private Attributes buildAddAttributes(Person p) {

Attributes attrs = new BasicAttributes();

BasicAttribute ocattr = new BasicAttribute("objectclass");

ocattr.add("top");

ocattr.add("person");

ocattr.add("organizationalPerson");

ocattr.add("inetOrgPerson");

ocattr.add("FJTicPerson");

attrs.put(ocattr);

Class c = p.getClass();

Field[] fields = c.getDeclaredFields();

for (int i = 0; i < fields.length; i++) {

try {

Class fieldClazz = fields[i].getType();

String fieldName = fields[i].getName(); // 获得属性名

String fieldVlue = BeanUtils.getProperty(p, fieldName); // 获得属性值

/*

* 判断属性是否要过滤,例如修改时间之类的字段LDAP是没有的 判断属性值是否为空,在这里过滤了所有null和""

* 增加操作中不存在主动设置某个值为空的情况 所以只需要处理有值属性

*/

if (checkfieldName(fieldName) || StringUtil.isEmpty(fieldVlue))

continue;

/*

* 多值属性的处理 如果多值属性为空,那么增加的时候就不会增加值进去

*/

if (fieldClazz.isAssignableFrom(List.class)) { // 集合属性

BasicAttribute ocattr1 = new BasicAttribute(fieldName);

PropertyDescriptor pd = new PropertyDescriptor(fieldName, c);

Method getMethod = pd.getReadMethod();// 获得get方法

List list = (List) getMethod.invoke(p);// 执行get方法返回一个Object

for (Object object : list) {

ocattr1.add(object);

}

attrs.put(ocattr1);

} else {

attrs.put(fieldName, fieldVlue);

}

} catch (Exception e) {

e.printStackTrace();

}

}

return attrs;

}

/**

*

* 组织修改数据

*

*/

@SuppressWarnings("unchecked")

private ModificationItem[] buildModifyAttributes(Person p) {

ArrayList attrs = new ArrayList();

Class c = p.getClass();

Field[] fields = c.getDeclaredFields();

for (Field field : fields) {

try {

Class fieldClazz = field.getType();

String fieldName = field.getName(); // 获得属性名

String fieldValue = BeanUtils.getProperty(p, fieldName);

/*

* 判断属性是否要过滤,例如修改时间之类的字段LDAP是没有的 判断属性值是否为空,在这里过滤了所有null和""

* 要置空的属性通过识别特殊属性值:delAtr 在后面做重新置空操作

*/

if (checkfieldName(fieldName) || StringUtil.isEmpty(fieldValue))

continue;

BasicAttribute basicAttr = new BasicAttribute(fieldName);

/*

* 多值属性的处理 如果传递一个空的list,那么修改的时候就会清空多值属性 (new ArrayList())

*/

if (fieldClazz.isAssignableFrom(List.class)) { // 如果是集合属性

PropertyDescriptor pd = new PropertyDescriptor(fieldName, c);

Method getMethod = pd.getReadMethod();// 获得get方法

List list = (List) getMethod.invoke(p);// 执行get方法返回一个Object

for (Object object : list) {

basicAttr.add(object);

}

} else {

/*

* 判断删除标记来对值进行置空 传递过来的对象中有些属性没有做修改就传递了"" 有些是要修改为 ""

* 所以在上面要过滤所有 "" 属性,避免将不修改的参数全都置空了 然后通过识别要修改参数的特有值来判断是否主动置空

* 如果add一个""进去,那么在LDAP中依然会显示

* 如果不给值,由BasicAttribute自动授予空值,那么在LDAP中就不显示了

*/

if ("delAtr".equals(fieldValue)) {

basicAttr.add(""); // 置空属性

} else {

basicAttr.add(fieldValue);// 有值属性

}

}

// 替换条目

attrs.add(new ModificationItem(

DirContextAdapter.REPLACE_ATTRIBUTE, basicAttr));

} catch (Exception e) {

e.printStackTrace();

}

}

return attrs.toArray(new ModificationItem[attrs.size()]);

}

/**

*

* 过滤默认值字段

*

*/

private static boolean checkfieldName(String fieldName) {

String[] check = new String[] { "id", "status", "createtime",

"updatetime", "dn" };

for (int i = 0; i < check.length; i++) {

if (check[i].equalsIgnoreCase(fieldName))

return true;

}

return false;

}

}

spring版:

1 package com.smnpc.util;

2

3 import java.util.Hashtable;

4 import java.util.Vector;

5

6 import javax.naming.Context;

7 import javax.naming.NamingEnumeration;

8 import javax.naming.NamingException;

9 import javax.naming.directory.Attribute;

10 import javax.naming.directory.Attributes;

11 import javax.naming.directory.BasicAttribute;

12 import javax.naming.directory.BasicAttributes;

13 import javax.naming.directory.DirContext;

14 import javax.naming.directory.InitialDirContext;

15 import javax.naming.directory.ModificationItem;

16 import javax.naming.directory.SearchControls;

17 import javax.naming.directory.SearchResult;

18 import javax.naming.ldap.LdapContext;

19

20 /**

21 * Java通过Ldap操作AD的增删该查询

22 *

23 * @author guob

24 */

25

26 public class LdapbyUser {

27 DirContext dc = null;

28 String root = "dc=example,dc=com"; // LDAP的根节点的DC

29

30 /**

31 *

32 * @param dn类似于"CN=RyanHanson,dc=example,dc=com"

33 * @param employeeID是Ad的一个员工号属性

34 */

35 public LdapbyUser(String dn, String employeeID) {

36 init();

37 // add();//添加节点

38 // delete("ou=hi,dc=example,dc=com");//删除"ou=hi,dc=example,dc=com"节点

39 // renameEntry("ou=new,o=neworganization,dc=example,dc=com","ou=neworganizationalUnit,o=neworganization,dc=example,dc=com");//重命名节点"ou=new,o=neworganization,dc=example,dc=com"

40 // searchInformation("dc=example,dc=com", "",

41 // "sAMAccountName=guob");//遍历所有根节点

42 modifyInformation(dn, employeeID);// 修改

43 // Ldapbyuserinfo("guob");//遍历指定节点的分节点

44 close();

45 }

46

47 /**

48 *

49 * Ldap连接

50 *

51 * @return LdapContext

52 */

53 public void init() {

54 Hashtable env = new Hashtable();

55 String LDAP_URL = "ldap://xxxx:389"; // LDAP访问地址

56 String adminName = "example\\user"; // 注意用户名的写法:domain\User或

57 String adminPassword = "userpassword"; // 密码

58 env.put(Context.INITIAL_CONTEXT_FACTORY,

59 "com.sun.jndi.ldap.LdapCtxFactory");

60 env.put(Context.PROVIDER_URL, LDAP_URL);

61 env.put(Context.SECURITY_AUTHENTICATION, "simple");

62 env.put(Context.SECURITY_PRINCIPAL, adminName);

63 env.put(Context.SECURITY_CREDENTIALS, adminPassword);

64 try {

65 dc = new InitialDirContext(env);// 初始化上下文

66 System.out.println("认证成功");// 这里可以改成异常抛出。

67 } catch (javax.naming.AuthenticationException e) {

68 System.out.println("认证失败");

69 } catch (Exception e) {

70 System.out.println("认证出错:" + e);

71 }

72 }

73

74 /**

75 * 添加

76 */

77 public void add(String newUserName) {

78 try {

79 BasicAttributes attrs = new BasicAttributes();

80 BasicAttribute objclassSet = new BasicAttribute("objectClass");

81 objclassSet.add("sAMAccountName");

82 objclassSet.add("employeeID");

83 attrs.put(objclassSet);

84 attrs.put("ou", newUserName);

85 dc.createSubcontext("ou=" + newUserName + "," + root, attrs);

86 } catch (Exception e) {

87 e.printStackTrace();

88 System.out.println("Exception in add():" + e);

89 }

90 }

91

92 /**

93 * 删除

94 *

95 * @param dn

96 */

97 public void delete(String dn) {

98 try {

99 dc.destroySubcontext(dn);

100 } catch (Exception e) {

101 e.printStackTrace();

102 System.out.println("Exception in delete():" + e);

103 }

104 }

105

106 /**

107 * 重命名节点

108 *

109 * @param oldDN

110 * @param newDN

111 * @return

112 */

113 public boolean renameEntry(String oldDN, String newDN) {

114 try {

115 dc.rename(oldDN, newDN);

116 return true;

117 } catch (NamingException ne) {

118 System.err.println("Error: " + ne.getMessage());

119 return false;

120 }

121 }

122

123 /**

124 * 修改

125 *

126 * @return

127 */

128 public boolean modifyInformation(String dn, String employeeID) {

129 try {

130 System.out.println("updating...\n");

131 ModificationItem[] mods = new ModificationItem[1];

132 /* 修改属性 */

133 // Attribute attr0 = new BasicAttribute("employeeID", "W0972");

134 // mods[0] = new ModificationItem(DirContext.REPLACE_ATTRIBUTE,

135 // attr0);

136 /* 删除属性 */

137 // Attribute attr0 = new BasicAttribute("description",

138 // "陈轶");

139 // mods[0] = new ModificationItem(DirContext.REMOVE_ATTRIBUTE,

140 // attr0);

141 /* 添加属性 */

142 Attribute attr0 = new BasicAttribute("employeeID", employeeID);

143 mods[0] = new ModificationItem(DirContext.ADD_ATTRIBUTE, attr0);

144 /* 修改属性 */

145 dc.modifyAttributes(dn + ",dc=example,dc=com", mods);

146 return true;

147 } catch (NamingException e) {

148 e.printStackTrace();

149 System.err.println("Error: " + e.getMessage());

150 return false;

151 }

152 }

153

154 /**

155 * 关闭Ldap连接

156 */

157 public void close() {

158 if (dc != null) {

159 try {

160 dc.close();

161 } catch (NamingException e) {

162 System.out.println("NamingException in close():" + e);

163 }

164 }

165 }

166

167 /**

168 * @param base

169 * :根节点(在这里是"dc=example,dc=com")

170 * @param scope

171 * :搜索范围,分为"base"(本节点),"one"(单层),""(遍历)

172 * @param filter

173 * :指定子节点(格式为"(objectclass=*)",*是指全部,你也可以指定某一特定类型的树节点)

174 */

175 public void searchInformation(String base, String scope, String filter) {

176 SearchControls sc = new SearchControls();

177 if (scope.equals("base")) {

178 sc.setSearchScope(SearchControls.OBJECT_SCOPE);

179 } else if (scope.equals("one")) {

180 sc.setSearchScope(SearchControls.ONELEVEL_SCOPE);

181 } else {

182 sc.setSearchScope(SearchControls.SUBTREE_SCOPE);

183 }

184 NamingEnumeration ne = null;

185 try {

186 ne = dc.search(base, filter, sc);

187 // Use the NamingEnumeration object to cycle through

188 // the result set.

189 while (ne.hasMore()) {

190 System.out.println();

191 SearchResult sr = (SearchResult) ne.next();

192 String name = sr.getName();

193 if (base != null && !base.equals("")) {

194 System.out.println("entry: " + name + "," + base);

195 } else {

196 System.out.println("entry: " + name);

197 }

198

199 Attributes at = sr.getAttributes();

200 NamingEnumeration ane = at.getAll();

201 while (ane.hasMore()) {

202 Attribute attr = (Attribute) ane.next();

203 String attrType = attr.getID();

204 NamingEnumeration values = attr.getAll();

205 Vector vals = new Vector();

206 // Another NamingEnumeration object, this time

207 // to iterate through attribute values.

208 while (values.hasMore()) {

209 Object oneVal = values.nextElement();

210 if (oneVal instanceof String) {

211 System.out.println(attrType + ": "

212 + (String) oneVal);

213 } else {

214 System.out.println(attrType + ": "

215 + new String((byte[]) oneVal));

216 }

217 }

218 }

219 }

220 } catch (Exception nex) {

221 System.err.println("Error: " + nex.getMessage());

222 nex.printStackTrace();

223 }

224 }

225

226 /**

227 * 查询

228 *

229 * @throws NamingException

230 */

231 public void Ldapbyuserinfo(String userName) {

232 // Create the search controls

233 SearchControls searchCtls = new SearchControls();

234 // Specify the search scope

235 searchCtls.setSearchScope(SearchControls.SUBTREE_SCOPE);

236 // specify the LDAP search filter

237 String searchFilter = "sAMAccountName=" + userName;

238 // Specify the Base for the search 搜索域节点

239 String searchBase = "DC=example,DC=COM";

240 int totalResults = 0;

241 String returnedAtts[] = { "url", "whenChanged", "employeeID", "name",

242 "userPrincipalName", "physicalDeliveryOfficeName",

243 "departmentNumber", "telephoneNumber", "homePhone", "mobile",

244 "department", "sAMAccountName", "whenChanged", "mail" }; // 定制返回属性

245

246 searchCtls.setReturningAttributes(returnedAtts); // 设置返回属性集

247

248 // searchCtls.setReturningAttributes(null); // 不定制属性,将返回所有的属性集

249

250 try {

251 NamingEnumeration answer = dc.search(searchBase, searchFilter,

252 searchCtls);

253 if (answer == null || answer.equals(null)) {

254 System.out.println("answer is null");

255 } else {

256 System.out.println("answer not null");

257 }

258 while (answer.hasMoreElements()) {

259 SearchResult sr = (SearchResult) answer.next();

260 System.out

261 .println("************************************************");

262 System.out.println("getname=" + sr.getName());

263 Attributes Attrs = sr.getAttributes();

264 if (Attrs != null) {

265 try {

266

267 for (NamingEnumeration ne = Attrs.getAll(); ne

268 .hasMore();) {

269 Attribute Attr = (Attribute) ne.next();

270 System.out.println("AttributeID="

271 + Attr.getID().toString());

272 // 读取属性值

273 for (NamingEnumeration e = Attr.getAll(); e

274 .hasMore(); totalResults++) {

275 String user = e.next().toString(); // 接受循环遍历读取的userPrincipalName用户属性

276 System.out.println(user);

277 }

278 // System.out.println(" ---------------");

279 // // 读取属性值

280 // Enumeration values = Attr.getAll();

281 // if (values != null) { // 迭代

282 // while (values.hasMoreElements()) {

283 // System.out.println(" 2AttributeValues="

284 // + values.nextElement());

285 // }

286 // }

287 // System.out.println(" ---------------");

288 }

289 } catch (NamingException e) {

290 System.err.println("Throw Exception : " + e);

291 }

292 }

293 }

294 System.out.println("Number: " + totalResults);

295 } catch (Exception e) {

296 e.printStackTrace();

297 System.err.println("Throw Exception : " + e);

298 }

299 }

300

301 /**

302 * 主函数用于测试

303 *

304 * @param args

305 */

306 public static void main(String[] args) {

307 new LdapbyUser("CN=RyanHanson", "bbs.it-");

308 }

309 }

如果觉得《java 操作 ldap_JAVA操作LDAP总结》对你有帮助,请点赞、收藏,并留下你的观点哦!

本内容不代表本网观点和政治立场,如有侵犯你的权益请联系我们处理。
网友评论
网友评论仅供其表达个人看法,并不表明网站立场。