LDAP方式连接AD获取用户信息

DAP资料介绍可以参考: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 - 用户必须重设密码

Java代码  收藏代码
  1. import java.util.Hashtable;  

  2. import javax.naming.Context;  

  3. import javax.naming.NamingEnumeration;  

  4. import javax.naming.NamingException;  

  5. import javax.naming.directory.Attribute;  

  6. import javax.naming.directory.Attributes;  

  7. import javax.naming.directory.SearchControls;  

  8. import javax.naming.directory.SearchResult;  

  9. import javax.naming.ldap.InitialLdapContext;  

  10. import javax.naming.ldap.LdapContext;  

  11. publicclass LdapADHelper {  

  12. public LdapADHelper() {  

  13.    }  

  14. private String host,url,adminName,adminPassword;  

  15. private LdapContext ctx = null;  

  16. /**

  17.     * 初始化ldap

  18.     */

  19. publicvoid initLdap(){  

  20. //ad服务器

  21. this.host = "xxx.com"; // AD服务器

  22. this.url = new String("ldap://" + host );//默认端口为80的可以不用填写,其他端口需要填写,如ldap://xxx.com:8080

  23. this.adminName = "[email protected]";// 注意用户名的写法:domain\User 或  [email protected]

  24. this.adminPassword = "admin";            

  25.        Hashtable HashEnv = new Hashtable();  

  26.        HashEnv.put(Context.SECURITY_AUTHENTICATION, "simple"); // LDAP访问安全级别

  27.        HashEnv.put(Context.SECURITY_PRINCIPAL, adminName); // AD User

  28.        HashEnv.put(Context.SECURITY_CREDENTIALS, adminPassword); // AD Password

  29.        HashEnv.put(Context.INITIAL_CONTEXT_FACTORY, "com.sun.jndi.ldap.LdapCtxFactory"); // LDAP工厂类

  30.        HashEnv.put(Context.PROVIDER_URL, url);  

  31. try {  

  32.             ctx = new InitialLdapContext(HashEnv, null);  

  33.             System.out.println("初始化ldap成功!");  

  34.        } catch (NamingException e) {  

  35.            e.printStackTrace();  

  36.            System.err.println("Throw Exception : " + e);  

  37.        }  

  38.    }  

  39. /**

  40.     * 关闭ldap

  41.     */

  42. publicvoid closeLdap(){  

  43. try {  

  44. this.ctx.close();  

  45.        } catch (NamingException e) {  

  46. // TODO Auto-generated catch block

  47.            e.printStackTrace();  

  48.        }  

  49.    }  

  50. /**

  51.     *

  52.     * @param type organizationalUnit:组织架构 group:用户组 user|person:用户

  53.     * @param name

  54.     * @return

  55.     */

  56. public String GetADInfo(String type ,String filter ,String name) {  

  57.        String userName = name; // 用户名称

  58. if (userName == null) {  

  59.            userName = "";  

  60.        }  

  61.        String company = "";  

  62.        String result = "";  

  63. try {  

  64. // 域节点

  65.            String searchBase = "DC=xx,DC=xxx,DC=com";  

  66. // LDAP搜索过滤器类

  67. //cn=*name*模糊查询 cn=name 精确查询

  68. //          String searchFilter = "(objectClass="+type+")";

  69.            String searchFilter = "(&(objectClass="+type+")("+filter+"=*" + name + "*))";  

  70. // 创建搜索控制器

  71.            SearchControls searchCtls = new SearchControls();  

  72. //  设置搜索范围

  73.            searchCtls.setSearchScope(SearchControls.SUBTREE_SCOPE);  

  74. //          String returnedAtts[] = {  "memberOf" }; // 定制返回属性

  75. //      searchCtls.setReturningAttributes(returnedAtts); // 设置返回属性集 不设置则返回所有属性

  76. // 根据设置的域节点、过滤器类和搜索控制器搜索LDAP得到结果

  77.            NamingEnumeration answer = ctx.search(searchBase, searchFilter,searchCtls);// Search for objects using the filter

  78. // 初始化搜索结果数为0

  79. int totalResults = 0;// Specify the attributes to return

  80. int rows = 0;  

  81. while (answer.hasMoreElements()) {// 遍历结果集

  82.                SearchResult sr = (SearchResult) answer.next();// 得到符合搜索条件的DN

  83.                ++rows;  

  84.                String dn = sr.getName();  

  85.                System.out.println(dn);  

  86.                Attributes Attrs = sr.getAttributes();// 得到符合条件的属性集

  87. if (Attrs != null) {  

  88. try {  

  89. for (NamingEnumeration ne = Attrs.getAll(); ne.hasMore();) {  

  90.                            Attribute Attr = (Attribute) ne.next();// 得到下一个属性

  91.                            System.out.println(" AttributeID=属性名:"+ Attr.getID().toString());  

  92. // 读取属性值

  93. for (NamingEnumeration e = Attr.getAll(); e.hasMore(); totalResults++) {  

  94.                                company = e.next().toString();  

  95.                                System.out.println("    AttributeValues=属性值:"+ company);  

  96.                            }  

  97.                            System.out.println("    ---------------");  

  98.                        }  

  99.                    } catch (NamingException e) {  

  100.                        System.err.println("Throw Exception : " + e);  

  101.                    }  

  102.                }// if

  103.            }// while

  104.            System.out.println("************************************************");  

  105.            System.out.println("Number: " + totalResults);  

  106.            System.out.println("总共用户数:"+rows);  

  107.        } catch (NamingException e) {  

  108.            e.printStackTrace();  

  109.            System.err.println("Throw Exception : " + e);  

  110.        }  

  111. return result;  

  112.    }  

  113. publicstaticvoid main(String args[]) {  

  114. // 实例化

  115.        LdapADHelper ad = new LdapADHelper();  

  116.        ad.initLdap();  

  117.    ad.GetADInfo("user","cn","李XX");//查找用户

  118.        ad.GetADInfo("organizationalUnit","ou","工程");//查找组织架构

  119.    ad.GetADInfo("group","cn","福建xxx");//查找用户组

  120.        ad.closeLdap();  

  121.    }  

  122. }  



發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章