Jndi通过LDAP从AD执行基本search

package test;

import java.util.Hashtable;
import javax.naming.Context;
import javax.naming.NamingEnumeration;
import javax.naming.NamingException;
import javax.naming.directory.DirContext;
import javax.naming.directory.InitialDirContext;
import javax.naming.directory.SearchControls;
import javax.naming.directory.SearchResult;

public class TestJndiLdapSearch {
    public static void main(String[] args) {
        Hashtable env = new Hashtable();
        env.put(Context.INITIAL_CONTEXT_FACTORY, "com.sun.jndi.ldap.LdapCtxFactory");
        env.put(Context.PROVIDER_URL, "ldap://192.168.0.23:389");
        env.put(Context.SECURITY_AUTHENTICATION, "simple");
        env.put(Context.SECURITY_PRINCIPAL, "cn=administrator,cn=users,dc=lcl,dc=com");
        env.put(Context.SECURITY_CREDENTIALS, "1234abcd@");
        String root = "cn=users,dc=lcl,dc=com";
        try {
            DirContext context = new InitialDirContext(env);

            // 使用方式见jdk1.6的InitialDirContext的search
            // Specify the ids of the attributes to return
            String[] attrIDs = { "sn", "telephonenumber", "name", "mail" };

            // Create the default search controls
            SearchControls ctls = new SearchControls();
            ctls.setReturningAttributes(attrIDs);
            ctls.setSearchScope(SearchControls.SUBTREE_SCOPE);

            String filter = "(&(cn=*))";
            // Search for objects that have those matching attributes
            NamingEnumeration enum = context.search(root, filter, ctls);

            while (enum.hasMore()) {
                SearchResult result = (SearchResult) enum.next();
                System.out.println("name : " + result.getName());
            }
        } catch (NamingException e) {
            e.printStackTrace();
        }
    }
}

 

你可能感兴趣的:(Security,sun)