Spring LDAP 注解方式使用

Spring LDAP官方网站
https://docs.spring.io/spring-ldap/docs/2.3.3.RELEASE/reference/#preface

Maven导入包
<dependency>
  <groupId>commons-pool</groupId>
  <artifactId>commons-pool</artifactId>
  <version>1.6</version>
</dependency>

<dependency>
  <groupId>org.springframework.ldap</groupId>
  <artifactId>spring-ldap-core</artifactId>
  <version>2.3.3.RELEASE</version>
</dependency>
配置数据源
package net.lb.config;

import org.apache.tomcat.util.net.SSLUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.ldap.core.LdapTemplate;
import org.springframework.ldap.core.support.DefaultTlsDirContextAuthenticationStrategy;
import org.springframework.ldap.core.support.LdapContextSource;
import org.springframework.ldap.pool.factory.PoolingContextSource;
import org.springframework.ldap.pool.validation.DefaultDirContextValidator;

import javax.naming.Context;
import javax.naming.NamingException;
import javax.naming.directory.InitialDirContext;
import javax.naming.ldap.LdapContext;
import javax.net.ssl.HostnameVerifier;
import javax.net.ssl.SSLSession;
import java.util.HashMap;
import java.util.Hashtable;
import java.util.Map;
import java.util.Properties;

@Configuration
@EnableConfigurationProperties({LdapConfigureProperties.class})
public class LdapConfiguration {

    @Autowired
    LdapConfigureProperties ldapProperties;

    @Bean
    public SSLLdapContextSource sslLdapContextSource(){
        SSLLdapContextSource sslLdapContextSource = new SSLLdapContextSource();
        sslLdapContextSource.setUrls(ldapProperties.getLdapUrl().split(","));
        sslLdapContextSource.setBase(ldapProperties.getBaseDn());
        sslLdapContextSource.setUserDn(ldapProperties.getUserDn());
        sslLdapContextSource.setPassword(ldapProperties.getPassword());
        //sslLdapContextSource.setAuthenticationStrategy(getDefaultTlsDirContextAuthenticationStrategy());
        sslLdapContextSource.afterPropertiesSet();
        return sslLdapContextSource;
    }

    @Bean
    public LdapContextSource ldapContextSource() {
        LdapContextSource contextSource = new LdapContextSource();
        Map<String, Object> config = new HashMap();
        contextSource.setUrls(ldapProperties.getLdapUrl().split(","));
        contextSource.setBase(ldapProperties.getBaseDn());
        contextSource.setUserDn(ldapProperties.getUserDn());
        contextSource.setPassword(ldapProperties.getPassword());
        config.put("java.naming.ldap.attributes.binary", "objectGUID");
        contextSource.setBaseEnvironmentProperties(config);
        contextSource.afterPropertiesSet();
        return contextSource;
    }

    @Bean
    public DefaultDirContextValidator defaultDirContextValidator(){
        return new DefaultDirContextValidator();
    }

    @Bean
    public PoolingContextSource poolingContextSource() {
        PoolingContextSource poolingSource = new PoolingContextSource();
        if(ldapProperties.isUseSsl()) {
            poolingSource.setContextSource(sslLdapContextSource());
        }else {
            poolingSource.setContextSource(ldapContextSource());
        }
        poolingSource.setDirContextValidator(defaultDirContextValidator());
        poolingSource.setMaxActive(ldapProperties.getMaxActive());
        poolingSource.setMaxTotal(ldapProperties.getMaxTotal());
        poolingSource.setMaxIdle(ldapProperties.getMaxIdle());
        poolingSource.setMinIdle(ldapProperties.getMinIdle());
        poolingSource.setMaxWait(ldapProperties.getMaxWait());
        poolingSource.setTestOnBorrow(true);
        poolingSource.setTestWhileIdle(true);

        return poolingSource;
    }

    @Bean
    public DefaultTlsDirContextAuthenticationStrategy getDefaultTlsDirContextAuthenticationStrategy(){
        DefaultTlsDirContextAuthenticationStrategy strategy = new DefaultTlsDirContextAuthenticationStrategy();
        strategy.setShutdownTlsGracefully(true);
        strategy.setSslSocketFactory(new CustomSSLSocketFactory());
        strategy.setHostnameVerifier(new HostnameVerifier(){
            @Override
            public boolean verify(String hostname, SSLSession session){
                return true;
            }
        });
        return strategy;
    }
    @Bean
    @ConditionalOnMissingBean(name = "ldapTemplate")
    public LdapTemplate ldapTemplate() {
       return new LdapTemplate(poolingContextSource());
    }
}

读取配置文件类
package net.lb.config;

import lombok.Getter;
import lombok.Setter;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.context.annotation.Configuration;

@Getter
@Setter
@Configuration(value = "ldapProperties")
@ConfigurationProperties(value = "cas.custom.properties.ldap", ignoreUnknownFields = true)
@EnableConfigurationProperties({LdapConfigureProperties.class})
public class LdapConfigureProperties {
    private String ldapUrl;
    private boolean useSsl = false;
    private String baseDn;
    private String userDn;
    private String password;
    private String searchBn;
    private String searchAttribute;

    private int maxActive=20;
    private int maxTotal=40;
    private int maxIdle=10;
    private int minIdle=5;
    private int MaxWait=5;
}
配置文件

cas.custom.properties.ldap.ldapUrl=ldap://192.168.204.8:389,ldap://192.168.204.9:389
cas.custom.properties.ldap.userSsl=false
cas.custom.properties.ldap.baseDn=dc=wow,dc=gao
cas.custom.properties.ldap. userDn=npn\libo
cas.custom.properties.ldap.password=123456
cas.custom.properties.ldap.searchBn=CN=Users
cas.custom.properties.ldap.searchAttribute=employeeID
cas.custom.properties.ldap.maxActive=20
cas.custom.properties.ldap.maxTotal=40
cas.custom.properties.ldap. maxIdle=10
cas.custom.properties.ldap.minIdle=5
cas.custom.properties.ldap.MaxWait=5

SSL 数据源配置
package net.lb.config;

import org.springframework.ldap.core.support.LdapContextSource;

import javax.naming.Context;
import java.util.Hashtable;

public class SSLLdapContextSource extends LdapContextSource {
    public Hashtable<String, Object> getAnonymousEnv(){
        Hashtable<String, Object> anonymousEnv = super.getAnonymousEnv();
        anonymousEnv.put("java.naming.security.protocol", "ssl");
        anonymousEnv.put("java.naming.ldap.factory.socket", CustomSSLSocketFactory.class.getName());
        anonymousEnv.put(Context.INITIAL_CONTEXT_FACTORY, "com.sun.jndi.ldap.LdapCtxFactory");
        return anonymousEnv;
    }
}
证书解析
package net.lb.gateway.config;

import javax.net.SocketFactory;
import javax.net.ssl.SSLContext;

import javax.net.ssl.SSLSocketFactory;
import javax.net.ssl.TrustManager;
import javax.net.ssl.X509TrustManager;
import java.io.IOException;
import java.net.InetAddress;
import java.net.Socket;
import java.net.UnknownHostException;
import java.security.SecureRandom;
import java.security.cert.CertificateException;
import java.security.cert.X509Certificate;

public class CustomSSLSocketFactory extends SSLSocketFactory {
    private SSLSocketFactory socketFactory;
    public CustomSSLSocketFactory()
    {
        try {
            SSLContext ctx = SSLContext.getInstance("TLS");
            ctx.init(null, new TrustManager[]{ new DummyTrustmanager()}, new SecureRandom());
            socketFactory = ctx.getSocketFactory();
        } catch ( Exception ex ){ ex.printStackTrace(System.err);  }
    }
    public static SocketFactory getDefault(){
        return new CustomSSLSocketFactory();
    }
    @Override
    public String[] getDefaultCipherSuites() {
        return socketFactory.getDefaultCipherSuites();
    }

    @Override
    public String[] getSupportedCipherSuites() {
        return socketFactory.getSupportedCipherSuites();
    }

    @Override
    public Socket createSocket(Socket socket, String s, int i, boolean b) throws IOException {
        return socketFactory.createSocket(socket,s,i,b);
    }

    @Override
    public Socket createSocket(String s, int i) throws IOException, UnknownHostException {
        return socketFactory.createSocket(s,i);
    }

    @Override
    public Socket createSocket(String s, int i, InetAddress inetAddress, int i1) throws IOException, UnknownHostException {
        return socketFactory.createSocket(s,i,inetAddress,i1);
    }

    @Override
    public Socket createSocket(InetAddress inetAddress, int i) throws IOException {
        return socketFactory.createSocket(inetAddress,i);
    }

    @Override
    public Socket createSocket(InetAddress inetAddress, int i, InetAddress inetAddress1, int i1) throws IOException {
        return socketFactory.createSocket(inetAddress,i,inetAddress1,i1);
    }

    public static class DummyTrustmanager implements X509TrustManager {
        public void checkClientTrusted(X509Certificate[] cert, String string) throws CertificateException
        {
        }
        public void checkServerTrusted(X509Certificate[] cert, String string) throws CertificateException
        {
        }
        public X509Certificate[] getAcceptedIssuers()
        {
            return new java.security.cert.X509Certificate[0];
        }

    }
}

测试

package net.lb.gateway;

import net.lb.gateway.config.LdapConfigureProperties;
import net.lb.gateway.config.LdapUser;
import net.lb.gateway.config.LdapUserAttributeMapper;
import org.junit.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.ldap.NameNotFoundException;
import org.springframework.ldap.core.AttributesMapper;
import org.springframework.ldap.core.DirContextAdapter;
import org.springframework.ldap.core.LdapTemplate;
import org.springframework.ldap.filter.AndFilter;
import org.springframework.ldap.filter.EqualsFilter;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
import org.junit.runner.RunWith;
import static org.springframework.ldap.query.LdapQueryBuilder.query;

import javax.management.Query;
import javax.naming.NamingEnumeration;
import javax.naming.NamingException;
import javax.naming.directory.Attributes;
import javax.naming.directory.SearchControls;
import javax.naming.directory.SearchResult;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.Calendar;
import java.util.List;
import java.util.stream.Collectors;

@RunWith(SpringJUnit4ClassRunner.class)
@SpringBootTest
public class LdapTest {

    @Autowired
    private LdapTemplate ldapTemplate;


    @Autowired
    LdapConfigureProperties ldapProperties;

    @Test
    public void testfind() {
        try{
            String searchTeml =ldapProperties.getSearchAttribute();
            String search = String.format(searchTeml,"Libo");
            DirContextAdapter obj = (DirContextAdapter) ldapTemplate.lookup(search);

            System.out.println(obj);
            System.out.println(obj.getStringAttribute("sAMAccountName"));
            System.out.println(obj.getStringAttribute("employeeID"));
        }catch (NameNotFoundException nameNotFoundException){
            System.out.println("没有查询到实体");
        }

    }

    @Test
    public void testfindlist() {
        AndFilter filter = new AndFilter();
        filter.and(new EqualsFilter("objectClass", "person"));

        SearchControls controls = new SearchControls();
        controls.setSearchScope(SearchControls.SUBTREE_SCOPE);

        List<LdapUser> users = ldapTemplate.search("CN=Users", filter.encode(),controls, new LdapUserAttributeMapper());
        for (LdapUser user: users ) {
            System.out.println(user);
        }

    }

    @Test
    public void testfindlistsTRING() {
        AndFilter filter = new AndFilter();
        filter.and(new EqualsFilter("objectClass", "person"));

        SearchControls controls = new SearchControls();
        controls.setSearchScope(SearchControls.SUBTREE_SCOPE);

        List<String> users = (List<String>) ldapTemplate.search(ldapProperties.getSearchBn(), filter.encode(),controls, new AttributesMapper() {
            @Override
            public Object mapFromAttributes(Attributes attributes) throws NamingException {
                if(attributes.get(ldapProperties.getSearchAttribute()) != null){
                    if (attributes.get(ldapProperties.getSearchAttribute()).get().toString().equals("SAP12345678")){
                        return attributes.get("username").get().toString();
                    }
                }
                return null;
            }
        }).stream().filter(x->x!=null).collect(Collectors.toList());
        users.forEach(System.out::println);
    }


===================补丁==========

如何使用apache pool2

对于 commons-pool 1.x 使用下面的类:
org.springframework.ldap.pool.factory.PoolingContextSource

对于commons-pool 2.x 使用下面的类:
org.springframework.ldap.pool2.factory.PooledContextSource

Maven导入包
<dependency>
    <groupId>org.apache.commons</groupId>
    <artifactId>commons-pool2</artifactId>
    <version>2.9.0</version>
</dependency>
修改数据库链接池
import org.springframework.ldap.pool2.factory.PoolConfig;
import org.springframework.ldap.pool2.validation.DefaultDirContextValidator;
import org.springframework.ldap.pool2.factory.PooledContextSource;

@Bean
public PooledContextSource poolingContextSource() {
    PoolConfig poolConfig = new PoolConfig();
    poolConfig.setMaxTotal(ldapProperties.getMaxTotal());
    poolConfig.setMaxWaitMillis(ldapProperties.getMaxWait());
    /*The maximum number of active connections of each type (read-only|read-write) that can remain idle
        in the pool, without extra ones being released, or non-positive for no limit.*/
    poolConfig.setMaxIdlePerKey(ldapProperties.getMaxIdle());
    /*The limit on the number of object instances allocated by the pool (checked out or idle), per key.
        When the limit is reached, the sub-pool is said to be exhausted. A negative value indicates no limit.*/
    poolConfig.setMaxTotalPerKey(ldapProperties.getMaxActive());
    poolConfig.setTestOnBorrow(true);
    poolConfig.setTestWhileIdle(true);

    PooledContextSource poolingSource = new PooledContextSource(poolConfig);
    if(ldapProperties.isUseSsl()) {
        poolingSource.setContextSource(sslLdapContextSource());
    }else {
        poolingSource.setContextSource(ldapContextSource());
    }
    poolingSource.setDirContextValidator(defaultDirContextValidator());
    return poolingSource;
 }
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
禁止转载,如需转载请通过简信或评论联系作者。
  • 序言:七十年代末,一起剥皮案震惊了整个滨河市,随后出现的几起案子,更是在滨河造成了极大的恐慌,老刑警刘岩,带你破解...
    沈念sama阅读 199,519评论 5 468
  • 序言:滨河连续发生了三起死亡事件,死亡现场离奇诡异,居然都是意外死亡,警方通过查阅死者的电脑和手机,发现死者居然都...
    沈念sama阅读 83,842评论 2 376
  • 文/潘晓璐 我一进店门,熙熙楼的掌柜王于贵愁眉苦脸地迎上来,“玉大人,你说我怎么就摊上这事。” “怎么了?”我有些...
    开封第一讲书人阅读 146,544评论 0 330
  • 文/不坏的土叔 我叫张陵,是天一观的道长。 经常有香客问我,道长,这世上最难降的妖魔是什么? 我笑而不...
    开封第一讲书人阅读 53,742评论 1 271
  • 正文 为了忘掉前任,我火速办了婚礼,结果婚礼上,老公的妹妹穿的比我还像新娘。我一直安慰自己,他们只是感情好,可当我...
    茶点故事阅读 62,646评论 5 359
  • 文/花漫 我一把揭开白布。 她就那样静静地躺着,像睡着了一般。 火红的嫁衣衬着肌肤如雪。 梳的纹丝不乱的头发上,一...
    开封第一讲书人阅读 48,027评论 1 275
  • 那天,我揣着相机与录音,去河边找鬼。 笑死,一个胖子当着我的面吹牛,可吹牛的内容都是我干的。 我是一名探鬼主播,决...
    沈念sama阅读 37,513评论 3 390
  • 文/苍兰香墨 我猛地睁开眼,长吁一口气:“原来是场噩梦啊……” “哼!你这毒妇竟也来了?” 一声冷哼从身侧响起,我...
    开封第一讲书人阅读 36,169评论 0 254
  • 序言:老挝万荣一对情侣失踪,失踪者是张志新(化名)和其女友刘颖,没想到半个月后,有当地人在树林里发现了一具尸体,经...
    沈念sama阅读 40,324评论 1 294
  • 正文 独居荒郊野岭守林人离奇死亡,尸身上长有42处带血的脓包…… 初始之章·张勋 以下内容为张勋视角 年9月15日...
    茶点故事阅读 35,268评论 2 317
  • 正文 我和宋清朗相恋三年,在试婚纱的时候发现自己被绿了。 大学时的朋友给我发了我未婚夫和他白月光在一起吃饭的照片。...
    茶点故事阅读 37,299评论 1 329
  • 序言:一个原本活蹦乱跳的男人离奇死亡,死状恐怖,灵堂内的尸体忽然破棺而出,到底是诈尸还是另有隐情,我是刑警宁泽,带...
    沈念sama阅读 32,996评论 3 315
  • 正文 年R本政府宣布,位于F岛的核电站,受9级特大地震影响,放射性物质发生泄漏。R本人自食恶果不足惜,却给世界环境...
    茶点故事阅读 38,591评论 3 303
  • 文/蒙蒙 一、第九天 我趴在偏房一处隐蔽的房顶上张望。 院中可真热闹,春花似锦、人声如沸。这庄子的主人今日做“春日...
    开封第一讲书人阅读 29,667评论 0 19
  • 文/苍兰香墨 我抬头看了看天上的太阳。三九已至,却和暖如春,着一层夹袄步出监牢的瞬间,已是汗流浃背。 一阵脚步声响...
    开封第一讲书人阅读 30,911评论 1 255
  • 我被黑心中介骗来泰国打工, 没想到刚下飞机就差点儿被人妖公主榨干…… 1. 我叫王不留,地道东北人。 一个月前我还...
    沈念sama阅读 42,288评论 2 345
  • 正文 我出身青楼,却偏偏与公主长得像,于是被迫代替她去往敌国和亲。 传闻我的和亲对象是个残疾皇子,可洞房花烛夜当晚...
    茶点故事阅读 41,871评论 2 341