背景
近期有一个需求是希望Share自动化,也就是说用户申请流程审批通过后自动调用Share相关操作为用户添加权限,将用户移动到指定域组等操作。
通过调研后发现可以使用Ldap来完成!
Ldap概述
LDAP是一种协议,Lightweight Directory Access Protocol,轻量级目录访问协议,用于提供目录信息查询服务,基于TCP/IP协议。
目录服务:是一种特殊的数据库系统,其专门针对读取,浏览和搜索操作进行特定的优化。目录一般用来包含描述性的,基于属性的信息并支持精细复杂的过滤能力。
LDAP目录中的信息是是按照树型结构组织,具体信息存储在条目(entry)的数据结构中。条目相当于关系数据库中表的记录;条目是具有区别名DN (Distinguished Name)的属性(Attribute),DN是用来引用条目的,DN相当于关系数据库表中的关键字(Primary Key)。
简称:
组织-公司 O:organization
组织单元-部门 OU:organization unit
国家 C:countryName
域名 DC:domainComponent
真实名称 SN:suer name
常用名称 CN:common name
有需要深入详解Ldap的同学可以自行查询,这里就不在过多介绍!
Java操作Ldap实战
首先,想要操作Ldap首先我们要引入两个jar包,如果是Spring项目可以直接在pom.xml中引入
<!-- https://mvnrepository.com/artifact/org.springframework.ldap/spring-ldap-core -->
<dependency>
<groupId>org.springframework.ldap</groupId>
<artifactId>spring-ldap-core</artifactId>
<version>3.1.0</version>
</dependency>
还可以使用下面jar包进行操作
<!-- https://mvnrepository.com/artifact/com.unboundid/unboundid-ldapsdk -->
<dependency>
<groupId>com.unboundid</groupId>
<artifactId>unboundid-ldapsdk</artifactId>
<version>6.0.9</version>
</dependency>
下面代码都是以ldapsdk jar包为例
1. 链接到LDAP服务器
添加Ldap服务的相关配置,这里的用户一定要有修改权限,否则在add及modify的时候会报错
import javax.naming.Context;
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.DirContext;
import javax.naming.directory.InitialDirContext;
import javax.naming.directory.ModificationItem;
import javax.naming.directory.SearchControls;
import javax.naming.directory.SearchResult;
import java.util.ArrayList;
import java.util.List;
import java.util.Properties;
public class JndiLdapOperation {
private static final String LDAP_URL = "ldap://localhost:389";
private static final String USERNAME = "admin";
private static final String PASSWORD = "your_password";
private static final String DOMAIN_BASE_DN = "cn=test,dc=example,dc=com"
/**
*添加组到LDAP服务器的方法
*/
private static Properties getLdapEnvironment() {
Properties env = new Properties();
env.put(Context.INITIAL_CONTEXT_FACTORY, "com.sun.jndi.ldap.LdapCtxFactory");
env.put(Context.PROVIDER_URL, LDAP_URL ); // LDAP服务器地址
env.put(Context.SECURITY_AUTHENTICATION, "simple");
env.put(Context.SECURITY_PRINCIPAL, USERNAM
原文链接: https://onlyou.blog.csdn.net//article/details/137231833