Java通过Spring的LdapTemplate操作LDAP

Java通过Spring的LdapTemplate操作LDAP

1、添加maven依赖


  org.springframework.ldap
  spring-ldap-core
  2.3.2.RELEASE

除此之外的还需要Spring相关的依赖.

2、初始化LdapTemplate

方法一: 

package com.aitsys.openldap.util;
import com.atsys.server.common.util.PropertiesUtil;
import org.springframework.ldap.core.LdapTemplate;
import org.springframework.ldap.core.support.LdapContextSource;

/**
 * Created by gailun on 2018/8/1.
 */
public class LdapUtil {

    /**
     *  初始化LdapTemplate
     * @return
     */
    public static LdapTemplate getLdapTemplate(){
        LdapTemplate template = null;
        try {
            LdapContextSource contextSource = new LdapContextSource();

            String url = PropertiesUtil.getString("url");
            String base = PropertiesUtil.getString("base");
            String userDn = PropertiesUtil.getString("userDn");
            String password = PropertiesUtil.getString("password");

            contextSource.setUrl(url);
            contextSource.setBase(base);
            contextSource.setUserDn(userDn);
            contextSource.setPassword(password);
            contextSource.setPooled(false);
            contextSource.afterPropertiesSet(); // important
            template = new LdapTemplate(contextSource);
        }catch (Exception e){
            e.printStackTrace();
        }
        return template;
    }
}

方法二: (交给Spring管理, 在Spring的配置文件进行配置)


   



   
   
   
   
   

3.配置文件

url=ldap://192.168.6.214:38912
base=dc=luhe,dc=net
userDn=cn=Manager,dc=luhe,dc=net
password=KWELASFJ
file_catalog_student=ou=other,ou=Users
file_catalog_teacher=ou=teacher,ou=Users

4.LdapTemplate操作LDAP

package com.aitsys.openldap.controller;
import com.aitsys.openldap.util.LdapUtil;
import com.atsys.server.common.util.PropertiesUtil;
import com.atsys.server.common.util.ResultTO;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.ldap.core.DirContextAdapter;
import org.springframework.ldap.core.DirContextOperations;
import org.springframework.ldap.core.LdapTemplate;
import org.springframework.ldap.filter.AndFilter;
import org.springframework.ldap.filter.EqualsFilter;
import org.springframework.ldap.support.LdapNameBuilder;
import org.springframework.stereotype.Controller;
import org.springframework.ldap.core.DistinguishedName;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import javax.naming.directory.Attributes;
import javax.naming.directory.BasicAttribute;
import javax.naming.directory.BasicAttributes;
import javax.naming.directory.DirContext;
import javax.naming.directory.ModificationItem;
import javax.naming.ldap.LdapName;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

/**
 * Created by gailun on 2018/8/1.
 */
@Controller
@RequestMapping("/openldap")
public class OpenldapController {

    private static final Logger LOGGER = LoggerFactory.getLogger(OpenldapController.class);

    /**
     * 查询【】数据
     * @param
     * @return ResultTO
     * @author AutoCode
     * @date 2017-05-05 13:29:38
     */
    @RequestMapping(value = "select", method = RequestMethod.POST)
    @ResponseBody
    public ResultTO select(String userStudentId,String userType) {
        System.out.println("userStudentId  ===> "+userStudentId);
        System.out.println("userType  ===> "+userType);
        try {
            LdapTemplate template = LdapUtil.getLdapTemplate();

            AndFilter filter = new AndFilter();
            filter.and(new EqualsFilter("objectClass", "person"));
            filter.and(new EqualsFilter("cn",userStudentId));
            String fileCatalog = null;
            if ("3".equals(userType)){
                fileCatalog = PropertiesUtil.getString("file_catalog_teacher");
            }else if ("1".equals(userType)){
                fileCatalog = PropertiesUtil.getString("file_catalog_student");
            }
            List search = template.search(fileCatalog, filter.encode(), new PersonAttributesMapper());
            /*System.out.println(search.size());
            System.out.println(search.get(0));*/
            return ResultTO.newSuccessResultTO("查询成功", search);
        } catch (Exception e) {
            e.printStackTrace();
            return ResultTO.newFailResultTO("查询失败", null);
        }

    }


    /**
     * 编辑【】数据
     * @param   type: 1 新增 ; type:2 修改
     * @return ResultTO  userType:1 学生; userType:3 老师
     * @author AutoCode
     * @date 2017-05-05 13:29:38
     */
    @RequestMapping(value = "editOpenldap", method = RequestMethod.POST)
    @ResponseBody
    public ResultTO editCommentaryItem(@RequestParam String userPassword,
                                       Integer type,
                                       @RequestParam String userName,
                                       @RequestParam Integer userType) {
        try {
            LdapTemplate template = LdapUtil.getLdapTemplate();

            String fileCatalog = null;
            if (userType.compareTo(1)==0){
                fileCatalog = PropertiesUtil.getString("file_catalog_student");
            }else if (userType.compareTo(3)==0){
                fileCatalog = PropertiesUtil.getString("file_catalog_teacher");
            }
            AndFilter filter = new AndFilter();
            filter.and(new EqualsFilter("objectClass", "person"));
            filter.and(new EqualsFilter("cn",userName));
            List search = template.search(fileCatalog, filter.encode(), new PersonAttributesMapper());
            if (search.isEmpty()){
                LdapNameBuilder ldapNameBuilder = LdapNameBuilder.newInstance();
                if (!StringUtils.isBlank(fileCatalog)){
                    String[] split = fileCatalog.split(",");
                    for (int i = split.length - 1; i >= 0; i--) {
                        String s1 = split[i];
                        String cn = s1.substring(0, 2);
                        String fileName = s1.substring(3, s1.length());

                        ldapNameBuilder.add(cn,fileName);
                    }
                    ldapNameBuilder.add("cn", userName);
                }else{
                    return ResultTO.newFailResultTO("file_catalog的配置路径错误", null);
                }
                /*LdapName build = LdapNameBuilder.newInstance()
                        .add("cn", "admin")
                        .add("cn", userName)
                        .build();*/
                //创建用户
                LdapName build = ldapNameBuilder.build();

                // 基类设置
                BasicAttribute ocattr = new BasicAttribute("objectClass");
                ocattr.add("top");
                ocattr.add("person");
                // 用户属性
                Attributes attrs = new BasicAttributes();
                attrs.put(ocattr);
                attrs.put("cn", "Some Person");
                attrs.put("sn", "Person");
                attrs.put("userPassword", userPassword);
                attrs.put("description", "description");
                attrs.put("telephoneNumber", "123");

                template.bind(build,null,attrs);
            }else{
                ModificationItem[] modificationItems = {
                        new ModificationItem(DirContext.REPLACE_ATTRIBUTE, new BasicAttribute("userPassword", userPassword.trim()))
                };
                template.modifyAttributes("cn="+userName+","+fileCatalog,modificationItems);
            }


        } catch (Exception e) {
            e.printStackTrace();
            return ResultTO.newFailResultTO("更新失败", null);
        }
        return ResultTO.newSuccessResultTO("更新成功", null);
    }
}

总结: openldap的属性是由openldap的基类决定的, 如下图:

Java通过Spring的LdapTemplate操作LDAP_第1张图片

 

你可能感兴趣的:(spring)