1. 程式人生 > >spring 整合 ldap

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","[email protected]");
		ldapService.update("uid=zhukai,cn=研發三部,ou=通訊研發",paramMap);

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

通過LDAP Admin檢視效果如下