Ldap实现AD域认证

2018-06-18 03:23:33来源:未知 阅读 ()

新老客户大回馈,云服务器低至5折

1、java Ldap基础类

package com.common;

import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.UnsupportedEncodingException;
import java.util.ArrayList;
import java.util.Hashtable;
import java.util.List;
import java.util.Properties;

import javax.naming.Context;
import javax.naming.NamingEnumeration;
import javax.naming.NamingException;
import javax.naming.directory.Attribute;
import javax.naming.directory.Attributes;
import javax.naming.directory.DirContext;
import javax.naming.directory.SearchControls;
import javax.naming.directory.SearchResult;
import javax.naming.ldap.InitialLdapContext;
import javax.naming.ldap.LdapContext;

import org.apache.log4j.LogManager;
import org.apache.log4j.Logger;

public class LdapLoadUserAD {
    private static final Logger logger = LogManager.getLogger(LdapLoadUserAD.class);
    private LdapContext ctx = null;
    private String adminName = "TEST\\Administrator";
    private String adminpassword = "admin";
    private String host = "10.24.7.252";
    private String port = "389";
    private String ldapURL = new String("ldap://" + host + ":" + port);
    private String searchBase = "OU=组织单位1,DC=test,DC=com";
    private String searchFilter = "(&(objectClass=group)(cn=" + "war3" + "))";
    private String returnedAtts[] = { "url", "whenChanged", "employeeID",
            "name", "userPrincipalName", "physicalDeliveryOfficeName",
            "departmentNumber", "telephoneNumber", "homePhone", "mobile",
            "department", "sAMAccountName", "whenChanged", "mail" };

    /**
     * 已管理员身份 初始ad域服务器 (后期改进配置文件)
     * 
     * @return
     * @throws UnsupportedEncodingException 
     */
    public boolean initial_Ldap() throws UnsupportedEncodingException {
        Hashtable env = new Hashtable();
        env.put(Context.INITIAL_CONTEXT_FACTORY,
                "com.sun.jndi.ldap.LdapCtxFactory");
        env.put(Context.SECURITY_AUTHENTICATION, "simple");
        env.put(Context.SECURITY_PRINCIPAL, adminName);
        env.put(Context.SECURITY_CREDENTIALS, adminpassword);
        env.put(Context.PROVIDER_URL, ldapURL);
        try {
            logger.info("Start InitialLdapContext");
            ctx = new InitialLdapContext(env, null);
            logger.info("InitialLdapContext succeed");
        } catch (NamingException e) {
            logger.error("Problem initial_Ldap NamingException: " + e);
            return false;
        }
        return true;
    }

    public boolean initial_Ldap(String administratorName,
            String administratorPwd, String url) throws UnsupportedEncodingException {
        Hashtable env = new Hashtable();
        env.put(Context.INITIAL_CONTEXT_FACTORY,
                "com.sun.jndi.ldap.LdapCtxFactory");
        env.put(Context.SECURITY_AUTHENTICATION, "simple");
        env.put(Context.SECURITY_PRINCIPAL, administratorName);
        env.put(Context.SECURITY_CREDENTIALS, administratorPwd);
        env.put(Context.PROVIDER_URL, url);
        try {
            logger.info("Start InitialLdapContext");
            ctx = new InitialLdapContext(env, null);
            logger.info("InitialLdapContext succeed");
        } catch (NamingException e) {
            logger.error("Problem initial_Ldap NamingException: " + e);
            return false;
        }

        return true;
    }

    public boolean initial_Ldap(String administratorName,
            String administratorPwd, String url, String keystore,
            String keyPassword) {
        Hashtable env = new Hashtable();
        System.setProperty("javax.net.ssl.trustStore", keystore);
        System.setProperty("javax.net.ssl.trustStorePassword", keyPassword);
        env.put(Context.INITIAL_CONTEXT_FACTORY,
                "com.sun.jndi.ldap.LdapCtxFactory");
        env.put(Context.SECURITY_AUTHENTICATION, "simple");
        env.put(Context.SECURITY_PRINCIPAL, administratorName);
        env.put(Context.SECURITY_CREDENTIALS, administratorPwd);
        env.put(Context.SECURITY_PROTOCOL, "ssl");
        env.put(Context.PROVIDER_URL, url);
        try {
            logger.info("Start InitialLdapContext");
            ctx = new InitialLdapContext(env, null);
            logger.info("InitialLdapContext succeed");
        } catch (NamingException e) {
            logger.error("Problem initial_Ldap NamingException: " + e);
            return false;
        }

        return true;
    }

    /**
     * 关闭Close Ldap
     * 
     * @return
     */
    public boolean close_Ldap() {
        logger.info("Close Ldap");
        try {
            ctx.close();
        } catch (NamingException e) {
            logger.error("Problem close_Ldap NamingException: " + e);
            return false;
        }
        return true;
    }

    /**
     * 自定义返回ldap树节点内容
     * 
     * @param username
     *            如果不为空返回指定节点内容
     * @return
     */
    public Hashtable<String, List> search_distinguishedName(String username) {
        if (!(username.equals(""))) {
            String searchFilter = "(&(objectClass=user)(cn=" + username + "))";
            this.setSearchFilter(searchFilter);
        }

        Hashtable<String, List> ls = new Hashtable<String, List>();
        try {
            logger.info("Start search " + username+ "'s distinguishedName");
            SearchControls searchCtls = new SearchControls();
            searchCtls.setSearchScope(SearchControls.SUBTREE_SCOPE);
            searchCtls.setReturningAttributes(this.getReturnedAtts());
            NamingEnumeration answer = ctx.search(this.getSearchBase(),
                    this.getSearchFilter(), searchCtls);
            int totalResults = 0;// Specify the attributes to return
            int rows = 0;
            while (answer.hasMoreElements()) {// 遍历结果集
                SearchResult sr = (SearchResult) answer.next();// 得到符合搜索条件的DN

                String dn = sr.getName();

                String match = dn.split("CN=")[1].split(",")[0];// 返回格式一般是CN=test,OU=测试
                logger.info("match=" + match);

                Attributes Attrs = sr.getAttributes();// 得到符合条件的属性集
                if (Attrs != null) {
                    try {
                        for (NamingEnumeration ne = Attrs.getAll(); ne
                                .hasMore();) {
                            List nb = new ArrayList();
                            ;
                            Attribute Attr = (Attribute) ne.next();// 得到下一个属性
                            String valueid = Attr.getID().toString();
                            logger.info(" AttributeID=属性名:" + valueid);

                            // 读取属性值
                            for (NamingEnumeration e = Attr.getAll(); e
                                    .hasMore(); totalResults++) {

                                String value = e.next().toString();
                                logger.info("    AttributeValues=属性值:"+ value);
                                nb.add(value);
                            }
                            ls.put(valueid, nb);
                            logger.info("    ---------------");

                        }
                    } catch (NamingException e) {
                        logger.error("Throw Exception : " + e);
                    }
                }// if

            }
        } catch (NamingException e) {
            logger.error("Problem search_distinguishedName NamingException: "
                            + e);

        }
        return ls;
    }

    
    public boolean searchAD(String username, String pwd, String domain) {

        try {
            Properties env = new Properties();
            //String account = username + "@" + domain;
            String ldapURL = "LDAP://" + this.host + ":" + this.port;

            env.put(Context.PROVIDER_URL, ldapURL);
            env.put(Context.SECURITY_PRINCIPAL, username);
            env.put(Context.SECURITY_CREDENTIALS, pwd);
            //获取配置
            //env = this.getAdProperties(env);
            env.put(Context.SECURITY_AUTHENTICATION, "simple");
            env.put(Context.INITIAL_CONTEXT_FACTORY, "com.sun.jndi.ldap.LdapCtxFactory");
            // 批量处理
            env.put(Context.BATCHSIZE, "50");
            // 连接超时设置
            env.put("com.sun.jndi.ldap.connect.timeout","300000");
            // LDAP连接池
            env.put("com.sun.jndi.ldap.connect.pool", "true");
            // LDAP连接池最大数
            env.put("com.sun.jndi.ldap.connect.pool.maxsize", "30");
            // LDAP连接池优先数
            env.put("com.sun.jndi.ldap.connect.pool.prefsize", "10");
            // LDAP连接池超时
            env.put("com.sun.jndi.ldap.connect.pool.timeout", "3000");
            // LDAP连接池初始化数
            env.put("com.sun.jndi.ldap.connect.pool.initsize", "10");
            // LDAP连接池的认证方式
            env.put("com.sun.jndi.ldap.connect.pool.authentication", "simple");

            DirContext dc = new InitialLdapContext(env, null);
            logger.info("认证成功");

            SearchControls searchCtls = new SearchControls();
            searchCtls.setSearchScope(SearchControls.SUBTREE_SCOPE);
            String searchFilter = "(&(objectCategory=person)(objectClass=user)(name=*))";
            String searchBase = "DC=test,DC=com";
            String returnedAtts[] = {"memberOf","uSNCreated"};
            searchCtls.setReturningAttributes(returnedAtts);
            NamingEnumeration<SearchResult> answer = dc.search(searchBase, searchFilter,searchCtls);
            while (answer.hasMoreElements()) {
                SearchResult sr = (SearchResult) answer.next();
                logger.info("<<<::[" + sr.getName()+",uSNCreated="+sr.getAttributes().get("uSNCreated")+"]::>>>>");
            }
            dc.close();

            return true;
        } catch (Exception e) {
            logger.error("认证失败:"+e.getMessage());
            return false;
        }

    }
    /**
     * 验证AD域用户登录
     * 
     * @param username
     *            用户名
     * @param pwd
     *            密码
     * @param domain
     *            域名称
     * @return
     */
    public boolean login(String username, String pwd, String url,String domain) {
        try {
            //String account = username + "@" + domain;
            //String ldapURL = "LDAP://" + this.host + ":" + this.port;
            //username = "test\\"+username;
            username = domain+"\\"+username;
            Properties env = new Properties();
            String ldapURL = "LDAP://" + url;
            env.put(Context.PROVIDER_URL, ldapURL);
            env.put(Context.SECURITY_PRINCIPAL, username);
            env.put(Context.SECURITY_CREDENTIALS, pwd);
            logger.info("------------ LdapLoadUserAD ---- login 1------------------ ldapURL="+ldapURL+"---username="+username+"---pwd="+pwd);
            //获取配置
            env = this.getAdProperties(env);
            //认证
            DirContext dc = new InitialLdapContext(env, null);
            logger.debug("AD域认证登录成功LDAP接口" + " - username:[" + username +"] pwd:["+ pwd +"]");
            dc.close();
            return true;
        } catch (Exception e) {
            logger.error("AD域认证登陆失败LDAP接口:【"+ e.getMessage() + "】 - username:[" + username +"] pwd:["+ pwd +"]");
            return false;
        }

    }
    /**
     * 读取配置文件 配置AD域
     */
    public Properties getAdProperties (Properties env) throws IOException{
        InputStream is =null;
        Properties props = new Properties();
        try{
            String f0 = Common.getClassPath() + "ad.properties";
            is = new FileInputStream(f0);
            props.load(is);
        }catch(Exception e){
            e.printStackTrace();
        }finally{
            if(null != is){
                is.close();
                is = null;
            }
        }
        env.put(Context.SECURITY_AUTHENTICATION, props.getProperty("context.security.authentication"));
        env.put(Context.INITIAL_CONTEXT_FACTORY, props.getProperty("context.initial.context.factory"));
        // 批量处理
        env.put(Context.BATCHSIZE, props.getProperty("context.batchsize"));
        // 连接超时设置
        env.put("com.sun.jndi.ldap.connect.timeout", props.getProperty("ldap.connect.pool.timeout"));
        // LDAP连接池
        env.put("com.sun.jndi.ldap.connect.pool", props.getProperty("ldap.connect.pool"));
        // LDAP连接池最大数
        env.put("com.sun.jndi.ldap.connect.pool.maxsize", props.getProperty("ldap.connect.pool.maxsize"));
        // LDAP连接池优先数
        env.put("com.sun.jndi.ldap.connect.pool.prefsize", props.getProperty("ldap.connect.pool.prefsize"));
        // LDAP连接池超时
        env.put("com.sun.jndi.ldap.connect.pool.timeout", props.getProperty("ldap.connect.pool.timeout"));
        // LDAP连接池初始化数
        env.put("com.sun.jndi.ldap.connect.pool.initsize", props.getProperty("ldap.connect.pool.initsize"));
        // LDAP连接池的认证方式
        env.put("com.sun.jndi.ldap.connect.pool.authentication", props.getProperty("ldap.connect.pool.authentication"));
        return env;
    }

    /**
     * 返回登录域用户
     * 
     * @return
     */
    public String getAdminName() {
        return adminName;
    }

    /**
     * 返回搜索域节点
     * 
     * @return
     */
    public String getSearchBase() {
        return searchBase;
    }

    /**
     * 设置 ad域 (ldapURL)中 搜索域节点
     * 
     * @param searchBase
     */
    public void setSearchBase(String searchBase) {
        this.searchBase = searchBase;
    }

    /**
     * 返回搜索过滤器
     * 
     * @return
     */
    public String getSearchFilter() {
        return searchFilter;
    }

    /**
     * 设置 LDAP搜索过滤器
     * 
     * @param searchFilter
     */
    public void setSearchFilter(String searchFilter) {
        this.searchFilter = searchFilter;
    }

    /**
     * 返回 域节点、过滤器类和搜索控制器搜索LDAP得到结果
     * 
     * @return
     */
    public String[] getReturnedAtts() {
        return returnedAtts;
    }

    /**
     * 设置的域节点、过滤器类和搜索控制器搜索LDAP得到结果
     * 
     * @param returnedAtts
     */
    public void setReturnedAtts(String[] returnedAtts) {
        this.returnedAtts = returnedAtts;
    }

    /**
     * 设置登录域用户
     * 
     * @param adminName
     */
    public void setAdminName(String adminName) {
        this.adminName = adminName;
    }

    public String getAdminpassword() {
        return adminpassword;
    }

    public void setAdminpassword(String adminpassword) {
        this.adminpassword = adminpassword;
    }

    public String getHost() {
        return host;
    }

    public void setHost(String host) {
        this.host = host;
    }

    public String getPort() {
        return port;
    }

    public void setPort(String port) {
        this.port = port;
    }

    public String getLdapURL() {
        return ldapURL;
    }

    public void setLdapURL(String ldapURL) {
        this.ldapURL = ldapURL;
    }

    
}

2、java业务逻辑调用基层方法即可  这个是验证用户名 密码的调用

//连接AD域 验证登录用户名、密码是否正确
            LdapLoadUserAD inst = new LdapLoadUserAD();
            String url = this.userService.getParams("ad_ip")+":"+this.userService.getParams("ad_port");//AD域地址
            String domain = this.userService.getParams("ad_domain");//AD域域名
            succ = inst.login(username,password,url,domain);

3、写一个配置AD域库 相关参数配置的文件ad.properties 方便读取 修改

#AD域库 相关参数配置

#连接超时设置
ldap.connect.timeout=300000
#LDAP连接池
ldap.connect.pool=true
#LDAP连接池最大数
ldap.connect.pool.maxsize=30
#LDAP连接池优先数
ldap.connect.pool.prefsize=10
#LDAP连接池超时
ldap.connect.pool.timeout=3000
#LDAP连接池初始化数
ldap.connect.pool.initsize=10
#LDAP连接池的认证方式
ldap.connect.pool.authentication=simple
#批量处理
context.batchsize=50
#认证类型
context.security.authentication=simple
#初始上下文工厂
context.initial.context.factory=com.sun.jndi.ldap.LdapCtxFactory

4、代码部分大致是这个意思了,测试调试的时候,需要配置微软的AD域库,具体配置方案网上还是很多的。

标签:

版权申明:本站文章部分自网络,如有侵权,请联系:west999com@outlook.com
特别注意:本站所有转载文章言论不代表本站观点,本站所提供的摄影照片,插画,设计作品,如需使用,请与原作者联系,版权归原作者所有

上一篇:AOP 切面编程------JoinPoint ---- log日志

下一篇:java基础 final 修饰成员变量 只能赋值一次问题