JAVA 连接LDAP

java.naming.provider.url = ldap://192.168.1.118:389/ou=people,cn=EnterpriseLdap,cn=com,o=lan
java.naming.factory.initial = com.sun.jndi.ldap.LdapCtxFactory
java.naming.authoritative = simple
java.naming.security.principal = cn=admin
java.naming.security.credentials = ldapadmin
#之前写成这样怎么都不行
java.naming.provider.url = ldap://192.168.1.118:389/
java.naming.security.principal = cn=admin,ou=people,cn=EnterpriseLdap,cn=com,o=lan

 由于之前没接触过ladp,不知道DN的一些属性具体含义,没有连接成功

DirContext ctx = null;
try {
	ctx = new InitialDirContext();
	System.out.println("sucess");
} catch (AuthenticationException e) {
	System.out.println("认证失败");
	e.printStackTrace();
} catch (NamingException e){
	System.out.println("连接出错");
	e.printStackTrace();
}

 

NamingEnumeration<SearchResult> en = ctx.search("", "uid=*",constraints);
int i = 0;
while(en!=null&&en.hasMoreElements()){
	SearchResult sr = en.nextElement();
	System.out.println("name:"+ sr.getName());
					
	Attributes attrs = sr.getAttributes();
					
	for(NamingEnumeration attrEnum= attrs.getAll();attrEnum.hasMoreElements();){
		Attribute attr = (Attribute) attrEnum.next();
		String attrId = attr.getID();
		for(NamingEnumeration values = attr.getAll();values.hasMoreElements();){
			Object o = values.nextElement();
			System.out.print(attrId+"=");
			if(o instanceof byte[])
				System.out.println(new String((byte[])o));
			else
				System.out.println(o);
		}
	}
}

 添加和删除就比较简单了

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