美文网首页
Java-实现LDAP认证(获取用户信息)

Java-实现LDAP认证(获取用户信息)

作者: 你笑时很美丶 | 来源:发表于2018-11-05 14:36 被阅读0次

(可选)下载一个ldap浏览器,http://www.ldapbrowserwindows.com/

起个名字,下一步 填写好相关信息 账号密码 Filter是过滤信息,这里默认就好了,因为怕进去误删数据,我这里选择只查看 可以看到进去后它是一个目录结构,打开可以看到它的信息

前面我们已经测试了地址可以连进去并且看到了信息,下面是工具类代码(因为公司业务需求,所以写了这个工类,小伙伴们可以忽略),lombok这个包可以不导:

import java.util.Hashtable;
import javax.naming.Context;
import javax.naming.NamingException;
import javax.naming.ldap.InitialLdapContext;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
import lombok.extern.slf4j.Slf4j;

@Component
@Slf4j
public class LDAPUtil {

    @Value("${ldapUrl}")
    private String LDAPURL;
    @Value("${BaseDN}")
    private String BASEDN;

    public boolean connectLDAP(String userName, String passwd, String SearchName) {
        Hashtable<String, String> env = new Hashtable<String, String>();
        log.debug("===" + userName + "开始认证LDAP===");
        log.debug("password:" + passwd);

        boolean result = false;

        env.put(Context.SECURITY_PRINCIPAL, "uid=" + userName + "," + SearchName);//用户名
        log.debug("uid=" + userName + "," + SearchName);
        env.put(Context.SECURITY_CREDENTIALS, passwd);//密码
        env.put(Context.PROVIDER_URL, LDAPURL + BASEDN);//连接LDAP的URL和端口(这里的BASEDN你们可以不用,只要LDAPURL)
        env.put(Context.INITIAL_CONTEXT_FACTORY, "com.sun.jndi.ldap.LdapCtxFactory");//JNDI Context工厂类
        env.put(Context.SECURITY_AUTHENTICATION, "simple");//认证类型

        try {
            new InitialLdapContext(env, null);//开始连接
            result = true;
            log.debug("===认证成功===");
        } catch (NamingException e) {
            log.debug("===认证失败===");
        }
        return result;
    }
}

工具类写好之后我们写实现:

import java.util.HashMap;
import java.util.Hashtable;
import java.util.Map;
import javax.naming.Context;
import javax.naming.NamingEnumeration;
import javax.naming.NamingException;
import javax.naming.directory.Attribute;
import javax.naming.directory.SearchControls;
import javax.naming.directory.SearchResult;
import javax.naming.ldap.InitialLdapContext;
import javax.naming.ldap.LdapContext;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
import lombok.extern.slf4j.Slf4j;

/**
 * 
 * @version:
 * @Description: LDAP认证获取用户信息
 * @author: huyw
 * @date: 2018年10月5日 下午1:15:09
 */
@Slf4j
@Component
public class LADPGetUser {

    @Value("${BaseDN}")
    private String BASEDN;

    @Value("${pwd}")
    private String PASSWORD;

    @Value("${ldapUrl}")
    private String URL;

    @Value("${staffSearchName}")
    private String STAFFSEARCHNAME;

    @Value("${gstudentSearchName}")
    private String GSTUDENTSEARCHNAME;

    @Value("${studentSearchName}")
    private String STUDENTSEARCHNAME;

    @Value("${principle}")
    private String PRINCIPLE;

    @Autowired
    private LDAPUtil ldapUtil;

    public Map<String, Object> getUser(String uid, String pwd) {
        
        Map<String, Object> map = new HashMap<String, Object>();
        try {
            //连接LDAP
            LdapContext ctx = connetLDAP();
            //过滤条件
            String filter = "(&(objectClass=*)(uid=" + uid + "))";
            //要获取的字段信息
            String[] attrPersonArray = { "uid", "userPassword", "displayName", "cn", "sn", "mail", "description" };
            SearchControls searchControls = new SearchControls();//搜索控件
            searchControls.setSearchScope(2);//搜索范围
            searchControls.setReturningAttributes(attrPersonArray);
            //1.要搜索的上下文或对象的名称;2.过滤条件,可为null,默认搜索所有信息;3.搜索控件,可为null,使用默认的搜索控件
            NamingEnumeration<SearchResult> answer = ctx.search("ou=People,dc=uestc,dc=edu,dc=cn", filter.toString(),searchControls);

            while (answer.hasMore()) {
                SearchResult result = (SearchResult) answer.next();
                NamingEnumeration attrs = result.getAttributes().getAll();
                while (attrs.hasMore()) {
                    Attribute attr = (Attribute) attrs.next();
                    log.debug(attr.getID() + "=" + attr.get());
                    map.put(attr.getID(), attr.get());
                }
            }
            // 在校研究生
            boolean flag = ldapUtil.connectLDAP(uid, pwd, GSTUDENTSEARCHNAME);
            if (!flag) {
                // 在校本科生
                flag = ldapUtil.connectLDAP(uid, pwd, STUDENTSEARCHNAME);
                if (!flag) {
                    // 在校教职工
                    flag = ldapUtil.connectLDAP(uid, pwd, STAFFSEARCHNAME);
                }
            }
            map.put("flag", Boolean.valueOf(flag));

        } catch (Exception e) {
            log.error("===认证失败===");
        }

        return map;
    }

    public LdapContext connetLDAP() throws NamingException {

        log.debug("====管理员开始连接====");

        Hashtable<String, Object> env = new Hashtable<String, Object>();
        env.put(Context.SECURITY_PRINCIPAL, PRINCIPLE);//用户名
        env.put(Context.SECURITY_CREDENTIALS, PASSWORD);//密码
        env.put(Context.PROVIDER_URL, URL);//LDAP的地址:端口
        env.put(Context.INITIAL_CONTEXT_FACTORY, "com.sun.jndi.ldap.LdapCtxFactory");//LDAP工厂类
        env.put(Context.SECURITY_AUTHENTICATION, "simple");//认证类型
        LdapContext ctxTDS = new InitialLdapContext(env, null);//连接

        return ctxTDS;
    }
}

这个是我的配置文件:

#project
project.name=
project.packageName=

#ldap
Host=xxxxxx
Port=389
BaseDN=dc=xx,dc=xx,dc=xxx
principle=uid=xxxx,ou=xxxx,dc=xxx,dc=xxx,dc=xxx
pwd=xxx
ldapUrl=LDAP://xxxxxxxxx:389/

#搜索属性
#在校教职工所在ou:
#其实就是所在目录
staffSearchName=ou=xxx,ou=People,dc=uestc,dc=edu,dc=cn
#在校本科生所在ou:
studentSearchName=ou=xxx,ou=People,dc=uestc,dc=edu,dc=cn
#在校研究生所在ou:
gstudentSearchName=ou=xxx,ou=People,dc=uestc,dc=edu,dc=cn

LADP工具类:


import java.util.Hashtable;

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

import com.alibaba.fastjson.JSONObject;

/**
 * ldap连接
 * 
 * @version:
 * @Description:
 * @author: huyw
 * @date: 2018年12月24日 上午11:27:38
 */
public class LdapUtils {

    /**
     * 管理员连接
     * 
     * @Description:
     * @param principle
     * @param password
     * @param url
     * @return
     */
    public static LdapContext connectLdapAdmin(String principle, String password, String url) {
        LdapContext ctxTDS = null;
        Hashtable<String, Object> env = new Hashtable<String, Object>();
        env.put(Context.SECURITY_PRINCIPAL, principle);
        env.put(Context.INITIAL_CONTEXT_FACTORY, "com.sun.jndi.ldap.LdapCtxFactory");
        env.put(Context.SECURITY_CREDENTIALS, password);
        env.put(Context.PROVIDER_URL, url);
        env.put(Context.INITIAL_CONTEXT_FACTORY, "com.sun.jndi.ldap.LdapCtxFactory");
        env.put(Context.SECURITY_AUTHENTICATION, "simple");
        try {
            ctxTDS = new InitialLdapContext(env, null);
        } catch (NamingException e) {
            e.printStackTrace();
        }
        return ctxTDS;
    }

    /**
     * ldap
     */
    public static boolean connectLdap(String userName, String password, String SearchName, String ldapUrl,
            String baseDN) {
        Hashtable<String, String> env = new Hashtable<String, String>();
        boolean result = false;
        env.put(Context.SECURITY_PRINCIPAL, "uid=" + userName + "," + SearchName);
        env.put(Context.SECURITY_CREDENTIALS, password);
        env.put(Context.PROVIDER_URL, ldapUrl + baseDN);
        env.put(Context.INITIAL_CONTEXT_FACTORY, "com.sun.jndi.ldap.LdapCtxFactory");
        env.put(Context.SECURITY_AUTHENTICATION, "simple");
        try {
            new InitialLdapContext(env, null);
            result = true;
        } catch (NamingException e) {
            System.out.println("userName:" + userName + ",SearchName:" + SearchName + "登录失败");
        }
        return result;
    }

    public static void main(String[] args) {
        String certId = "";
        String password = "";
        String principle = "";
        String passwordLdap = "";
        String url = "";
        String teacherSearch = "";
        String studentSearch = "";
        String baseDN = "";
        try {
            LdapContext ctx = LdapUtils.connectLdapAdmin(principle, passwordLdap, url);
            String filter = "(&(objectClass=*)(uid=" + certId + "))";
            String[] attrPersonArray = { "uid", "employeeType", "displayName"};
            SearchControls searchControls = new SearchControls();
            searchControls.setSearchScope(2);
            searchControls.setReturningAttributes(attrPersonArray);
            NamingEnumeration<SearchResult> answer = ctx.search("ou=Users,dc=test,dc=edu,dc=cn", filter.toString(),
                    searchControls);
            JSONObject resultJson = new JSONObject();
            while (answer.hasMore()) {
                SearchResult result = (SearchResult) answer.next();
                NamingEnumeration attrs = result.getAttributes().getAll();
                while (attrs.hasMore()) {
                    Attribute attr = (Attribute) attrs.next();
                    resultJson.put(attr.getID(), attr.get());
                }
            }
            // 在校学生
            boolean studentFlag = LdapUtils.connectLdap(certId, password, studentSearch, url, baseDN);
            if (studentFlag) {
                System.out.println("ldap用户信息:" + resultJson.toJSONString());
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}

相关文章

网友评论

      本文标题:Java-实现LDAP认证(获取用户信息)

      本文链接:https://www.haomeiwen.com/subject/mhzjxqtx.html