关于openldap的一些java代码

认证代码

public static LdapContext getCtx(String username, String password) {
        String factory = "com.sun.jndi.ldap.LdapCtxFactory";
//        String root = "cn=admin,dc=auth,dc=equota,dc=cn"; // 用户
//        String pwd = "hello"; // pwd
        String simple = "simple";
        Hashtable<String, String> env = new Hashtable<>();
        env.put(Context.INITIAL_CONTEXT_FACTORY, factory);
        env.put(Context.PROVIDER_URL, url);
        env.put(Context.SECURITY_AUTHENTICATION, simple);
        env.put(Context.SECURITY_PRINCIPAL, username);
        env.put(Context.SECURITY_CREDENTIALS, password);
        LdapContext ctx = null;
        Control[] connCtls = null;
        try {
            ctx = new InitialLdapContext(env, connCtls);
        } catch (javax.naming.AuthenticationException e) {
            e.printStackTrace();
        } catch (Exception e) {
            e.printStackTrace();
        }
        return ctx;
    }

    public static LdapContext getCtx() {
        return getCtx("cn=admin,dc=auth,dc=equota,dc=cn", "hello");
    }

    public static boolean addUser(LdapUser user) {
        DirContext ctx = null;
        try {
            ctx = getCtx();
            BasicAttributes attrsbu = getBasicAttributes(user);
            
            String name = "uid=" + user.getUid() + ",ou=" + user.getOu() + ",dc=auth,dc=equota,dc=cn";
            ctx.createSubcontext(name, attrsbu);
            ctx.close();
            return true;
        } catch (NamingException ex) {
            try {
                if (ctx != null) {
                    ctx.close();
                }
            } catch (NamingException namingException) {
                namingException.printStackTrace();
            }

            ex.printStackTrace();
        }
        return false;
    }

    private static BasicAttributes getBasicAttributes(LdapUser user) {
        // TODO Auto-generated method stub
        BasicAttributes attrsbu = new BasicAttributes();
        BasicAttribute objclassSet = new BasicAttribute("objectclass");
        objclassSet.add("person");
        objclassSet.add("top");
        objclassSet.add("organizationalPerson");
        objclassSet.add("inetOrgPerson");
        attrsbu.put(objclassSet);
        attrsbu.put("sn", user.getSn());
        attrsbu.put("uid", user.getUid());
        attrsbu.put("userpassword", user.getUserPassword());
        attrsbu.put("cn", user.getCn());
        attrsbu.put("ou", user.getOu());
        attrsbu.put("businessCategory", user.getBusinessCategory());
        attrsbu.put("title", user.getTitle());
        attrsbu.put("employeeType", user.getEmployeeType());
        attrsbu.put("givenName", user.getGivenName());
        attrsbu.put("displayName", user.getDisplayName());
        attrsbu.put("mail", user.getMail());
        return attrsbu;
    }

    public static Object query(LoginUser user) {
        String username = user.getUsername();
        String department = user.getDepartment();
        if(StringUtils.isEmpty(username)) username = "*";
        LdapContext ctx = getCtx();
        List<LdapUser> result = new ArrayList<LdapUser>();
        try {
            SearchControls constraints = new SearchControls();
            constraints.setSearchScope(SearchControls.SUBTREE_SCOPE);
            // 限制要查询的字段内容
            // String[] attrPersonArray = { "cn", "memberUid","userPassword" };
            // 设置将被返回的Attribute
            // constraints.setReturningAttributes(attrPersonArray);
            String query = "dc=auth,dc=equota,dc=cn";
            if(!StringUtils.isEmpty(department)) query += "ou=" + department +",";
            NamingEnumeration<?> en = ctx.search(query, "uid=" + username, constraints);
            while (en != null && en.hasMoreElements()) {
                Object obj = en.nextElement();
                Map<String, Object> map = new HashMap<String, Object>();
                if (obj instanceof SearchResult) {
                    SearchResult si = (SearchResult) obj;
                    map.put("name", si.getName());
                    Attributes attrs = si.getAttributes();
                    if (attrs == null) {
                        System.out.println("No   attributes ");
                    } else {
                        for (NamingEnumeration<?> ae = attrs.getAll(); ae.hasMoreElements();) {
                            Attribute attr = (Attribute) ae.next();
                            String attrId = attr.getID();

                            for (NamingEnumeration<?> vals = attr.getAll(); vals.hasMoreElements();) {
                                Object o = vals.nextElement();
                                if (o instanceof byte[]) {
                                    map.put(attrId, new String((byte[]) o));
                                } else {
                                    map.put(attrId, o);
                                }
                                
                            }
                        }
                    }
                } else {
                    return obj;
                }
                LdapUser ldapUser = BeanUtil.toBean(map, LdapUser.class);
                result.add(ldapUser);
            }
        } catch (Exception e) {
            e.printStackTrace();
            try {
                if (ctx != null) {
                    ctx.close();
                }
            } catch (NamingException ex) {
                ex.printStackTrace();
            }
        }
        Map<String,List<LdapUser>> map = result.stream().collect(Collectors.groupingBy(LdapUser::getOu));
        return map;
    }
    
    /***
     * 修改用户信息
     */
    public static void updateUserData(String username, String department, String field, String value) throws NamingException {
        LdapContext ctx = getCtx();
        ModificationItem modificationItem[] = new ModificationItem[1];
        modificationItem[0] = new ModificationItem(DirContext.REPLACE_ATTRIBUTE, new BasicAttribute(field, value));
        ctx.modifyAttributes("uid=" + username + ",ou=" + department + "," + basedn, modificationItem);
    }

猜你喜欢

转载自blog.csdn.net/IamstudyingJava/article/details/131707487