JAVA操作Ldap示例

JAVA使用javax.naming.*;连接和操作ldap

1. 连接ldap

    private static String url = "ldaps://IP地址:636";

    private static String adminName = "登陆的用户名";
    private static String adminPwd = "密码";

    private static String fileName = "证书的无力路径";
    private static String keystoreAsString = "";
    private static String keystorePwd = "证书的密码";
    public static DirContext context = null;
public static void connectLdap(){
        setKeystoreAsString();
        System.setProperty("javax.net.ssl.trustStore" , keystoreAsString);
        System.setProperty("javax.net.ssl.trustStorePassword" , keystorePwd);
        Hashtable env = new Hashtable();
        env.put(Context.INITIAL_CONTEXT_FACTORY, "com.sun.jndi.ldap.LdapCtxFactory");
        env.put(Context.PROVIDER_URL, url);
        env.put(Context.SECURITY_AUTHENTICATION, "simple");
        env.put(Context.SECURITY_PROTOCOL, adminName);
        env.put(Context.SECURITY_CREDENTIALS, adminPwd);
        env.put(Context.SECURITY_PROTOCOL, "ssl");
        try{
            context = new InitialDirContext(env);
            System.out.println("connect to ldap success!");
        }catch (NamingException e){
            e.printStackTrace();
        }
    }

这里是用ssl方式连接,所以需要从服务器中导出证书

2. 操作ldap

2.1. 查询得到所有的container(类似的查询所有的group等)

private static List getContainerList(){
        if(context == null){
            connectLdap();
        }
        List containerList= new ArrayList();
        SearchControls ctl = new SearchControls();
        ctl.setSearchScope(SearchControls.SUBTREE_SCOPE);
        try{
            NamingEnumeration en = context.search(DN, "(&(&(objectClass=top)(objectClass=container))(!(objectClass=group)))", ctl);
            while ((en != null) && (en.hasMoreElements())){
                Object obj = en.nextElement();
                if( obj instanceof SearchResult)
                {
                    SearchResult result = (SearchResult)obj;
                    Attributes attrs = result.getAttributes();
                    if(attrs == null)
                    {
                        System.out.println("No containers");
                    }
                    else {
                        containerList.add((String) attrs.get("cn").get(0));
                    }
                }
            }
        }catch (NamingException e){
            e.printStackTrace();
        }

        return containerList;
    }

2.2. 得到所有的user

private static List getUserList(){
        List userList = new ArrayList();
        if(context == null){
            connectLdap();
        }
        SearchControls ctl = new SearchControls();
        ctl.setSearchScope(SearchControls.SUBTREE_SCOPE);
        try{
            NamingEnumeration en = context.search(DN, "(&(&(objectClass=user)(objectClass=organizationalPerson))(!(objectClass=computer)))", ctl);
            while ((en != null) && (en.hasMoreElements())){
                Object obj = en.nextElement();
                if( obj instanceof SearchResult)
                {
                    SearchResult result = (SearchResult)obj;
                    Attributes attrs = result.getAttributes();
                    if(attrs == null)
                    {
                        System.out.println("No containers");
                    }
                    else {
                        userList.add((String) attrs.get("cn").get(0));
                    }
                }
            }
        }catch (NamingException e){
            e.printStackTrace();
        }
        return userList;
    }

2.3. 创建container

public static void addContainer(String cn){
        if(context == null){
            connectLdap();
        }
        String userDN = "cn=" + cn + "," + baseDN;
        if(!isContainerExist(cn)){
            Attributes attrs = new BasicAttributes();
            attrs = addContainerObjectClass(attrs); //私有的功能函数,文章后面会有,填写必要的objectClass
            try{
                context.createSubcontext(userDN, attrs);
                System.out.println(cn + " is created successfully");
            }catch (NamingException e){
                e.printStackTrace();
            }
        }else{
            System.out.println("container已经存在");
            return;
        }
    }

2.4. 创建User

public static void createUserInContainerAsSlave(String cn){
        List userList = new ArrayList();
//批量产生用户并创建
        userList.add(cn + ".dn");
        userList.add(cn + ".hbase");
        userList.add(cn + ".http");
        userList.add(cn + ".nm");
        if(context == null){
            connectLdap();
        }
        for(String user: userList) {
            if (!isUserExist(user)) {
                Attributes attrs = getCommonUserAttributes(user); //功能函数,填写用户必要的属性
                attrs = addUserObjectClass(attrs); //功能函数,填写必要的objectClass
                try {
                    String userDN = "cn=" + user + ",cn=" + cn + "," + baseDN;
                    context.createSubcontext(userDN, attrs);
                    System.out.println("OK");
                } catch (NamingException e) {
                    e.printStackTrace();
                }
            }else{
                System.out.println("用户已经存在");
                return ;
            }
        }
    }

功能函数:

/**
     * 判断这个container是否存在
     * @param cn
     * @return
     */
    private static boolean isContainerExist(String cn){
        List list = getContainerList();
        if(list.contains(cn)){
            return true;
        }else{
            return false;
        }
    }

/**
     * 判断一个用户是否存在
     * @param cn
     * @return
     */
    private static boolean isUserExist(String cn){
        List userList = getUserList();
        if(userList.contains(cn)){
            return true;
        }else{
            return false;
        }
    }

private static void putAttribute( Attributes attrs , String attrName , Object attrValue)
    {
        if( attrValue != null && attrValue.toString().length() !=0 )
        {
            Attribute attr = new BasicAttribute(attrName , attrValue);
            attrs.put(attr);
        }
    }

private static Attributes addContainerObjectClass(Attributes attrs){
        Attribute obj = new BasicAttribute("objectClass");
        obj.add("top");
        obj.add("container");
        attrs.put(obj);
        return attrs;
    }

private static Attributes addUserObjectClass(Attributes attrs){
        Attribute obj = new BasicAttribute("objectClass");
        obj.add("top");
        obj.add("person");
        obj.add("organizationalPerson");
        obj.add("user");
        attrs.put(obj);
        return attrs;
    }

private static Attributes getCommonUserAttributes(String cn){
        int UF_PASSWD_NOTREQD = 0x0020;
        int UF_NORMAL_ACCOUNT = 0x0200;
        int UF_PASSWORD_EXPIRED = 0x800000;
        Attributes attrs =new BasicAttributes();
        try {
            putAttribute(attrs, "cn", cn);
            putAttribute(attrs, "unicodePwd", ("\"" + unicodePwd + "\"").getBytes("UTF-16LE"));
            attrs.put(new BasicAttribute("userAccountControl" , Integer.toString(UF_NORMAL_ACCOUNT + UF_PASSWD_NOTREQD + UF_PASSWORD_EXPIRED)));
        }catch(Exception e)
        {
            e.printStackTrace();
        }
        return attrs;
    }

ldap的其他操作其实和这些差不多,例如得到userPrincipalName, distinguishedName之类的属性,就是用NamingEnumerattion这个类是查找,今天没时间了,后续的以后写吧。

你可能感兴趣的:(java)