我爱编程LDAPspringboot

Spring LDAP的使用

2017-12-08  本文已影响3555人  消失er

LDAP入门http://www.jianshu.com/p/7e4d99f6baaf

下面是使用Spring-ldap的依赖
<!-- spring ldapTemplate操作 -->
        <dependency>
            <groupId>com.sun</groupId>
            <artifactId>ldapbp</artifactId>
            <version>1.0</version>
        </dependency>
        <dependency>
            <groupId>org.springframework.ldap</groupId>
            <artifactId>spring-ldap-core</artifactId>
            <version>2.3.2.RELEASE</version>
        </dependency>
下面是用Java代码的方式定义LdapTemplate,完成用Spring ldap连接LDAP服务器
import com.cvte.csb.sim.ldap.constants.LdapConstans;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.PropertySource;
import org.springframework.ldap.core.ContextSource;
import org.springframework.ldap.core.LdapTemplate;
import org.springframework.ldap.core.support.LdapContextSource;
import org.springframework.ldap.pool.factory.PoolingContextSource;
import org.springframework.ldap.pool.validation.DefaultDirContextValidator;
import org.springframework.ldap.transaction.compensating.manager.TransactionAwareContextSourceProxy;
import java.util.HashMap;
import java.util.Map;

/**
 * LDAP 的自动配置类
 *
 * 完成连接 及LdapTemplate生成
 */
@Configuration
public class LdapConfiguration {

    private LdapTemplate ldapTemplate;

    @Bean
    public LdapContextSource contextSource() {
        LdapContextSource contextSource = new LdapContextSource();
        Map<String, Object> config = new HashMap();

        contextSource.setUrl(LdapConstans.LDAP_URL);
        contextSource.setBase(LdapConstans.BASE_DC);
        contextSource.setUserDn(LdapConstans.USER_NAME);
        contextSource.setPassword(LdapConstans.PASS_WORD);

        //  解决 乱码 的关键一句
        config.put("java.naming.ldap.attributes.binary", "objectGUID");

        contextSource.setPooled(true);
        contextSource.setBaseEnvironmentProperties(config);
        return contextSource;
    }
 
    @Bean
    public LdapTemplate ldapTemplate() {
        if (null == ldapTemplate)
            ldapTemplate = new LdapTemplate(contextSource());
        return ldapTemplate;
    }

}
下面给出用LdapTemplate完成CRUD功能:
import com.cvte.csb.sim.ldap.attribute.LdapDeptAttributeMapper;
import com.cvte.csb.sim.ldap.attribute.LdapUserAttributeMapper;
import com.cvte.csb.sim.ldap.module.dto.LdapUser;
import org.junit.Assert;
import org.junit.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.ldap.core.DirContextAdapter;
import org.springframework.ldap.core.DistinguishedName;
import org.springframework.ldap.core.LdapTemplate;
import org.springframework.ldap.filter.AndFilter;
import org.springframework.ldap.filter.EqualsFilter;
import java.util.List;

public class ConfigTest extends BaseTest {
    @Autowired
    private LdapTemplate ldapTemplate;

    /**
     * 获取所有 内部人员
     * ou=Internal,ou=People
     */
    @Test
    public void listUsers(){
        AndFilter filter = new AndFilter();
        filter.and(new EqualsFilter("objectClass", "person"));

        //查询所有内部人员
        List<LdapUser> users = ldapTemplate.search("ou=Internal,ou=People", filter.encode(), new LdapUserAttributeMapper());
        for (LdapUser user: users ) {
            System.out.println(user);
        }

//        Assert.assertEquals(3056, users.size());
    }

    /**
     * 根据uid 查找单个人员
     */
    @Test
    public void findUser(){

        //uid=00012047,ou=Internal,ou=People,o=cvte.com,o=isp
        DirContextAdapter obj = (DirContextAdapter) ldapTemplate.lookup("uid=00012047,ou=Internal,ou=People");//BASE_DC 不用填
        System.out.println(obj);
    }

    /**
     * 根据部门编号o,查找部门
     */
    @Test
    public void findDept(){
        //o=598b09cb12ab4364864d8ac73ecee00d,ou=Organizations,ou=People,o=cvte.com,o=isp
        DirContextAdapter obj = (DirContextAdapter) ldapTemplate.lookup("o=598b09cb12ab4364864d8ac73ecee00d,ou=Organizations");//BASE_DC 不用填
        System.out.println(obj);
    }

    @Test
    public void listDepts(){
        AndFilter filter = new AndFilter();
        filter.and(new EqualsFilter("objectClass", "organization"));
        //search是根据过滤条件进行查询,第一个参数是父节点的dn,可以为空,不为空时查询效率更高
        List depts = ldapTemplate.search("", filter.encode(), new LdapDeptAttributeMapper());
        System.out.println(depts.size());
//        Assert.assertEquals(3056, depts.size());
    }
}

我们注意到,findAll(),list()肯定是返回一个java.util.List<T>,包括,

//查询所有内部人员
List<LdapUser> users = ldapTemplate.search("ou=Internal,ou=People", filter.encode(), new LdapUserAttributeMapper());

也是返回列表,列表里装的是查询出来的结果。但是上一篇文章用JNDI方式查询出来的是
Attributes attrs = ctx.getAttributes("uid=00012047,ou=Internal,ou=People");//获取到一个人员
Spring-ldap是基于JNDI实现的封装,那是哪里实现的把Attributes转成我们需要的Java Bean对象呢?
答案在new LdapUserAttributeMapper(),这个接口实现了查询结果到对象的转化。

import com.cvte.csb.sim.ldap.module.dto.LdapUser;
import org.springframework.ldap.core.AttributesMapper;
import javax.naming.NamingException;
import javax.naming.directory.Attributes;

/**
 * 将ldap返回的结果,转成指定对象
 */
public class LdapUserAttributeMapper implements AttributesMapper {

    /**
     * 将单个Attributes转成单个对象
     * @param attrs
     * @return
     * @throws NamingException
     */
    public Object mapFromAttributes(Attributes attrs) throws NamingException {
        LdapUser user  = new LdapUser();

        if(attrs.get("uid") != null){
            user.setUsername( attrs.get("uid").get().toString());
        }
        if(attrs.get("cn") != null){
            user.setUserCn( attrs.get("cn").get().toString());
        }
        if(attrs.get("mobile") != null){
            user.setMobile( attrs.get("mobile").get().toString());
        }
        if(attrs.get("mail") != null){
            user.setMail( attrs.get("mail").get().toString());
        }
        if(attrs.get("employeeNumber") != null){
            user.setUserNumber( attrs.get("employeeNumber").get().toString());
        }

        if(attrs.get("type") != null){
            user.setUserType( attrs.get("type").get().toString());
        }
        if(attrs.get("py") != null){
            user.setPinyin(attrs.get("py").get().toString());
        }
        if(attrs.get("alias") != null){
            user.setAlias(attrs.get("alias").get().toString());
        }
        if(attrs.get("departmentNumber") != null){
            user.setDeptId(attrs.get("departmentNumber").get().toString());
        }
        if(attrs.get("departmentName") != null){
            user.setDeptName(attrs.get("departmentName").get().toString());
        }
        if(attrs.get("jobname") != null){
            user.setPositionName(attrs.get("jobname").get().toString());
        }
        if(attrs.get("modifyTimestamp") != null){
            user.setModifyTimestamp(attrs.get("modifyTimestamp").get().toString());
        }
        return user;
    }
}

可以看到转化的过程非常繁琐,无非就是拿JNDI查询到的Attributes,不停的获取属性值,再设置到Java对象中;attrs.get("uid").get().toString()然后set。

那好了,在每次查询的时候,要查询到多少列,在这个AttributesMapper转化方法中就要写多少个,判断及赋值。而且,如果因为业务不同,要查询不同的列,那AttributesMapper接口的实现必须重新写。那有没有支持复用的方式呢?答案是肯定的。下节分享spring ldap ODM , Object-Directory Mapping。

spring-ldap-2.3.2.RELEASE所有jar包下载
http://download.csdn.net/download/ljheee/10150501

Spring-ldap最新版官方文档:
https://docs.spring.io/spring-ldap/docs/2.3.2.RELEASE/reference/

上一篇下一篇

猜你喜欢

热点阅读