通過LDAP在AD域控上進行添加、刪除、修改、查詢等各種操作。


LDAP操作代碼樣例  初始化LDAP 目錄服務上下文
該例子中,我們使用uid=linly,ou=People,dc=jsoso,dc=net這個賬號,鏈接位於本機8389端口的LDAP服務器(ldap://localhost:8389),認證方式采用simple類型,即用戶名/密碼方式。

private static void initialContext() throws NamingException{
   if(singleton == null){
    singleton = new LDAPConnection();
    /*
    *
在實際編碼中,這些環境變量應盡可能通過配置文件讀取
    */
    //LDAP
服務地址
    singleton.sLDAP_URL = "ldap://localhost:8389";
    //
管理員賬號
    singleton.sMANAGER_DN = "uid=linly,ou=People,dc=jsoso,dc=net";
    //
管理員密碼
    singleton.sMANAGER_PASSWORD = "coffee";
    //
認證類型
    singleton.sAUTH_TYPE = "simple";
    //JNDI Context
工廠類
    singleton.sCONTEXT_FACTORY = "com.sun.jndi.ldap.LdapCtxFactory";
  
    singleton.envProps.setProperty(Context.INITIAL_CONTEXT_FACTORY, singleton.sCONTEXT_FACTORY);
    singleton.envProps.setProperty(Context.PROVIDER_URL, singleton.sLDAP_URL);
    singleton.envProps.setProperty(Context.SECURITY_AUTHENTICATION, singleton.sAUTH_TYPE);
    singleton.envProps.setProperty(Context.SECURITY_PRINCIPAL, singleton.sMANAGER_DN);
    singleton.envProps.setProperty(Context.SECURITY_CREDENTIALS, singleton.sMANAGER_PASSWORD);
    /*
    *
綁定ldap服務器
    */
    singleton.dirCtx = new InitialDirContext(singleton.envProps);
   }
}

通過一個Hashtable或者Properties對象為LDAPContext設置參數,而后初始化InitialDirContext,即可綁定LDAP服務。這相當於JDBC中獲取數據庫的Connection對象。

綁定/創建LDAP條目對象
用戶可以使用bind方法創建新的LDAP條目,下面的代碼創建一個DN"ou=Employee , dc=jsoso ,dc=net"OrganizationUnitLDAP條目如下:


public boolean createOrganizationUnit(){
   String ldapGroupDN = "ou=Employee , dc=jsoso ,dc=net";
   try {
    /*
    *
查找是否已經存在指定的OU條目
    *
如果存在,則打印OU條目的屬性信息
    *
如果不存在,則程序會拋出NamingException異常,進入異常處理
    */
    Attributes attrs = dirContext.getAttributes(ldapGroupDN);
    System.out.println("Find the group , attributes list :");
    NamingEnumeration<String> nEnum = attrs.getIDs();  
    for( ; nEnum.hasMore() ; ){
     String attrID = nEnum.next();
     Attribute attr = (Attribute)attrs.get(attrID);
     System.out.println(attr.toString());
    }  
    return false;
   } catch (NamingException e) {
    /*
    *
沒有找到對應的Group條目,新增Group條目
    */
    //
創建objectclass屬性
    Attribute objclass = new BasicAttribute("objectclass");
    objclass.add("top");
    objclass.add("organizationalunit");
    //
創建cn屬性
    Attribute cn = new BasicAttribute("ou", "Employee");
    //
創建Attributes,並添加objectclasscn屬性
    Attributes attrs = new BasicAttributes();
    attrs.put(objclass);
    attrs.put(cn);
    //
將屬性綁定到新的條目上,創建該條目
    try {
     dirContext.bind(ldapGroupDN, null, attrs);
     System.out.println("Group created successful");
     return true;
    } catch (NamingException e1) {
     e1.printStackTrace();
    }   
   }
   return false;
}



獲取條目屬性
下面一段代碼獲取entryDN參數指定條目中的屬性集合,並打印到控制台

/**
*
獲取一個指定的LDAP Entry
* @param entryDN
*/
public void find(String entryDN){
   try {
    Attributes attrs = dirContext.getAttributes(entryDN);
    if (attrs != null) {
     NamingEnumeration<String> nEnum = attrs.getIDs();
     for( ; nEnum.hasMore() ; ){
      String attrID = nEnum.next();
      Attribute attr = (Attribute)attrs.get(attrID);
      System.out.println(attr.toString());
     }
     System.out.println();
    }else{
     System.out.println("No found binding.");
    }
   }catch(NamingException ne) {
    ne.printStackTrace();
   }
}

修改條目屬性
修改DN=user.getDistinguishedName()的條目中的cngivennamesnuserpassword四個屬性值。
(注:參數DirContext.REPLACE_ATTRIBUTE有另外兩個常量:DirContext.ADD_ATTRIBUTEDirContext.REMOVE_ATTRIBUTE,分別表示新增屬性和刪除屬性。)

/**
*
修改用戶信息
* @param user
* @return
* @throws Exception
*/
public boolean modifyUser(LDAPUser user) throws Exception {
   //
用戶對象為空
   if (user == null) {
    throw new Exception("No user information!n");
   }

   //
檢查uid
   String userDN = user.getDistinguishedName();
   if (userDN == null && userDN.length() == 0) {
    throw new NamingException("No userDN you specify!n");
   }

   //
判斷用戶條目是否已經存在
   if(!isUserexist(userDN)){
    return false;
   }
 
   //
設置屬性
   Attributes attrs = new BasicAttributes();
   setBasicAttribute(attrs, "cn", user.getCommomName());
   setBasicAttribute(attrs, "givenname", user.getFirstName());
   setBasicAttribute(attrs, "sn", user.getLastName());
   setBasicAttribute(attrs, "userpassword", user.getPassword());
   //
修改屬性
   try{
    dirContext.modifyAttributes(user.getDistinguishedName(),DirContext.REPLACE_ATTRIBUTE, attrs);
    System.out.println("User(" + user.getDistinguishedName() + ") information modified.n");
    return true;
   }catch(NamingException ne){
    ne.printStackTrace();
   }
   return false;
}




根據屬性集搜索條目
根據屬性集matchingAttributes中的匹配值,在上下文DN= "ou=People,dc=jsoso ,dc=net"中搜索它的所有子樹中的匹配條目。
(注:SearchControlsSCOPE參數詳見SearchControls SCOPE補充說明)

          /**
*
通過屬性搜索LDAP范例
* @return
*/
public void searchByAttribute(Attributes matchingAttributes){
   String baseDN = "ou=People,dc=jsoso ,dc=net";
   SearchControls cons = new SearchControls();
   cons.setSearchScope(SearchControls.SUBTREE_SCOPE);
   try {
    Name baseName = new LdapName(baseDN);
    NamingEnumeration<SearchResult> ne = dirContext.search(baseName, matchingAttributes);
    SearchResult entry = null;
    for(;ne.hasMore();){
     entry = ne.next();
     showEntry(entry);
    }    
   } catch (NamingException e) {
    e.printStackTrace();
   }
}

根據過濾器搜索條目
根據過濾器條件,在上下文DN = "ou=People,dc=jsoso ,dc=net"中,搜索它的所有子樹中的匹配條目。
(注:過濾器filter的相關語法詳見LDAP filter語法補充說明)

/**
*
通過過濾器搜索LDAP范例
* @return
*/
public void searchByFilter(String filter){
   String baseDN = "ou=People,dc=jsoso ,dc=net";  
   SearchControls cons = new SearchControls();
   cons.setSearchScope(SearchControls.SUBTREE_SCOPE);
   try {
    NamingEnumeration<SearchResult> ne = dirContext.search(baseDN, filter , cons);
    SearchResult entry = null;
    for(;ne.hasMore();){
     entry = ne.next();
     showEntry(entry);
    }    
   } catch (NamingException e) {
    e.printStackTrace();
   } 

 

這里的內容是抄錄別人的,自己寫的沒有別人寫的這份全。這里的增加用戶,增加組織單元,查找用戶都經過了我的驗證,沒有問題。但是修改我沒有驗證通過。

刪除沒有做,但是從API上看,是沒有問題的。 詳細內容可以去百度文庫搜:LDAP實用資料收錄3.doc 。

該例子中,我們使用uid=linly,ou=People,dc=jsoso,dc=net這個賬號,鏈接位於本機8389端口的LDAP服務器(ldap://localhost:8389),認證方式采用simple類型,即用戶名/密碼方式。

Java代碼 <!--[if !vml]-->復制代碼<!--[endif]-->

<!--[if !supportLists]-->1.   <!--[endif]-->private static void initialContext() throws NamingException{   

<!--[if !supportLists]-->2.   <!--[endif]-->    if(singleton == null){   

<!--[if !supportLists]-->3.   <!--[endif]-->        singleton = new LDAPConnection();   

<!--[if !supportLists]-->4.   <!--[endif]-->        /*  

<!--[if !supportLists]-->5.   <!--[endif]-->         * 在實際編碼中,這些環境變量應盡可能通過配置文件讀取  

<!--[if !supportLists]-->6.   <!--[endif]-->         */  

<!--[if !supportLists]-->7.   <!--[endif]-->        //LDAP服務地址   

<!--[if !supportLists]-->8.   <!--[endif]-->        singleton.sLDAP_URL = "ldap://localhost:8389";    

<!--[if !supportLists]-->9.   <!--[endif]-->        //管理員賬號   

<!--[if !supportLists]-->10.<!--[endif]-->        singleton.sMANAGER_DN = "uid=linly,ou=People,dc=jsoso,dc=net";   

<!--[if !supportLists]-->11.<!--[endif]-->        //管理員密碼   

<!--[if !supportLists]-->12.<!--[endif]-->        singleton.sMANAGER_PASSWORD = "coffee";   

<!--[if !supportLists]-->13.<!--[endif]-->        //認證類型   

<!--[if !supportLists]-->14.<!--[endif]-->        singleton.sAUTH_TYPE = "simple";   

<!--[if !supportLists]-->15.<!--[endif]-->        //JNDI Context工廠類   

<!--[if !supportLists]-->16.<!--[endif]-->        singleton.sCONTEXT_FACTORY = "com.sun.jndi.ldap.LdapCtxFactory";    

<!--[if !supportLists]-->17.<!--[endif]-->           

<!--[if !supportLists]-->18.<!--[endif]-->        singleton.envProps.setProperty(Context.INITIAL_CONTEXT_FACTORY, singleton.sCONTEXT_FACTORY);   

<!--[if !supportLists]-->19.<!--[endif]-->        singleton.envProps.setProperty(Context.PROVIDER_URL, singleton.sLDAP_URL);   

<!--[if !supportLists]-->20.<!--[endif]-->        singleton.envProps.setProperty(Context.SECURITY_AUTHENTICATION, singleton.sAUTH_TYPE);   

<!--[if !supportLists]-->21.<!--[endif]-->        singleton.envProps.setProperty(Context.SECURITY_PRINCIPAL, singleton.sMANAGER_DN);   

<!--[if !supportLists]-->22.<!--[endif]-->        singleton.envProps.setProperty(Context.SECURITY_CREDENTIALS, singleton.sMANAGER_PASSWORD);   

<!--[if !supportLists]-->23.<!--[endif]-->        /*  

<!--[if !supportLists]-->24.<!--[endif]-->         * 綁定ldap服務器  

<!--[if !supportLists]-->25.<!--[endif]-->         */  

<!--[if !supportLists]-->26.<!--[endif]-->        singleton.dirCtx = new InitialDirContext(singleton.envProps);   

<!--[if !supportLists]-->27.<!--[endif]-->    }   

<!--[if !supportLists]-->28.<!--[endif]-->}  


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM