LDAP资料介绍可以参考:http://wenku.baidu.com/view/262742f9f705cc17552709f9.html
ldap访问AD域的的错误一般会如下格式:
Ldap load error: [LDAP: error code 49 - 80090308: LdapErr: DSID-0C090334, comment: AcceptSecurityContext error, data 525, vece]
其中红字部分的意思如下(这些错误码跟语言无关):
525 - 用户没有找到
52e - 证书不正确
530 - not permitted to logon at this time
532 - 密码期满
533 - 帐户不可用
701 - 账户期满
773 - 用户必须重设密码
import java.util.Hashtable; 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.SearchControls; import javax.naming.directory.SearchResult; import javax.naming.ldap.InitialLdapContext; import javax.naming.ldap.LdapContext; public class LdapADHelper { public LdapADHelper() { } private String host,url,adminName,adminPassword; private LdapContext ctx = null; /** * 初始化ldap */ public void initLdap(){ //ad服务器 this.host = "xxx.com"; // AD服务器 this.url = new String("ldap://" + host );//默认端口为80的可以不用填写,其他端口需要填写,如ldap://xxx.com:8080 this.adminName = "admin@xxx.com";// 注意用户名的写法:domain\User 或 User@domain.com this.adminPassword = "admin"; Hashtable HashEnv = new Hashtable(); HashEnv.put(Context.SECURITY_AUTHENTICATION, "simple"); // LDAP访问安全级别 HashEnv.put(Context.SECURITY_PRINCIPAL, adminName); // AD User HashEnv.put(Context.SECURITY_CREDENTIALS, adminPassword); // AD Password HashEnv.put(Context.INITIAL_CONTEXT_FACTORY, "com.sun.jndi.ldap.LdapCtxFactory"); // LDAP工厂类 HashEnv.put(Context.PROVIDER_URL, url); try { ctx = new InitialLdapContext(HashEnv, null); System.out.println("初始化ldap成功!"); } catch (NamingException e) { e.printStackTrace(); System.err.println("Throw Exception : " + e); } } /** * 关闭ldap */ public void closeLdap(){ try { this.ctx.close(); } catch (NamingException e) { // TODO Auto-generated catch block e.printStackTrace(); } } /** * * @param type organizationalUnit:组织架构 group:用户组 user|person:用户 * @param name * @return */ public String GetADInfo(String type ,String filter ,String name) { String userName = name; // 用户名称 if (userName == null) { userName = ""; } String company = ""; String result = ""; try { // 域节点 String searchBase = "DC=xx,DC=xxx,DC=com"; // LDAP搜索过滤器类 //cn=*name*模糊查询 cn=name 精确查询 // String searchFilter = "(objectClass="+type+")"; String searchFilter = "(&(objectClass="+type+")("+filter+"=*" + name + "*))"; // 创建搜索控制器 SearchControls searchCtls = new SearchControls(); // 设置搜索范围 searchCtls.setSearchScope(SearchControls.SUBTREE_SCOPE); // String returnedAtts[] = { "memberOf" }; // 定制返回属性 // searchCtls.setReturningAttributes(returnedAtts); // 设置返回属性集 不设置则返回所有属性 // 根据设置的域节点、过滤器类和搜索控制器搜索LDAP得到结果 NamingEnumeration answer = ctx.search(searchBase, searchFilter,searchCtls);// Search for objects using the filter // 初始化搜索结果数为0 int totalResults = 0;// Specify the attributes to return int rows = 0; while (answer.hasMoreElements()) {// 遍历结果集 SearchResult s