Jndi通过LDAP取得AD中用户属性

package test;

import java.util.Hashtable;

import javax.naming.AuthenticationException;
import javax.naming.Context;
import javax.naming.NamingEnumeration;
import javax.naming.NamingException;
import javax.naming.directory.Attribute;
import javax.naming.directory.Attributes;
import javax.naming.directory.DirContext;
import javax.naming.directory.InitialDirContext;

public class TestJndiLdapGetAttrs {
    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@"); 
        //若红色部分注释掉,则报下面错误,不知道具体原因 
        //javax.naming.NamingException: [LDAP: error code 1 - 00000000: LdapErr: DSID-0C0905FF, comment: In order to perform this operation a successful bind must be completed on the connection., data 0, vece 
        DirContext context = null;
        try {
            context = new InitialDirContext(env);
            System.out.println("user check ok");
//            Name name = new LdapName("cn=aa,cn=users,dc=lcl,dc=com");
            String[] strIds = { "name", "cn"};
            Attributes allAttrs = context.getAttributes("cn=aa,cn=users,dc=lcl,dc=com", strIds);
            //Attributes allAttrs = context.getAttributes(name);
            if (null == allAttrs) {
                System.out.println("no attributes");
                return;
            }
            for (NamingEnumeration attrs = allAttrs.getAll(); attrs.hasMore();) {
                Attribute attr = (Attribute) attrs.next();
                System.out.println("attr : " + attr.getID());
                for (NamingEnumeration values = attr.getAll(); values.hasMore();) {
                    System.out.println("\tvalue : " + values.next());
                }
            }
            System.out.println("ok");
        } catch (AuthenticationException e) {
            e.printStackTrace();
        } catch (NamingException e) {
            e.printStackTrace();
        } finally {
            try {
                context.close();
            } catch (NamingException e) {
                e.printStackTrace();
            }
        }
    }
}

 

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