Spring LDAP 注解方式使用

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

Maven导入包

  commons-pool
  commons-pool
  1.6



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

配置数据源
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 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 getAnonymousEnv(){
        Hashtable 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 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 users = (List) 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导入包

    org.apache.commons
    commons-pool2
    2.9.0

修改数据库链接池
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;
 }

你可能感兴趣的:(Spring LDAP 注解方式使用)