惯性聚合 高效追踪和阅读你感兴趣的博客、新闻、科技资讯
阅读原文 在惯性聚合中打开

推荐订阅源

Blog — PlanetScale
Blog — PlanetScale
Y
Y Combinator Blog
G
Google Developers Blog
Cyber Security Advisories - MS-ISAC
Cyber Security Advisories - MS-ISAC
L
LangChain Blog
S
SegmentFault 最新的问题
J
Java Code Geeks
V
Visual Studio Blog
H
Help Net Security
Stack Overflow Blog
Stack Overflow Blog
aimingoo的专栏
aimingoo的专栏
OSCHINA 社区最新新闻
OSCHINA 社区最新新闻
T
Tailwind CSS Blog
Microsoft Azure Blog
Microsoft Azure Blog
博客园_首页
H
Hackread – Cybersecurity News, Data Breaches, AI and More
奇客Solidot–传递最新科技情报
奇客Solidot–传递最新科技情报
博客园 - Franky
B
Blog RSS Feed
The Cloudflare Blog
MyScale Blog
MyScale Blog
月光博客
月光博客
Microsoft Security Blog
Microsoft Security Blog
美团技术团队

Liu Zijian's Blog | 一个技术博客

使用Certbot自动续签HTTPS证书 使用Filebeat采集Nginx日志到ES Python的协程 Python中的异常 Python中的类和对象 Python的函数 Python的数据结构,推导式、迭代器和生成器 Spring AI集成多模态模型 LangChain4j多模态 LangChain Tools工具使用 Python中的模块和包 Python全局环境和虚拟环境(venv) LangChain Prompt提示词工程 LangChain4j Tools工具使用 基于Dify搭建AI智能体应用 LangChain4j RAG检索增强生成 Spring AI实现MCP Server Spring AI集成MCP Client LangChain4j Prompt提示词工程 Spring AI使用知识库增强对话功能 Spring AI实现一个智能客服 Spring AI实现一个简单的对话机器人 实现MinIO数据的每日备份 自己实现一个DNS服务 简单理解AI智能体 大模型和大模型应用 LangChain开篇 LangChain4j开篇 一个解析Excel2007的POI工具类 DataPermissionInterceptor源码解读
Java实现LDAP登录
Liu Zijian · 2024-12-10 · via Liu Zijian's Blog | 一个技术博客

LDAP的全称是Lightweight Directory Access Protocol(轻量级目录访问协议),是一种用于访问和管理分布式目录信息服务的应用协议。LDAP通常用于存储用户、组和其他组织信息,提供对这些信息的快速查询和管理。

LDAP是基于X.500标准的一个简化版本,使用更简单的网络协议(如 TCP/IP)来实现,定义了客户端如何与目录服务交互,如添加、删除、修改或查询目录信息。

LDAP使用SSL加密(ldaps://)时,如果服务端是自签证书,需提前安装证书到jdk的信任证书库内,我采用的open-jdk8的证书库位于/etc/pki/ca-trust/extracted/java/cacerts,将自签发的证书certificate.pem导入

keytool -importcert -keystore $JAVA_HOME/jre/lib/security/cacerts -storepass changeit -trustcacerts -file certificate.pem -alias uua01

Java原生支持LDAP协议,通过管理员账户adminDnadminPassword连接LDAP服务器,并搜索用户的DN,验证用户凭据,再检查输入的密码是否正确


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 java.io.InputStream;
import java.util.Hashtable;
import java.util.Map;

import lombok.extern.slf4j.Slf4j;

@Slf4j
public class LdapVerify {

    public boolean connehct(String username, String password) {

        String ip = "";
        String port = "";
        String timeOut = "";
        String adminDn = "";
        String adminPassword = "";
        String url = String.format("ldaps://%s:%s", ip, port);


        // 1. 建立与 LDAP 的连接
        Hashtable<String, String> env = new Hashtable<>();
        env.put(Context.INITIAL_CONTEXT_FACTORY, "com.sun.jndi.ldap.LdapCtxFactory");
        env.put(Context.PROVIDER_URL, url);
        env.put(Context.SECURITY_AUTHENTICATION, "simple");
        env.put(Context.SECURITY_PRINCIPAL, adminDn);
        env.put(Context.SECURITY_CREDENTIALS, adminPassword);
        env.put(Context.SECURITY_PROTOCOL, "ssl"); // 启用 LDAPS
        env.put("com.sun.jndi.ldap.connect.timeout", "3000");

        try {
            LdapContext ldapContext = new InitialLdapContext(env, null);

            // 2. 查找用户的完整 DN
            String searchBase = "OU=All Users,DC=demo,DC=com"; // 搜索起点
            String searchFilter = "(sAMAccountName=" + username + ")"; // 根据用户名查找
            SearchControls searchControls = new SearchControls();
            searchControls.setSearchScope(SearchControls.SUBTREE_SCOPE);

            NamingEnumeration<SearchResult> results = ldapContext.search(searchBase, searchFilter, searchControls);
            if (results.hasMore()) {
                SearchResult result = results.next();
                String userDn = result.getNameInNamespace();
                log.info("LDAP登录, 找到用户 DN: " + userDn);

                // 3. 验证用户密码
                Hashtable<String, String> userEnv = new Hashtable<>();
                userEnv.put(Context.INITIAL_CONTEXT_FACTORY, "com.sun.jndi.ldap.LdapCtxFactory");
                userEnv.put(Context.PROVIDER_URL, url);
                userEnv.put(Context.SECURITY_AUTHENTICATION, "simple");
                userEnv.put(Context.SECURITY_PRINCIPAL, userDn);
                userEnv.put(Context.SECURITY_CREDENTIALS, password);
                userEnv.put(Context.SECURITY_PROTOCOL, "ssl");
                userEnv.put("com.sun.jndi.ldap.connect.timeout", "3000");

                try {
                    new InitialLdapContext(userEnv, null).close();
                    log.info("LDAP登录, 用户验证成功 {}", username);
                    return true;
                }
                catch (Exception e) {
                    log.error("LDAP登录, 用户验证失败", username);
                    return false;
                }

            }

            log.error("LDAP登录, 找不到用户 DN {} ", username);

            return false;

        }
        catch (NamingException e) {
            log.error("LDAP登录, 找用户异常 DN {} {} ", username, e.getMessage(), e);
            return false;
        }

    }

}