一、基本理解

1. 基本概念

参考地址:LDAP概念和原理介绍

LDAP表示Lightweight Directory Access Protocol,是一个基于TCP/IP协议之上的轻型目录访问协议。

目录是一个为查询、浏览和搜索而优化的数据库,它成树状结构组织数据,类似文件目录一样。

目录数据库和关系数据库不同,它有优异的读性能,但写性能差,并且没有事务处理、回滚等复杂功能,不适于存储修改频繁的数据。

2. LdapTemplate <-> JdbcTemplate
  • 可以把LDAP的产品(如微软AD域、开源项目OpenLDAP)对标数据库产品去理解;
  • 可以把LDAP对标JDBC去理解,java通过JDBC操作数据库,通过LDAP操作目录数据库;
  • 可以把Spring的LdapTemplate对标JdbcTemplate去理解,分别为对LDAP和JDBC的简单封装,提供基本增删改查操作的易用API;
  • 可以使用LDAP客户端工具访问目录数据库,对标navicat、sqlyog等数据库客户端工具。(LDAP客户端工具下载地址

二、代码实现

1. 引入依赖
<!-- LDAP集成 -->
<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-data-ldap</artifactId>
</dependency>
2. 在application.yml中配置ldap(s)连接信息
spring:
  # LDAP连接配置
  ldap:
    urls: ldaps://x.x.x.x:636/
    base: ou=xxx,dc=ad,dc=xxx,dc=com
    username: 用户
    password: 密码

注意:

  • ldap默认端口为389,ldaps默认端口为636
  • 重置密码操作必须使用ldaps协议,使用ldaps协议必须配置ssl证书
3. 生成和导入ssl证书

如果使用ldap协议,只使用用户认证、检索用户等操作,则无需该步骤。

参考地址:java开发https请求ssl不受信任问题

(1) 将以下代码保存为InstallCert.java文件

/*
 * Copyright 2006 Sun Microsystems, Inc.  All Rights Reserved.
 *
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions
 * are met:
 *
 *   - Redistributions of source code must retain the above copyright
 *     notice, this list of conditions and the following disclaimer.
 *
 *   - Redistributions in binary form must reproduce the above copyright
 *     notice, this list of conditions and the following disclaimer in the
 *     documentation and/or other materials provided with the distribution.
 *
 *   - Neither the name of Sun Microsystems nor the names of its
 *     contributors may be used to endorse or promote products derived
 *     from this software without specific prior written permission.
 *
 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS
 * IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO,
 * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
 * PURPOSE ARE DISCLAIMED.  IN NO EVENT SHALL THE COPYRIGHT OWNER OR
 * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
 * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
 * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
 * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
 * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
 * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
 * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
 */
/**
 * http://blogs.sun.com/andreas/resource/InstallCert.java
 * Use:
 * java InstallCert hostname
 * Example:
 *% java InstallCert ecc.fedora.redhat.com
 */
 
import javax.net.ssl.*;
import java.io.*;
import java.security.KeyStore;
import java.security.MessageDigest;
import java.security.cert.CertificateException;
import java.security.cert.X509Certificate;
 
/**
 * Class used to add the server's certificate to the KeyStore
 * with your trusted certificates.
 */
public class InstallCert {
 
    public static void main(String[] args) throws Exception {
        String host;
        int port;
        char[] passphrase;
        if ((args.length == 1) || (args.length == 2)) {
            String[] c = args[0].split(":");
            host = c[0];
            port = (c.length == 1) ? 443 : Integer.parseInt(c[1]);
            String p = (args.length == 1) ? "changeit" : args[1];
            passphrase = p.toCharArray();
        } else {
            System.out.println("Usage: java InstallCert <host>[:port] [passphrase]");
            return;
        }
 
        File file = new File("jssecacerts");
        if (file.isFile() == false) {
            char SEP = File.separatorChar;
            File dir = new File(System.getProperty("java.home") + SEP
                    + "lib" + SEP + "security");
            file = new File(dir, "jssecacerts");
            if (file.isFile() == false) {
                file = new File(dir, "cacerts");
            }
        }
        System.out.println("Loading KeyStore " + file + "...");
        InputStream in = new FileInputStream(file);
        KeyStore ks = KeyStore.getInstance(KeyStore.getDefaultType());
        ks.load(in, passphrase);
        in.close();
 
        SSLContext context = SSLContext.getInstance("TLS");
        TrustManagerFactory tmf =
                TrustManagerFactory.getInstance(TrustManagerFactory.getDefaultAlgorithm());
        tmf.init(ks);
        X509TrustManager defaultTrustManager = (X509TrustManager) tmf.getTrustManagers()[0];
        SavingTrustManager tm = new SavingTrustManager(defaultTrustManager);
        context.init(null, new TrustManager[]{tm}, null);
        SSLSocketFactory factory = context.getSocketFactory();
 
        System.out.println("Opening connection to " + host + ":" + port + "...");
        SSLSocket socket = (SSLSocket) factory.createSocket(host, port);
        socket.setSoTimeout(10000);
        try {
            System.out.println("Starting SSL handshake...");
            socket.startHandshake();
            socket.close();
            System.out.println();
            System.out.println("No errors, certificate is already trusted");
        } catch (SSLException e) {
            System.out.println();
            e.printStackTrace(System.out);
        }
 
        X509Certificate[] chain = tm.chain;
        if (chain == null) {
            System.out.println("Could not obtain server certificate chain");
            return;
        }
 
        BufferedReader reader =
                new BufferedReader(new InputStreamReader(System.in));
 
        System.out.println();
        System.out.println("Server sent " + chain.length + " certificate(s):");
        System.out.println();
        MessageDigest sha1 = MessageDigest.getInstance("SHA1");
        MessageDigest md5 = MessageDigest.getInstance("MD5");
        for (int i = 0; i < chain.length; i++) {
            X509Certificate cert = chain[i];
            System.out.println
                    (" " + (i + 1) + " Subject " + cert.getSubjectDN());
            System.out.println("   Issuer  " + cert.getIssuerDN());
            sha1.update(cert.getEncoded());
            System.out.println("   sha1    " + toHexString(sha1.digest()));
            md5.update(cert.getEncoded());
            System.out.println("   md5     " + toHexString(md5.digest()));
            System.out.println();
        }
 
        System.out.println("Enter certificate to add to trusted keystore or 'q' to quit: [1]");
        String line = reader.readLine().trim();
        int k;
        try {
            k = (line.length() == 0) ? 0 : Integer.parseInt(line) - 1;
        } catch (NumberFormatException e) {
            System.out.println("KeyStore not changed");
            return;
        }
 
        X509Certificate cert = chain[k];
        String alias = host + "-" + (k + 1);
        ks.setCertificateEntry(alias, cert);
 
        OutputStream out = new FileOutputStream("jssecacerts");
        ks.store(out, passphrase);
        out.close();
 
        System.out.println();
        System.out.println(cert);
        System.out.println();
        System.out.println
                ("Added certificate to keystore 'jssecacerts' using alias '"
                        + alias + "'");
    }
 
    private static final char[] HEXDIGITS = "0123456789abcdef".toCharArray();
 
    private static String toHexString(byte[] bytes) {
        StringBuilder sb = new StringBuilder(bytes.length * 3);
        for (int b : bytes) {
            b &= 0xff;
            sb.append(HEXDIGITS[b >> 4]);
            sb.append(HEXDIGITS[b & 15]);
            sb.append(' ');
        }
        return sb.toString();
    }
 
    private static class SavingTrustManager implements X509TrustManager {
 
        private final X509TrustManager tm;
        private X509Certificate[] chain;
 
        SavingTrustManager(X509TrustManager tm) {
            this.tm = tm;
        }
 
        public X509Certificate[] getAcceptedIssuers() {
            throw new UnsupportedOperationException();
        }
 
        public void checkClientTrusted(X509Certificate[] chain, String authType)
                throws CertificateException {
            throw new UnsupportedOperationException();
        }
 
        public void checkServerTrusted(X509Certificate[] chain, String authType)
                throws CertificateException {
            this.chain = chain;
            tm.checkServerTrusted(chain, authType);
        }
    }
 
}

(2) 将InstallCert.java拷贝到目标服务器
(3) 在目标服务器运行

javac InstallCert.java
java InstallCert x.x.x.x:636
  • x.x.x.x是AD域服务器IP地址
  • 第2条命令会报javax.net.ssl.SSLHandshakeException错误,不用管
  • 第2条命令执行中需要输入1回车或者直接回车(Enter certificate to add to trusted keystore or ‘q’ to quit: [1])
  • 执行完毕会在当前目录下生成jssecacerts文件

(4) 将jssecacerts文件拷贝到JDK8\jre\lib\security\文件夹下

[root@root ~]# which java
/usr/bin/java
[root@root ~]# ls -lrt /usr/bin/java
lrwxrwxrwx 1 root root 22 8月   2 2017 /usr/bin/java -> /etc/alternatives/java
[root@root ~]# ls -lrt /etc/alternatives/java
lrwxrwxrwx 1 root root 35 8月   2 2017 /etc/alternatives/java -> /usr/java/jdk1.8.0_144/jre/bin/java
[root@root ~]# mv jssecacerts /usr/java/jdk1.8.0_144/jre/lib/security/
4. 创建domain类Person.java
import com.fasterxml.jackson.annotation.JsonIgnore;
import org.springframework.ldap.odm.annotations.Attribute;
import org.springframework.ldap.odm.annotations.Entry;
import org.springframework.ldap.odm.annotations.Id;

import javax.naming.Name;

@Entry(objectClasses = {"person"})
public class Person {
    @Id
    @JsonIgnore // 必写
    private Name distinguishedName;

    /* 登录账号 */
    @Attribute(name = "sAMAccountName")
    private String loginName;

    /* 用户姓名 */
    @Attribute(name = "cn")
    private String userName;

    /* 邮箱 */
    @Attribute(name = "mail")
    private String email;
    
    // gettet...setter...toString...
}
5. ILdapService.java
import java.util.List;

public interface ILdapService {

    /**
     * LDAP用户认证
     */
    boolean authenticate(String loginName, String password);

    /**
     * 检索域用户
     */
    List<Person> searchLdapUser(String keyword);

    /**
     * 修改密码
     */
    void resetPwd(String loginName, String newPassword) throws Exception;

}
6. LdapServiceImpl.java
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.ldap.core.LdapTemplate;
import org.springframework.ldap.filter.EqualsFilter;
import org.springframework.ldap.query.LdapQuery;
import org.springframework.stereotype.Component;

import javax.naming.directory.BasicAttribute;
import javax.naming.directory.DirContext;
import javax.naming.directory.ModificationItem;
import java.io.UnsupportedEncodingException;
import java.util.List;

import static org.springframework.ldap.query.LdapQueryBuilder.query;

@Component
public class LdapServiceImpl implements ILdapService {

    @Autowired
    private LdapTemplate ldapTemplate;

    /**
     * LDAP用户认证
     */
    @Override
    public boolean authenticate(String loginName, String password) {
        EqualsFilter filter = new EqualsFilter("sAMAccountName", loginName);
        return ldapTemplate.authenticate("", filter.toString(), password);
    }

    /**
     * 检索域用户
     */
    @Override
    public List<Person> searchLdapUser(String keyword) {
        keyword = "*" + keyword + "*";
        LdapQuery query = query().where("sAMAccountName").like(keyword).or("cn").like(keyword).or("mail").like(keyword);
        return ldapTemplate.find(query, Person.class);
    }

    /**
     * 修改密码
     */
    @Override
    public void resetPwd(String loginName, String newPassword) throws Exception {
        // 1. 查找AD用户
        LdapQuery query = query().where("sAMAccountName").is(loginName);
        Person person = ldapTemplate.findOne(query, Person.class);

        // 2. 创建密码
        String newQuotedPassword = "\"" + newPassword + "\"";
        byte[] newUnicodePassword = newQuotedPassword.getBytes("UTF-16LE");

        // 3. 修改密码
        ModificationItem item = new ModificationItem(DirContext.REPLACE_ATTRIBUTE, new BasicAttribute("unicodePwd", newUnicodePassword));
        ldapTemplate.modifyAttributes(person.getDistinguishedName(), new ModificationItem[]{item});
    }

}

诠释:

  • 检索类似jdbc,主要包括三步:
    (1)创造LdapQuery条件(链式),有is、like等,like用*表示通配
    (2)执行检索(LdapTemplate提供的方法)
    (3)封装返回结果,主要是两种方法,一使用Mapper映射,二使用@Attribute注解
  • 重置密码操作必须使用ldaps协议,使用ldaps协议必须配置ssl证书
  • 重置密码并没有类似changePwd的方法,是使用modifyAttributes修改属性的方式,密码需要用特定编码转一下

三、常见错误排除

  1. org.springframework.ldap.CommunicationException

    org.springframework.ldap.CommunicationException: simple bind failed: x.x.x.x:636;
    Root exception is javax.net.ssl.SSLHandshakeException: sun.security.validator.ValidatorException: PKIX path building failed: sun.security.provider.certpath.SunCertPathBuilderException: unable to find valid certification path to requested target

    分析处理:使用ldaps协议,必须配置ssl证书,配置方法见本文第二部分第3步。

  2. org.springframework.ldap.OperationNotSupportedException

    org.springframework.ldap.OperationNotSupportedException: [LDAP: error code 53 - 0000052D: SvcErr: DSID-031A12D2, problem 5003 (WILL_NOT_PERFORM), data 0

    问题原因:其它情况也可能碰到这个异常,我实际遇到的是由于设置的密码太过简单,不符合AD配置的密码强度要求所致。

    参考:It usually means that the password quality is too low (see AD password policy), or that you are trying to change the password on a non secure connection.

    解决办法:正常捕获异常,前端提醒密码太过简单即可。

  3. org.springframework.ldap.PartialResultException

    org.springframework.ldap.PartialResultException: Unprocessed Continuation Reference(s); nested exception is javax.naming.PartialResultException: Unprocessed Continuation Reference(s); remaining name ‘/’

    问题复现:在yml中配置ldap:base时,没有设置ou,只有dc时出现该问题。

    base: dc=ad,dc=xxx,dc=com
    

    解决办法:ldapTemplate.setIgnorePartialResultException(true);

    参考地址:https://stackoverflow.com/questions/37486159/springs-ldaptemplate-search-partialresultexception-unprocessed-continuation-r


References

[1] Spring LDAP Reference官方文档
[2] 简书-Spring Boot LDAP/AD认证
[3] JAVA使用Ldap操作AD域的方法示例

Logo

为开发者提供学习成长、分享交流、生态实践、资源工具等服务,帮助开发者快速成长。

更多推荐