JAVA实现连接LDAP服务器密码认证

简述

  前阵子因为项目需要用到 LDAP ,发现从百度搜到的结果很少专一针对认证LDAP密码认证代码例子,废了很多功夫,很多的例子都是只是单单连接LDAP服务器(ctx = new InitialDirContext(env);)就完事了。所以特意奉上一段代码,对密码认证的。当然主要是对 获取某个DN下面的属性值进行对比 这样的一个操作。理论的话就不多说了,如果想了解 LDAP 以及想去了解调用LDAP接口的可以移步到我上一条转载的博客 【Java LDAP操作http://blog.csdn.net/charlven/article/details/78032221

实现方式:

方式一:最简单的账号密码认证方式

直接拿到用户的账号密码即可认证,没什么可描述的,直接上代码!

代码示例

try {
        String username=email.split("@")[0];   //uid
        String bindUserDN = "uid="+username+",ou=people,dc=department";  //用户 DN
        String bindPassword = "*****"; //用户密码
        String url = "ldap://127.0.0.1:389/";  //ldap服务器IP
        Hashtable<String, String> env = new Hashtable<String, String>();
        env.put(javax.naming.Context.INITIAL_CONTEXT_FACTORY, "com.sun.jndi.ldap.LdapCtxFactory");
        env.put(javax.naming.Context.PROVIDER_URL, url);
        env.put(javax.naming.Context.SECURITY_AUTHENTICATION, "simple");
        env.put(javax.naming.Context.SECURITY_PRINCIPAL, bindUserDN);
        env.put(javax.naming.Context.SECURITY_CREDENTIALS, bindPassword);
        javax.naming.directory.DirContext ctx = new javax.naming.directory.InitialDirContext(env);
        return "OK";
    } catch (Exception e) {
        // todo log
        return "FAILED";
    }

方式二:手动获取节点下的属性值进行校验

这种方式有点复杂,首先我们来整理一下获取LDAP密码认证的整体逻辑思路:

  1. 收集LDAP服务器信息 : 连接LDAP服务器账号和密码(连接每一个服务器都是需要账号密码的,就想连接MySql也需要密码),LDAP服务器 IP 地址 , 端口(Port) ,密码存在于 LDAP 服务器中的DN 、以及密码在该 DN 下的属性名 Attr

    String bindLdapUser;
    String bindLdapPassword;
    String baseDN;
    String ldapIp;
    String port;
    String mapAttr;
    
  2. 收集了以上信息之后开始对进行编码连接 LDAP 进行验证了。
    (1) 建立连接 ctx = new InitialDirContext(env);
    (2) 定义 SearchControls();调用 DirContext.search 方法。
    (3) 对search出来的结果NamingEnumeration进行遍历,因为search是获取当前节点下的所有支节点,不单单只是获取一个对象,如果想获取一个对象,可以调用lookup()方法。当然如果search()方法中依靠filter可以定位到一个对象节点,效果和lookup也是一样的。
    (4) 遍历过程中获取相应的Attributes。这个Attributes就是当前节点的所有属性,比如说当前节点是DN : sid=admin,ou=People,o=test ,那么获取出来的Attributes里面的属性将会是在此DN下你增加的所有属性比如(username=admin,password=123456,partment=xx,age=16.....)。这里我们获取其中的密码所以是

    Attribute attr = attrs.get("password");            
    String ldapPassword = (String)attr.get();       //获取出来的 ldapPassword 就是123456
    

    (5) 获取出来之后再对你传入的 requestPwd 和 ldap 获取出来的 ldapPassword 进行对比

    requestPwd.equals(ldapPassword);
    

    代码示例

    接下来直接贴上详细的代码,因为当时做的是认证,所以直接写成一个认证方法:

    private Map<String, Object> auth(String password, String userName) throws NamingException {
        String bindLdapUser = "root"; // 连接LDAP服务器的管理员账号密码
        String bindLdapPwd = "123456";
        String ldapBaseDN = "ou=People,o=test"; // 这个根据自己需要更改
        String attrName = "password";   // 获取DN下面的属性名
        String port = "389"; // ldap 服务器占用的端口号
        String ldapIp = "192.168.120.222"; // ldap 服务器的IP地址
    
        String url = "ldap://" + ldapIp + ":" + port + '/' + ldapBaseDN;
        System.console().printf("[auth ldap] ldap url : " + url);
    
        Hashtable<String, Object> env = new Hashtable<String, Object>();
        env.put(Context.INITIAL_CONTEXT_FACTORY, "com.sun.jndi.ldap.LdapCtxFactory");
        env.put(Context.SECURITY_AUTHENTICATION, "simple");
        env.put(Context.SECURITY_CREDENTIALS, bindLdapPwd);
        env.put(Context.SECURITY_PRINCIPAL, bindLdapUser);
        env.put(Context.PROVIDER_URL, url);
        DirContext ctx = null;
    
        try {
            // Ldap link
            ctx = new InitialDirContext(env);
            System.console().printf("[auth ldap linked] InitialDirContext success");
    
            // Ldap search
            SearchControls searchControls = new SearchControls();
            searchControls.setSearchScope(SearchControls.SUBTREE_SCOPE);
            String filter = "sid" + userName;// 加上filter之后DN就变成sid={userName},ou=People,o=test
            NamingEnumeration<?> nameEnu = ctx.search("", filter, searchControls);
            System.console().printf("[step1 ladp linked] begin to search, filter :" + filter);
    
            if (nameEnu == null) {
                // User Not Found
                System.console().printf("[step error] DirContext.search() return null. filter : " + filter);
                return createResult(104, 2001, "User Not Found");
            } else {
                System.console().printf("[step2 ldap] Begin to print elements");
                String ldapUserPwd = null;
    
                while (nameEnu.hasMore()) {
                    System.console().printf("[step3 ldap] nameEnu element is not null");
                    Object obj = nameEnu.nextElement();
                    System.console().printf(obj.toString());
                    if (obj instanceof SearchResult) {
                        System.console().printf("[step4 ldap] obj instanceof SearchResult");
                        SearchResult result = (SearchResult) obj;
                        Attributes attrs = result.getAttributes();
                        if (attrs == null) {
                            // Password Error
                            System.console().printf("[step error] SearchResult.getAttrbutes() is null. ");
                            return createResult(102, 4003, "Password Error");
                        } else {
                            System.console().printf("[step5 ldap] begin to get attribute : " + attrName);   // attrName就是属性名
                            Attribute attr = attrs.get(attrName);
                            if (attr != null) {
                                System.console().printf("[step6 ldap] attribute is not null.");
                                ldapUserPwd = (String) attr.get();
                                System.console().printf("[step7 print ldapPwd] the ldap password is : *********");
                                System.console().printf("[step7 print ldapPwd] the request password is : *********");
                                if (password.equalsIgnoreCase(ldapUserPwd)) {
                                    // OK
                                    System.console().printf("[step8 ldap] equals password , success .");
                                    return createResult(0, 0, "OK");
                                } else {
                                    // Password Error
                                    System.console().printf("[step9 ldap] equals password , failure . password is not same .");
                                    return createResult(102, 4003, "Password Error");
                                }
                            }
                        }
                    }
                }
                System.console().printf("[step error] while end . ldapUserPwd is null , can't find password from ldap .");
                return createResult(102, 4003, "Password Error");
            }
        } catch (NamingException e) {
            e.printStackTrace();
            System.console().printf("[ldap link failed] message :" + e.getMessage());
            throw e;
        } finally {
            if (ctx != null) {
                ctx.close();
            }
        }
    }
    
    private Map<String, Object> createResult(int ret, int code, String msg) {
      Map<String, Object> result = WmsvrFactory.createParamsObj();
      result.put("ret", ret);
      result.put("code", code);
      result.put("msg", msg);
      return result;
    }
    
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
  • 序言:七十年代末,一起剥皮案震惊了整个滨河市,随后出现的几起案子,更是在滨河造成了极大的恐慌,老刑警刘岩,带你破解...
    沈念sama阅读 219,366评论 6 508
  • 序言:滨河连续发生了三起死亡事件,死亡现场离奇诡异,居然都是意外死亡,警方通过查阅死者的电脑和手机,发现死者居然都...
    沈念sama阅读 93,521评论 3 395
  • 文/潘晓璐 我一进店门,熙熙楼的掌柜王于贵愁眉苦脸地迎上来,“玉大人,你说我怎么就摊上这事。” “怎么了?”我有些...
    开封第一讲书人阅读 165,689评论 0 356
  • 文/不坏的土叔 我叫张陵,是天一观的道长。 经常有香客问我,道长,这世上最难降的妖魔是什么? 我笑而不...
    开封第一讲书人阅读 58,925评论 1 295
  • 正文 为了忘掉前任,我火速办了婚礼,结果婚礼上,老公的妹妹穿的比我还像新娘。我一直安慰自己,他们只是感情好,可当我...
    茶点故事阅读 67,942评论 6 392
  • 文/花漫 我一把揭开白布。 她就那样静静地躺着,像睡着了一般。 火红的嫁衣衬着肌肤如雪。 梳的纹丝不乱的头发上,一...
    开封第一讲书人阅读 51,727评论 1 305
  • 那天,我揣着相机与录音,去河边找鬼。 笑死,一个胖子当着我的面吹牛,可吹牛的内容都是我干的。 我是一名探鬼主播,决...
    沈念sama阅读 40,447评论 3 420
  • 文/苍兰香墨 我猛地睁开眼,长吁一口气:“原来是场噩梦啊……” “哼!你这毒妇竟也来了?” 一声冷哼从身侧响起,我...
    开封第一讲书人阅读 39,349评论 0 276
  • 序言:老挝万荣一对情侣失踪,失踪者是张志新(化名)和其女友刘颖,没想到半个月后,有当地人在树林里发现了一具尸体,经...
    沈念sama阅读 45,820评论 1 317
  • 正文 独居荒郊野岭守林人离奇死亡,尸身上长有42处带血的脓包…… 初始之章·张勋 以下内容为张勋视角 年9月15日...
    茶点故事阅读 37,990评论 3 337
  • 正文 我和宋清朗相恋三年,在试婚纱的时候发现自己被绿了。 大学时的朋友给我发了我未婚夫和他白月光在一起吃饭的照片。...
    茶点故事阅读 40,127评论 1 351
  • 序言:一个原本活蹦乱跳的男人离奇死亡,死状恐怖,灵堂内的尸体忽然破棺而出,到底是诈尸还是另有隐情,我是刑警宁泽,带...
    沈念sama阅读 35,812评论 5 346
  • 正文 年R本政府宣布,位于F岛的核电站,受9级特大地震影响,放射性物质发生泄漏。R本人自食恶果不足惜,却给世界环境...
    茶点故事阅读 41,471评论 3 331
  • 文/蒙蒙 一、第九天 我趴在偏房一处隐蔽的房顶上张望。 院中可真热闹,春花似锦、人声如沸。这庄子的主人今日做“春日...
    开封第一讲书人阅读 32,017评论 0 22
  • 文/苍兰香墨 我抬头看了看天上的太阳。三九已至,却和暖如春,着一层夹袄步出监牢的瞬间,已是汗流浃背。 一阵脚步声响...
    开封第一讲书人阅读 33,142评论 1 272
  • 我被黑心中介骗来泰国打工, 没想到刚下飞机就差点儿被人妖公主榨干…… 1. 我叫王不留,地道东北人。 一个月前我还...
    沈念sama阅读 48,388评论 3 373
  • 正文 我出身青楼,却偏偏与公主长得像,于是被迫代替她去往敌国和亲。 传闻我的和亲对象是个残疾皇子,可洞房花烛夜当晚...
    茶点故事阅读 45,066评论 2 355

推荐阅读更多精彩内容