jldap实现Java对LDAP的基本操作

目录:

  1. 概述
  2. 基本操作
    • 查询
    • 添加
    • 删除
    • 修改属性
    • 验证密码

[一]、概述

jldap 官网:http://www.openldap.org/jldap/

可以从官网下载源编译生成jar包,如果项目是用maven构建的,在pom.xml中增加如下内容即可:

1 <dependency>
2     <groupId>com.novell.ldapgroupId>
3     <artifactId>jldapartifactId>
4     <version>4.3version>
5     <type>jartype>
6     <scope>compilescope>
7 dependency>

[二]、基本操作

为了演示基本的操作,需要搭建个LDAP服务,有关openLDAP在windows上的安装配置可参见:http://www.micmiu.com/enterprise-app/sso/openldap-windows-config/ ,我配置好演示用的LDAP基本信息可见客户端截图:

jldap实现Java对LDAP的基本操作_第1张图片

1.查询

java代码:LDAPSearchDemo.java

1 package com.micmiu.ldap;
2  
3 import java.io.UnsupportedEncodingException;
4 import java.util.Enumeration;
5 import java.util.Iterator;
6  
7 import com.novell.ldap.LDAPAttribute;
8 import com.novell.ldap.LDAPAttributeSet;
9 import com.novell.ldap.LDAPConnection;
10 import com.novell.ldap.LDAPEntry;
11 import com.novell.ldap.LDAPException;
12 import com.novell.ldap.LDAPSearchResults;
13 import com.novell.ldap.util.Base64;
14  
15 /**
16  * 查询条目示例 blog http://www.micmiu.com
17  *
18  * @author Michael
19  *
20  */
21 public class LDAPSearchDemo {
22  
23     /**
24      *
25      * @param args
26      */
27     public static void main(String[] args) {
28  
29         String ldapHost = "localhost";
30         String loginDN = "cn=Manager,dc=micmiu,dc=com";
31         String password = "secret";
32         String searchBase = "dc=micmiu,dc=com";
33         String searchFilter = "objectClass=*";
34  
35         int ldapPort = LDAPConnection.DEFAULT_PORT;
36         // 查询范围
37         // SCOPE_BASE、SCOPE_ONE、SCOPE_SUB、SCOPE_SUBORDINATESUBTREE
38         int searchScope = LDAPConnection.SCOPE_SUB;
39  
40         LDAPConnection lc = new LDAPConnection();
41         try {
42             lc.connect(ldapHost, ldapPort);
43             lc.bind(LDAPConnection.LDAP_V3, loginDN, password.getBytes("UTF8"));
44             LDAPSearchResults searchResults = lc.search(searchBase,
45                     searchScope, searchFilter, null, false);
46  
47             while (searchResults.hasMore()) {
48                 LDAPEntry nextEntry = null;
49                 try {
50                     nextEntry = searchResults.next();
51                 } catch (LDAPException e) {
52                     System.out.println("Error: " + e.toString());
53                     if (e.getResultCode() == LDAPException.LDAP_TIMEOUT
54                             || e.getResultCode() == LDAPException.CONNECT_ERROR) {
55                         break;
56                     } else {
57                         continue;
58                     }
59                 }
60                 System.out.println("DN =: " + nextEntry.getDN());
61                 System.out.println("|---- Attributes list: ");
62                 LDAPAttributeSet attributeSet = nextEntry.getAttributeSet();
63                 Iterator allAttributes = attributeSet.iterator();
64                 while (allAttributes.hasNext()) {
65                     LDAPAttribute attribute = allAttributes.next();
66                     String attributeName = attribute.getName();
67  
68                     Enumeration allValues = attribute.getStringValues();
69                     if (null == allValues) {
70                         continue;
71                     }
72                     while (allValues.hasMoreElements()) {
73                         String value = allValues.nextElement();
74                         if (!Base64.isLDIFSafe(value)) {
75                             // base64 encode and then print out
76                             value = Base64.encode(value.getBytes());
77                         }
78                         System.out.println("|---- ---- " + attributeName
79                                 + " = " + value);
80                     }
81                 }
82             }
83  
84         } catch (LDAPException e) {
85             System.out.println("Error: " + e.toString());
86         } catch (UnsupportedEncodingException e) {
87             System.out.println("Error: " + e.toString());
88         } finally {
89             try {
90                 if (lc.isConnected()) {
91                     lc.disconnect();
92                 }
93             } catch (Exception e) {
94                 e.printStackTrace();
95             }
96         }
97     }
98 }

运行结果:

DN =: dc=micmiu,dc=com
|---- Attributes list:
|---- ---- dc = micmiu
|---- ---- o = Michael Blog
|---- ---- objectClass = domain
|---- ---- objectClass = top
DN =: ou=Developer,dc=micmiu,dc=com
|---- Attributes list:
|---- ---- description = Container for developer entries
|---- ---- ou = Developer
|---- ---- objectClass = organizationalUnit
DN =: ou=Tester,dc=micmiu,dc=com
|---- Attributes list:
|---- ---- description = Container for test entries
|---- ---- ou = Tester
|---- ---- objectClass = organizationalUnit
DN =: uid=Michael,ou=Developer,dc=micmiu,dc=com
|---- Attributes list:
|---- ---- userPassword = 111111
|---- ---- labeledURI = http://www.micmiu.com
|---- ---- uid = Michael
|---- ---- sn = Sun
|---- ---- cn = Michael Sun
|---- ---- mail = [email protected]
|---- ---- objectClass = inetOrgPerson
DN =: uid=Miumiu,ou=Tester,dc=micmiu,dc=com
|---- Attributes list:
|---- ---- userPassword = 111111
|---- ---- labeledURI = http://www.micmiu.com
|---- ---- uid = Miumiu
|---- ---- sn = Wu
|---- ---- cn = Miumiu Wu
|---- ---- objectClass = inetOrgPerson
DN =: dc=app1,dc=micmiu,dc=com
|---- Attributes list:
|---- ---- dc = app1
|---- ---- o = Michael Demo
|---- ---- objectClass = domain
DN =: dc=app2,dc=micmiu,dc=com
|---- Attributes list:
|---- ---- dc = app2
|---- ---- o = Michael Demo
|---- ---- objectClass = domain
DN =: ou=Demo,dc=app1,dc=micmiu,dc=com
|---- Attributes list:
|---- ---- description = Container for Demo entries
|---- ---- ou = Developer
|---- ---- ou = Demo
|---- ---- objectClass = organizationalUnit
DN =: ou=Demo,dc=app2,dc=micmiu,dc=com
|---- Attributes list:
|---- ---- description = Container for Demo entries
|---- ---- ou = Developer
|---- ---- ou = Demo
|---- ---- objectClass = organizationalUnit
DN =: uid=michael,ou=Demo,dc=app1,dc=micmiu,dc=com
|---- Attributes list:
|---- ---- userPassword = 111111
|---- ---- labeledURI = http://www.micmiu.com
|---- ---- uid = michael
|---- ---- sn = Sun
|---- ---- cn = Michael Sun
|---- ---- mail = [email protected]
|---- ---- objectClass = inetOrgPerson
DN =: uid=hazel,ou=Demo,dc=app1,dc=micmiu,dc=com
|---- Attributes list:
|---- ---- userPassword = 111111
|---- ---- labeledURI = http://www.micmiu.com
|---- ---- uid = hazel
|---- ---- sn = Wu
|---- ---- cn = Hazel Wu
|---- ---- objectClass = inetOrgPerson
DN =: uid=michael,ou=Demo,dc=app2,dc=micmiu,dc=com
|---- Attributes list:
|---- ---- userPassword = 111111
|---- ---- labeledURI = http://www.micmiu.com
|---- ---- uid = michael
|---- ---- sn = Sun
|---- ---- cn = Michael Sun
|---- ---- mail = [email protected]
|---- ---- objectClass = inetOrgPerson
DN =: uid=hazel,ou=Demo,dc=app2,dc=micmiu,dc=com
|---- Attributes list:
|---- ---- userPassword = 111111
|---- ---- labeledURI = http://www.micmiu.com
|---- ---- uid = hazel
|---- ---- sn = Wu
|---- ---- cn = Hazel Wu
|---- ---- objectClass = inetOrgPerson

查询结果和客户端查询出的信息一致。

2.添加

java代码:LDAPAddEntry.java

1 package com.micmiu.ldap;
2  
3 import java.io.UnsupportedEncodingException;
4  
5 import com.novell.ldap.LDAPAttribute;
6 import com.novell.ldap.LDAPAttributeSet;
7 import com.novell.ldap.LDAPConnection;
8 import com.novell.ldap.LDAPEntry;
9 import com.novell.ldap.LDAPException;
10  
11 /**
12  * 添加新条目的示例
13  * blog http://www.micmiu.com
14  *
15  * @author Michael
16  *
17  */
18 public class LDAPAddEntry {
19  
20     /**
21      *
22      * @param args
23      */
24     public static void main(String[] args) {
25  
26         String ldapHost = "localhost";
27         String loginDN = "cn=Manager,dc=micmiu,dc=com";
28         String password = "secret";
29         String containerName = "dc=micmiu,dc=com";
30  
31         int ldapPort = LDAPConnection.DEFAULT_PORT;
32         int ldapVersion = LDAPConnection.LDAP_V3;
33         LDAPConnection lc = new LDAPConnection();
34         LDAPAttributeSet attributeSet = new LDAPAttributeSet();
35  
36         attributeSet.add(new LDAPAttribute("objectclass", new String(
37                 "inetOrgPerson")));
38         attributeSet.add(new LDAPAttribute("cn", "Wukong Sun"));
39         attributeSet.add(new LDAPAttribute("sn", "Sun"));
40         attributeSet.add(new LDAPAttribute("mail", "[email protected]"));
41         attributeSet.add(new LDAPAttribute("labeledURI",
42                 "http://www.micmiu.com"));
43         attributeSet.add(new LDAPAttribute("userPassword", "111111"));
44         attributeSet.add(new LDAPAttribute("uid", "addnew"));
45         String dn = "uid=addnew,ou=Developer,"+containerName;
46         LDAPEntry newEntry = new LDAPEntry(dn, attributeSet);
47         try {
48             lc.connect(ldapHost, ldapPort);
49             lc.bind(ldapVersion, loginDN, password.getBytes("UTF8"));
50             System.out.println("login ldap server successfully.");
51             lc.add(newEntry);
52             System.out.println("Added object: " + dn + " successfully.");
53         } catch (LDAPException e) {
54             e.printStackTrace();
55         } catch (UnsupportedEncodingException e) {
56             System.out.println("Error: " + e.toString());
57         } finally {
58             try {
59                 if (lc.isConnected()) {
60                     lc.disconnect();
61                 }
62             } catch (Exception e) {
63                 e.printStackTrace();
64             }
65         }
66     }
67 }

运行结果:

login ldap server successfully.
Added object: uid=addnew,ou=Developer,dc=micmiu,dc=com successfully.

客户端刷新后的截图:

jldap实现Java对LDAP的基本操作_第2张图片

3.删除

java代码:LDAPDeleteEntry.java

1 package com.micmiu.ldap;
2  
3 import java.io.UnsupportedEncodingException;
4  
5 import com.novell.ldap.LDAPConnection;
6 import com.novell.ldap.LDAPException;
7  
8 /**
9  * 删除条目的示例
10  * blog http://www.micmiu.com
11  *
12  * @author Michael
13  *
14  */
15 public class LDAPDeleteEntry {
16  
17     /**
18      * @param args
19      */
20     public static void main(String[] args) {
21  
22         String ldapHost = "localhost";
23         String loginDN = "cn=Manager,dc=micmiu,dc=com";
24         String password = "secret";
25         String deleteDN = "uid=addnew,ou=Developer,dc=micmiu,dc=com";
26  
27         int ldapPort = LDAPConnection.DEFAULT_PORT;
28         int ldapVersion = LDAPConnection.LDAP_V3;
29         LDAPConnection lc = new LDAPConnection();
30         try {
31             lc.connect(ldapHost, ldapPort);
32             lc.bind(ldapVersion, loginDN, password.getBytes("UTF8"));
33  
34             lc.delete(deleteDN);
35             System.out.println(" delete Entry: " + deleteDN + " success.");
36             lc.disconnect();
37         } catch (LDAPException e) {
38             if (e.getResultCode() == LDAPException.NO_SUCH_OBJECT) {
39                 System.err.println("Error: No such object");
40             } else if (e.getResultCode() == LDAPException.INSUFFICIENT_ACCESS_RIGHTS) {
41                 System.err.println("Error: Insufficient rights");
42             } else {
43                 System.err.println("Error: " + e.toString());
44             }
45         } catch (UnsupportedEncodingException e) {
46             System.out.println("Error: " + e.toString());
47         } finally {
48             try {
49                 if (lc.isConnected()) {
50                     lc.disconnect();
51                 }
52             } catch (Exception e) {
53                 e.printStackTrace();
54             }
55         }
56  
57     }
58  
59 }

运行结果:

delete Entry: uid=addnew,ou=Developer,dc=micmiu,dc=com success.

在刷新客户端后发现刚新增加的条目:addnew 已经被删除了。

4.修改属性

java代码:LDAPAddEntry.java

1 package com.micmiu.ldap;
2  
3 import java.io.UnsupportedEncodingException;
4 import java.util.ArrayList;
5 import java.util.Date;
6 import java.util.List;
7  
8 import com.novell.ldap.LDAPAttribute;
9 import com.novell.ldap.LDAPConnection;
10 import com.novell.ldap.LDAPException;
11 import com.novell.ldap.LDAPModification;
12  
13 /**
14  * 修改操作示例
15  * blog http://www.micmiu.com
16  *
17  * @author Michael
18  *
19  */
20 public class LDAPModifyAttrs {
21  
22     /**
23      * @param args
24      */
25     public static void main(String[] args) {
26  
27         String ldapHost = "localhost";
28         String loginDN = "cn=Manager,dc=micmiu,dc=com";
29         String password = "secret";
30         String modifyDN = "uid=Michael,ou=Developer,dc=micmiu,dc=com";
31  
32         int ldapPort = LDAPConnection.DEFAULT_PORT;
33         int ldapVersion = LDAPConnection.LDAP_V3;
34         LDAPConnection lc = new LDAPConnection();
35  
36         List modList = new ArrayList();
37  
38         // Add a new value to the description attribute
39         String desc = "This object was modified at " + new Date();
40         LDAPAttribute attribute = new LDAPAttribute("description", desc);
41         modList.add(new LDAPModification(LDAPModification.ADD, attribute));
42  
43         attribute = new LDAPAttribute("telephoneNumber", "180-8888-xxxx");
44         modList.add(new LDAPModification(LDAPModification.ADD, attribute));
45  
46         // Replace the labeledURI address with a new value
47         attribute = new LDAPAttribute("labeledURI", "www.micmiu.com");
48         modList.add(new LDAPModification(LDAPModification.REPLACE, attribute));
49  
50         // delete the email attribute
51         attribute = new LDAPAttribute("mail");
52         modList.add(new LDAPModification(LDAPModification.DELETE, attribute));
53  
54         LDAPModification[] mods = new LDAPModification[modList.size()];
55         mods = (LDAPModification[]) modList.toArray(mods);
56  
57         try {
58             lc.connect(ldapHost, ldapPort);
59             lc.bind(ldapVersion, loginDN, password.getBytes("UTF8"));
60             lc.modify(modifyDN, mods);
61             System.out
62                     .println("LDAPAttribute add、replace、delete all successful.");
63         } catch (LDAPException e) {
64             e.printStackTrace();
65         } catch (UnsupportedEncodingException e) {
66             System.out.println("Error: " + e.toString());
67         } finally {
68             try {
69                 if (lc.isConnected()) {
70                     lc.disconnect();
71                 }
72             } catch (Exception e) {
73                 e.printStackTrace();
74             }
75         }
76  
77     }
78  
79 }

修改后客户端查询到的信息截图如下:

jldap实现Java对LDAP的基本操作_第3张图片

5.验证密码

java代码:LDAPVerifyPassword.java

1 package com.micmiu.ldap;
2  
3 import java.io.UnsupportedEncodingException;
4  
5 import com.novell.ldap.LDAPAttribute;
6 import com.novell.ldap.LDAPConnection;
7 import com.novell.ldap.LDAPException;
8  
9 /**
10  * 验证密码的示例
11  * blog http://www.micmiu.com
12  *
13  * @author Michael
14  *
15  */
16 public class LDAPVerifyPassword {
17  
18     /**
19      * @param args
20      */
21     public static void main(String[] args) {
22  
23         String ldapHost = "localhost";
24         String loginDN = "cn=Manager,dc=micmiu,dc=com";
25         String password = "secret";
26         String verifyDN = "uid=Michael,ou=Developer,dc=micmiu,dc=com";
27         String verifyPassword = "111111";
28  
29         int ldapPort = LDAPConnection.DEFAULT_PORT;
30  
31         int ldapVersion = LDAPConnection.LDAP_V3;
32         LDAPConnection lc = new LDAPConnection();
33  
34         try {
35             lc.connect(ldapHost, ldapPort);
36             lc.bind(ldapVersion, loginDN, password.getBytes("UTF8"));
37             LDAPAttribute attr = new LDAPAttribute("userPassword",
38                     verifyPassword);
39             boolean correct = lc.compare(verifyDN, attr);
40             System.out.println(correct ? "The password is correct.^_^"
41                     : "The password is incorrect.!!!");
42         } catch (LDAPException e) {
43             e.printStackTrace();
44             if (e.getResultCode() == LDAPException.NO_SUCH_OBJECT) {
45                 System.err.println("Error: No such entry");
46             } else if (e.getResultCode() == LDAPException.NO_SUCH_ATTRIBUTE) {
47                 System.err.println("Error: No such attribute");
48             } else {
49                 System.err.println("Error: " + e.toString());
50             }
51         } catch (UnsupportedEncodingException e) {
52             System.err.println("Error: " + e.toString());
53         } finally {
54             try {
55                 if (lc.isConnected()) {
56                     lc.disconnect();
57                 }
58             } catch (Exception e) {
59                 e.printStackTrace();
60             }
61         }
62     }
63 }

运行结果:

The password is correct.^_^

验证密码成功。

—-

原创文章,转载请注明: 转载自micmiu – 软件开发+生活点滴[ http://www.micmiu.com/ ]

本文链接地址: http://www.micmiu.com/opensource/java-ldap-demo/

你可能感兴趣的:(Ldap)