利用LDAP操作AD域

摘要:
LDAP操作代码示例初始化LDAP目录服务上下文。在本例中,我们使用uid=linly,ou=People,dc=jsoso,dc=cnet帐户链接到本地计算机(ldap://localhost:8389),身份验证方法为简单类型,即用户名/密码。privatestaticvoinitialContext()throwsNamingExceptio

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对象为LDAP的Context设置参数,而后初始化InitialDirContext,即可绑定LDAP服务。这相当于JDBC中获取数据库的Connection对象。 

绑定/创建LDAP条目对象
用户可以使用bind方法创建新的LDAP条目,下面的代码创建一个DN:"ou=Employee , dc=jsoso ,dc=net"的OrganizationUnit类LDAP条目如下: 


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,并添加objectclass和cn属性 
    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()的条目中的cn、givenname、sn和userpassword四个属性值。 
(注:参数DirContext.REPLACE_ATTRIBUTE有另外两个常量:DirContext.ADD_ATTRIBUTE;DirContext.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"中搜索它的所有子树中的匹配条目。 
(注:SearchControls的SCOPE参数详见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代码 

1.   private static void initialContext() throws NamingException{   

2.       if(singleton == null){   

3.           singleton = new LDAPConnection();   

4.           /*  

5.            * 在实际编码中,这些环境变量应尽可能通过配置文件读取  

6.            */  

7.           //LDAP服务地址   

8.           singleton.sLDAP_URL = "ldap://localhost:8389";    

9.           //管理员账号   

10.        singleton.sMANAGER_DN = "uid=linly,ou=People,dc=jsoso,dc=net";   

11.        //管理员密码   

12.        singleton.sMANAGER_PASSWORD = "coffee";   

13.        //认证类型   

14.        singleton.sAUTH_TYPE = "simple";   

15.        //JNDI Context工厂类   

16.        singleton.sCONTEXT_FACTORY = "com.sun.jndi.ldap.LdapCtxFactory";    

17.           

18.        singleton.envProps.setProperty(Context.INITIAL_CONTEXT_FACTORY, singleton.sCONTEXT_FACTORY);   

19.        singleton.envProps.setProperty(Context.PROVIDER_URL, singleton.sLDAP_URL);   

20.        singleton.envProps.setProperty(Context.SECURITY_AUTHENTICATION, singleton.sAUTH_TYPE);   

21.        singleton.envProps.setProperty(Context.SECURITY_PRINCIPAL, singleton.sMANAGER_DN);   

22.        singleton.envProps.setProperty(Context.SECURITY_CREDENTIALS, singleton.sMANAGER_PASSWORD);   

23.        /*  

24.         * 绑定ldap服务器  

25.         */  

26.        singleton.dirCtx = new InitialDirContext(singleton.envProps);   

27.    }   

28.}  

免责声明:文章转载自《利用LDAP操作AD域》仅用于学习参考。如对内容有疑问,请及时联系本站处理。

上篇Java探针技术-动态agent机制:在main函数启动之后运行agentmysql 链接失败(ERROR 1045 (28000): Access denied for user 'root'@'localhost' (using password: YES))下篇

宿迁高防,2C2G15M,22元/月;香港BGP,2C5G5M,25元/月 雨云优惠码:MjYwNzM=

相关文章

服务器内部模拟Http请求

前言:   在做小程序的开发时需要获取用户的openId用来做唯一标识,来获取对应用户的相关数据   官方的文档说明上有四个必须传的参数   其中appId和appSecret可在自己的微信公众号平台上获取,同时这些也是属于私密信息,应该妥善保管的,因为微信手机客户端是很容易反编译获取到这些信息的,所以在前端的ajax请求将这些参数传到后台是不可取的,最...

asp.net 调用 excel 组件

Asp.net 如何调用 Excel ? 1.引用 Microsoft.Office.Interop.Excel.dll,自动包装成Interop.Microsoft.Office.Interop.Excel.dll 2.代码: ///<summary> ///生成 excel 报表 ///</summary> privatevoi...

LDAP Browser/Editor v2.8.2

https://www.netiq.com/communities/cool-solutions/wp-content/uploads/sites/2/2009/07/Gawor_ldapbrowser_282.zip https://www.netiq.com/communities/cool-solutions/cool_tools/gawors-exc...

Spring Security 自定义登录认证(二)

一、前言 本篇文章将讲述Spring Security自定义登录认证校验用户名、密码,自定义密码加密方式,以及在前后端分离的情况下认证失败或成功处理返回json格式数据 温馨小提示:Spring Security中有默认的密码加密方式以及登录用户认证校验,但小编这里选择自定义是为了方便以后业务扩展,比如系统默认带一个超级管理员,当认证时识别到是超级管理员账...

Java 设计模式六原则及23中常用设计模式

一、设计模式的分类 总体来说设计模式分为三大类: 创建型模式,共五种:工厂方法模式、抽象工厂模式、单例模式、建造者模式、原型模式。 结构型模式,共七种:适配器模式、装饰器模式、代理模式、外观模式、桥接模式、组合模式、享元模式。 行为型模式,共十一种:策略模式、模板方法模式、观察者模式、迭代子模式、责任链模式、命令模式、备忘录模式、状态模式、访...

.NET Core 常用加密和Hash工具NETCore.Encrypt

https://www.cnblogs.com/piscesLoveCc/p/7423205.html  前言  在日常开发过程中,不可避免的涉及到数据加密解密(Hash)操作,所以就有想法开发通用工具,NETCore.Encrypt就诞生了。目前NETCore.Encrypt只支持.NET Core ,工具包含了AES,DES,RSA加密解密,MD5...