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. }  



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