jldap实现Java对LDAP的基本操作

目录:

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

[一]、概述

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

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

1<dependency>
2    <groupId>com.novell.ldap</groupId>
3    <artifactId>jldap</artifactId>
4    <version>4.3</version>
5    <type>jar</type>
6    <scope>compile</scope>
7</dependency>

[二]、基本操作

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

1.查询

java代码:LDAPSearchDemo.java

1package com.micmiu.ldap;
2 
3import java.io.UnsupportedEncodingException;
4import java.util.Enumeration;
5import java.util.Iterator;
6 
7import com.novell.ldap.LDAPAttribute;
8import com.novell.ldap.LDAPAttributeSet;
9import com.novell.ldap.LDAPConnection;
10import com.novell.ldap.LDAPEntry;
11import com.novell.ldap.LDAPException;
12import com.novell.ldap.LDAPSearchResults;
13import com.novell.ldap.util.Base64;
14 
15/**
16 * 查询条目示例 blog http://www.micmiu.com
17 *
18 * @author Michael
19 *
20 */
21public 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<LDAPAttribute> allAttributes = attributeSet.iterator();
64                while (allAttributes.hasNext()) {
65                    LDAPAttribute attribute = allAttributes.next();
66                    String attributeName = attribute.getName();
67 
68                    Enumeration<String> 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 = sjsky007@gmail.com
|---- ---- 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 = sjsky007@gmail.com
|---- ---- 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 = sjsky007@gmail.com
|---- ---- 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

1package com.micmiu.ldap;
2 
3import java.io.UnsupportedEncodingException;
4 
5import com.novell.ldap.LDAPAttribute;
6import com.novell.ldap.LDAPAttributeSet;
7import com.novell.ldap.LDAPConnection;
8import com.novell.ldap.LDAPEntry;
9import com.novell.ldap.LDAPException;
10 
11/**
12 * 添加新条目的示例
14 *
15 * @author Michael
16 *
17 */
18public 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", "sjsky007@gmail.com"));
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.

客户端刷新后的截图:

3.删除

java代码:LDAPDeleteEntry.java

1package com.micmiu.ldap;
2 
3import java.io.UnsupportedEncodingException;
4 
5import com.novell.ldap.LDAPConnection;
6import com.novell.ldap.LDAPException;
7 
8/**
9 * 删除条目的示例
11 *
12 * @author Michael
13 *
14 */
15public 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

1package com.micmiu.ldap;
2 
3import java.io.UnsupportedEncodingException;
4import java.util.ArrayList;
5import java.util.Date;
6import java.util.List;
7 
8import com.novell.ldap.LDAPAttribute;
9import com.novell.ldap.LDAPConnection;
10import com.novell.ldap.LDAPException;
11import com.novell.ldap.LDAPModification;
12 
13/**
14 * 修改操作示例
16 *
17 * @author Michael
18 *
19 */
20public 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<LDAPModification> modList = new ArrayList<LDAPModification>();
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}

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

5.验证密码

java代码:LDAPVerifyPassword.java

1package com.micmiu.ldap;
2 
3import java.io.UnsupportedEncodingException;
4 
5import com.novell.ldap.LDAPAttribute;
6import com.novell.ldap.LDAPConnection;
7import com.novell.ldap.LDAPException;
8 
9/**
10 * 验证密码的示例
12 *
13 * @author Michael
14 *
15 */
16public 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.^_^

验证密码成功。

—-

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值