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.Attributes;
import javax.naming.directory.BasicAttribute;
import javax.naming.directory.BasicAttributes;
import javax.naming.directory.DirContext;
import javax.naming.directory.InitialDirContext;
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);
            Attributes matchAttrs = new BasicAttributes(true);

            matchAttrs.put(new BasicAttribute("cn", "aa"));
            matchAttrs.put(new BasicAttribute("name"));

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

            // Search for objects that have those matching attributes
            NamingEnumeration enum = context.search(root, matchAttrs, attrIDs);

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

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