spring 集成 ldap

java 对LDAP进行数据操作,本文用到了LdapTemplate

1、pom文件添加

<!-- 添加Spring-ldap-->
		<dependency>
			<groupId>org.springframework.ldap</groupId>
			<artifactId>spring-ldap-core</artifactId>
			<version>2.3.1.RELEASE</version>
		</dependency>

2、新增spring-ldap.xml配置文件

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
       xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
       xmlns:ldap="http://www.springframework.org/schema/ldap"
       xsi:schemaLocation="http://www.springframework.org/schema/beans
    http://www.springframework.org/schema/beans/spring-beans-4.3.xsd
    http://www.springframework.org/schema/ldap
    http://www.springframework.org/schema/ldap/spring-ldap.xsd">

    <ldap:context-source id="contextSource"
                         password="${ldap.password}"
                         url="${ldap.url}"
                         username="${ldap.username}"
                         base="${ldap.base}" />
    <ldap:ldap-template id="ldapTemplate" context-source-ref="contextSource"/>

</beans>

3、新增ldap.properties

ldap.url= ldap://192.168.12.85:389
ldap.base= dc=domain,dc=com
ldap.username= cn=root,dc=domain,dc=com
ldap.password= 123456

4、封装对应的service类

package com.ais.esns.service;

import javax.naming.directory.Attributes;
import java.util.Map;

/**
 * Created with IntelliJ IDEA.
 * User: zhukai
 * Date: 2018/9/5
 * Time: 13:55
 * Description:
 */
public interface LdapService {
    /**
     * 查询数据
     * @param paramMap  eg:paramMap.put("filter","(&(objectclass=inetOrgPerson)(uid=zhukai))") // 过滤条件
     *                  paramMap.put("base","ou=南京") // 在南京组织下查询uid=zhukai的用户
     * @return
     */
    Attributes search(Map<String,Object> paramMap);

    /**
     * 更新数据
     * @param name  eg:uid=zhukai,cn=研发二部,ou=南京
     * @param paramMap 需要更新的数据
     * @return
     */
    boolean update(String name,Map<String,Object> paramMap);

    /**
     * 删除数据
     * @param distinguishedName eg:uid=zhukai,cn=研发二部,ou=南京
     * @return
     */
    boolean delete(String distinguishedName) ;

    /**
     * 创建组织,paramMap中存储组织的属性信息
     * @param paramMap ou – organization unit(组织单元/部门)必填,eg:paramMap.put("ou","南京")
     * @return
     */
    boolean addOrganizationalUnit(Map<String,Object> paramMap);

    /**
     * 创建用户组
     * @param paramMap cn(常用名称)和gidNumber(用户组的id),dn(可分辨的名称)为必填字段,
     *                 eg:paramMap.put("cn","研发三部");paramMap.put("gidNumber","10001");paramMap.put("dn","cn=研发三部,ou=南京")
     * @return
     */
    boolean addUserGroup(Map<String,Object> paramMap);

    /**
     * 创建用户
     * @param paramMap cn(常用名称)和gidNumber(用户组的id),uidNumber(类似用户id),homeDirectory,uid为必填字段
     *                 eg: paramMap.put("cn","zhukai")
     *                    paramMap.put("gidNumber","10001")
     *                    paramMap.put("uidNumber","10002")
     *                   paramMap.put("homeDirectory","/home/user")
     *                  paramMap.put("dn","uid=zhukai,cn=研发三部,ou=南京")
     *
     * @return
     */
    boolean addUser(Map<String,Object> paramMap);
}

5、service对应的实现类

package com.ais.esns.service.impl;

import com.ais.esns.service.LdapService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.ldap.core.AttributesMapper;
import org.springframework.ldap.core.LdapTemplate;
import org.springframework.stereotype.Service;

import javax.naming.InvalidNameException;
import javax.naming.NamingException;
import javax.naming.directory.*;
import javax.naming.ldap.LdapName;
import java.util.List;
import java.util.Map;

/**
 * Created with IntelliJ IDEA.
 * User: zhukai
 * Date: 2018/9/5
 * Time: 13:56
 * Description:
 */
@Service
public class LdapServiceImpl implements LdapService {

    @Autowired
    private LdapTemplate ldapTemplate;

    /**
     * 查询数据
     * @param paramMap  eg:paramMap.put("filter","(&(objectclass=inetOrgPerson)(uid=zhukai))") // 过滤条件
     *                  paramMap.put("base","ou=南京") // 在南京组织下查询uid=zhukai的用户
     * @return
     */
    @Override
    public Attributes search(Map<String, Object> paramMap) {
        /*String filter = "(&(objectclass=inetOrgPerson)(uid=" + paramMap.get("uid") + "))";*/
        String filter = String.valueOf(paramMap.get("filter"));

        List<Attributes> list = ldapTemplate.search(String.valueOf(paramMap.get("base")), filter, new AttributesMapper() {
            @Override
            public Object mapFromAttributes(Attributes attributes) throws NamingException {
                return attributes;
            }
        });
        if (list.isEmpty()){
            return null;
        }
        return list.get(0);
    }

    /**
     * 更新
     * @param name eg:uid=zhukai,cn=研发二部,ou=南京
     * @param paramMap 需要更新的字段
     * @return
     */
    @Override
    public boolean update(String name,Map<String, Object> paramMap) {
        try {
            LdapName dn = new LdapName(name);
            ModificationItem[] modificationItem = new ModificationItem[paramMap.size()];
            int i = 0;
            for (Map.Entry<String,Object> entry:paramMap.entrySet()) {
                modificationItem[i] = new ModificationItem(DirContext.REPLACE_ATTRIBUTE,new BasicAttribute (entry.getKey(),entry.getValue()));
                i++;
            }
            ldapTemplate.modifyAttributes(dn,modificationItem);
         /*   ldapTemplate.modifyAttributes(dn, new ModificationItem[] {
                    new ModificationItem(DirContext.REPLACE_ATTRIBUTE, new BasicAttribute("cn", paramMap.get("cn"))),
                    new ModificationItem(DirContext.REPLACE_ATTRIBUTE, new BasicAttribute("sn", paramMap.get("sn"))),
                    *//*new ModificationItem(DirContext.REPLACE_ATTRIBUTE, new BasicAttribute("mail", paramMap.get("mail"))),*//*
            });*/
            return true;
        } catch (InvalidNameException e) {
            e.printStackTrace();
            return false;
        }
    }

    @Override
    public boolean delete(String distinguishedName) {
        try {
            ldapTemplate.unbind(distinguishedName);
            return  true;
        } catch (Exception e) {
            e.printStackTrace();
            return  false;
        }
    }

    /**
     * 创建组织,paramMap中存储组织的属性信息
     * @param paramMap ou – organization unit(组织单元/部门)eg:paramMap.put("ou","通信研发")
     * @return
     */
    @Override
    public boolean addOrganizationalUnit(Map<String, Object> paramMap) {
        try {
            Attributes attr = new BasicAttributes();
            BasicAttribute ocattr = new BasicAttribute("objectclass");
            ocattr.add("organizationalUnit");
            ocattr.add("top");
            attr.put(ocattr);
           /*ldapTemplate.bind("ou=通信研发", null, attr);*/
            ldapTemplate.bind("ou="+String.valueOf(paramMap.get("ou")), null, attr);
            return   true;
        } catch (Exception e) {
            e.printStackTrace();
            return false;
        }
    }

    /**
     * 创建用户组
     * @param paramMap cn(常用名称)和gidNumber(用户组的id),dn(可分辨的名称)为必填字段,
     *                 eg:paramMap.put("cn","研发三部");paramMap.put("gidNumber","10001");paramMap.put("dn","cn=研发三部,ou=通信研发")
     * @return
     */
    @Override
    public boolean addUserGroup(Map<String, Object> paramMap) {
        try {
            Attributes attr = new BasicAttributes();
            BasicAttribute ocattr = new BasicAttribute("objectclass");
            ocattr.add("posixGroup");// 加此属性才是用户组
            ocattr.add("top");
            attr.put(ocattr);
            // 用户组的话,cn(常用名称)和gidNumber(用户组的id)为必填字段
            attr.put("cn",paramMap.get("cn"));
            attr.put("gidNumber",paramMap.get("gidNumber"));
          /*ldapTemplate.bind("cn=研发三部,ou=通信研发", null, attr);*/
            ldapTemplate.bind(String.valueOf(paramMap.get("dn")), null, attr);
            return true;
        } catch (Exception e) {
            e.printStackTrace();
            return false;
        }
    }

    /**
     * 创建用户
     * @param paramMap cn(常用名称)和gidNumber(用户组的id),uidNumber(类似用户id),homeDirectory,uid为必填字段
     *                 eg: paramMap.put("cn","zhukai")
     *                    paramMap.put("gidNumber","10001")
     *                    paramMap.put("uidNumber","10002")
     *                   paramMap.put("homeDirectory","/home/user")
     *                  paramMap.put("dn","uid=zhukai,cn=研发三部,ou=通信研发")
     *
     * @return
     */
    @Override
    public boolean addUser(Map<String, Object> paramMap) {
        try {
            Attributes attr = new BasicAttributes();
            BasicAttribute ocattr = new BasicAttribute("objectclass");
            ocattr.add("top");
            ocattr.add("organizationalPerson");
            ocattr.add("shadowAccount");
            ocattr.add("person");
            ocattr.add("inetOrgPerson");
            ocattr.add("posixAccount");// 加上此属性才是用户
            attr.put(ocattr);
            // common name
            attr.put("cn",paramMap.get("cn"));
            // suer name
            attr.put("sn",paramMap.get("sn"));
            attr.put("gidNumber",paramMap.get("gidNumber"));
            attr.put("uidNumber",paramMap.get("uidNumber"));
            attr.put("homeDirectory", paramMap.get("homeDirectory"));
            //ldapTemplate.bind("uid=zhukai,cn=研发三部,ou=通信研发", null, attr);
            ldapTemplate.bind(String.valueOf(paramMap.get("dn")), null, attr);
            return true;
        } catch (Exception e) {
            e.printStackTrace();
            return false;
        }
    }




    /**
     * 创建组织
     */
    public void createOrganizationalUnit(){
        Attributes attr = new BasicAttributes();
        BasicAttribute ocattr = new BasicAttribute("objectclass");
        ocattr.add("organizationalUnit");
        ocattr.add("top");
        attr.put(ocattr);
        ldapTemplate.bind("ou=南京", null, attr);
        ldapTemplate.bind("ou=通信研发, ou=南京", null, attr);

    }


    /**
     * 创建用户组
     */
    public void createUserGroup(){
        Attributes attr = new BasicAttributes();
        BasicAttribute ocattr = new BasicAttribute("objectclass");
        ocattr.add("posixGroup");// 加此属性才是用户组
        ocattr.add("top");
        attr.put(ocattr);
        attr.put("cn","研发三部");
        attr.put("gidNumber","10003");
        ldapTemplate.bind("cn=研发三部,ou=通信研发, ou=南京", null, attr);
        attr.put("cn","研发二部");
        attr.put("gidNumber","10002");
        ldapTemplate.bind("cn=研发二部,ou=通信研发, ou=南京", null, attr);
    }
    /**
     * 创建用户
     */
    public void createUser(){
        Attributes attr = new BasicAttributes();
        BasicAttribute ocattr = new BasicAttribute("objectclass");
        ocattr.add("top");
        ocattr.add("organizationalPerson");
        ocattr.add("shadowAccount");
        ocattr.add("person");
        ocattr.add("inetOrgPerson");
        ocattr.add("posixAccount");// 加上此属性才是用户
        attr.put(ocattr);
       /* attr.put("uid","zhukai");*/
        attr.put("userPassword","123456");
        attr.put("sn","zhukai");
        attr.put("cn","zhukai");
        attr.put("gidNumber","10003");
        attr.put("uidNumber","102");
        attr.put("homeDirectory", "/home/admin");
        ldapTemplate.bind("uid=zhukai,cn=研发三部,ou=通信研发, ou=南京", null, attr);

        attr = new BasicAttributes();
        ocattr = new BasicAttribute("objectclass");
        ocattr.add("top");
        ocattr.add("organizationalPerson");
        ocattr.add("shadowAccount");
        ocattr.add("person");
        ocattr.add("inetOrgPerson");
        ocattr.add("posixAccount");// 加上此属性才是用户
        attr.put(ocattr);
       /* attr.put("uid","zhukai");*/
        attr.put("userPassword","123456");
        attr.put("sn","zhangsan");
        attr.put("cn","张三");
        attr.put("gidNumber","10002");
        attr.put("uidNumber","620");
        attr.put("homeDirectory", "/home/admin");
        ldapTemplate.bind("uid=zhangsan,cn=研发二部,ou=通信研发, ou=南京", null, attr);

    }
}

6、示例

@RequestMapping(value = "/ldap",produces={MediaType.APPLICATION_JSON_UTF8_VALUE})
	@ResponseBody
	public WapiResponse ldap(HttpServletRequest request,HttpServletResponse response) throws NamingException{
		WapiResponse wapiResponse = new WapiResponse();

		Map<String,Object> paramMap = new HashMap<>();
		paramMap.put("ou","通信研发");
		ldapService.addOrganizationalUnit(paramMap);
		paramMap = new HashMap<>();
		paramMap.put("cn","研发三部");
		paramMap.put("gidNumber","10002");
		paramMap.put("dn","cn=研发三部,ou=通信研发");
		ldapService.addUserGroup(paramMap);

		paramMap = new HashMap<>();
		paramMap.put("cn","zhukai");
		paramMap.put("sn","zhukai");
		paramMap.put("gidNumber","10002");
		paramMap.put("uidNumber","77702");
		paramMap.put("homeDirectory","/xxxx");
		paramMap.put("dn","uid=zhukai,cn=研发三部,ou=通信研发");
		ldapService.addUser(paramMap);


		paramMap = new HashMap<>();
		paramMap.put("base","cn=研发三部,ou=通信研发");
		paramMap.put("filter","(&(objectclass=inetOrgPerson)(uid=zhukai))");
		Attributes users =  ldapService.search(paramMap);
		paramMap = new HashMap<>();
		paramMap.put("cn","zhukai123");
		paramMap.put("gidNumber","10002");
		paramMap.put("mail","zhukai@163.com");
		ldapService.update("uid=zhukai,cn=研发三部,ou=通信研发",paramMap);

		ldapService.delete("uid=zhukai,cn=研发三部,ou=通信研发");
		return wapiResponse;
	}

通过LDAP Admin查看效果如下  LDAP下载路径 https://download.csdn.net/download/u011196623/10646983

8e7a10b581c8e06d8baa1300bc55cd38ae7.jpg

 

©️2020 CSDN 皮肤主题: 大白 设计师: CSDN官方博客 返回首页
实付0元
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值