import java.util.Hashtable;
import javax.naming.Context;
import javax.naming.NamingException;
import javax.naming.directory.DirContext;
import javax.naming.directory.InitialDirContext;
/**
* @author winter
*
*/
public class Test {
/**
* @param args
*/
public static void main(String[] args) {
// TODO Auto-generated method stub
String userName = "xxxxx"; //使用者名稱稱
String password = "xxxxx"; //密碼
String host = "xxx.xxx.xxx.xxx"; //AD伺服器
String port = "389"; //連接埠
String domain = "@xxx.com"; //郵箱的尾碼名
String url = new String("ldap://" + host + ":" + port);
String user = userName.indexOf(domain) > 0 ? userName : userName + domain;
Hashtable env = new Hashtable();
DirContext ctx;
env.put(Context.SECURITY_AUTHENTICATION, "simple");
env.put(Context.SECURITY_PRINCIPAL, user); //不帶郵箱尾碼名的話,會報錯,具體原因還未探究。高手可以解釋分享。
env.put(Context.SECURITY_CREDENTIALS, password);
env.put(Context.INITIAL_CONTEXT_FACTORY,"com.sun.jndi.ldap.LdapCtxFactory");
env.put(Context.PROVIDER_URL, url);
try {
ctx = new InitialDirContext(env);
ctx.close();
System.out.println("驗證成功!");
} catch (NamingException err) {
err.printStackTrace();
System.out.println("驗證失敗!");
}
}
}
============================================================================== Properties env = new Properties();
String ldapURL = "ldap://" + server + ":" + port;
env.put(Context.INITIAL_CONTEXT_FACTORY, "com.sun.jndi.ldap.LdapCtxFactory");
env.put(Context.SECURITY_AUTHENTICATION, "simple");
env.put(Context.SECURITY_PRINCIPAL, user);
env.put(Context.SECURITY_CREDENTIALS, passwd);
env.put(Context.PROVIDER_URL, ldapURL);
LdapContext ctx = new InitialLdapContext(env,null);
searchCtls.setSearchScope(SearchControls.SUBTREE_SCOPE);
NamingEnumeration results = ctx.search(baseDN, "CN=" + testUser, searchCtls);
while (results.hasMoreElements()) {
SearchResult sr = (SearchResult) results.next();
Attributes attributes = sr.getAttributes();
NamingEnumeration values = attributes.getAll();
while(values.hasMore()){
Attribute attr = (Attribute)values.next();
Enumeration vals = attr.getAll();
while(vals.hasMoreElements()){
Object o = vals.nextElement();
System.out.println(attr.getID()+"--------------"+o.toString());
}
}
}
讀取一個使用者資訊 用cn=* 可以讀取所有的..