欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  IT编程

JAVA使用Ldap操作AD域的方法示例

程序员文章站 2024-02-23 16:56:40
项目上遇到的需要在集成 操作域用户的信息的功能,第一次接触ad域,因为不了解而且网上其他介绍不明确,比较费时,这里记录下。 说明: (1). 特别注意:java操作查询...

项目上遇到的需要在集成 操作域用户的信息的功能,第一次接触ad域,因为不了解而且网上其他介绍不明确,比较费时,这里记录下。

说明:

(1). 特别注意:java操作查询域用户信息获取到的数据和域管理员在电脑上操作查询的数据可能会存在差异(同一个意思的表示字段,两者可能不同)。

(2). 连接ad域有两个地址: ldap://xxxxx.com:389 和 ldap://xxxxx.com:636(ssl)。

(3). 端口389用于一般的连接,例如登录,查询等非密码操作,端口636安全性较高,用户密码相关操作,例如修改密码等。

(4).  域控可能有多台服务器,之间数据同步不及时,可能会导致已经修改的数据被覆盖掉,这个要么域控缩短同步的时间差,要么同时修改每一台服务器的数据。

1. 389登录

// 只要不抛出异常就是验证通过
public ldapcontext adlogin(jsonobject json) {
    string username = json.getstring("username");
    string password = json.getstring("password");
    string server = "ldap://xxxxxxx.com:389";
    try {
      hashtable<string, string> env = new hashtable<string, string>();
      //用户名称,cn,ou,dc 分别:用户,组,域
      env.put(context.security_principal, username);
      //用户密码 cn 的密码
      env.put(context.security_credentials, password);
      //url 格式:协议://ip:端口/组,域  ,直接连接到域或者组上面
      env.put(context.provider_url, server);
      //ldap 工厂
      env.put(context.initial_context_factory, "com.sun.jndi.ldap.ldapctxfactory");
      //验证的类型   "none", "simple", "strong"
      env.put(context.security_authentication, "simple");
      ldapcontext ldapcontext = new initialldapcontext(env, null);
      log.info("ldapcontext:" + ldapcontext);
      log.info("用户" + username + "登录验证成功");
      return ldapcontext;

    } catch (namingexception e) {
      log.info("用户" + username + "登录验证失败");
      log.info("错误信息:"+e.getexplanation());
      return null;
    }
  }

2. 636登录验证(需要导入证书)

 //证书提前倒入的java库中
// 参考:https://www.cnblogs.com/moonson/p/4454159.html

ldapcontext adloginssl(jsonobject json) {
string username = json.getstring("username");
string password = json.getstring("password");
hashtable env = new hashtable();

string javahome = system.getproperty("java.home");
     string keystore = javahome+"/lib/security/cacerts";
     log.info("java.home,{}",keystore);
    // 加载导入jdk的域证书
     system.setproperty("javax.net.ssl.truststore", keystore);
     system.setproperty("javax.net.ssl.truststorepassword", "changeit");
     string ldap_url = "ldap://xxxxxx.com:636"; // ldap访问地址

     env.put(context.initial_context_factory, "com.sun.jndi.ldap.ldapctxfactory");
     env.put(context.security_protocol, "ssl");//链接认证服务器
     env.put(context.provider_url, ldap_url);
     env.put(context.security_authentication, "simple");
     env.put(context.security_principal, username);
     env.put(context.security_credentials, password);
     try {
       ldapcontext ldapcontext = new initialldapcontext(env, null);
       log.info("认证成功");// 这里可以改成异常抛出。
       return ldapcontext;
     } catch (javax.naming.authenticationexception e) {
       log.info("认证失败:{}",e.getmessage());
     } catch (exception e) {
       log.info("认证出错:{}",e.getmessage());
     }
    return null;
  }

 3. 查询域用户信息

public list getuserkey(jsonobject json){

    jsonobject admin = new jsonobject();
    admin.put("username","aaaaa");
    admin.put("password", "bbbbbbbb");
    string name = json.getstring("name");
    log.info("需要查询的ad信息:{}",name);
    list<jsonobject> resultlist = new jsonarray();
    ldapcontext ldapcontext = adlogin(admin); //连接到域控
    if (ldapcontext!=null){

      string company = "";
      string result = "";
      try {
        // 域节点
        string searchbase = "dc=xxxxxxx,dc=com";
        // ldap搜索过滤器类
        //cn=*name*模糊查询 
         //cn=name 精确查询
          // string searchfilter = "(objectclass="+type+")";
        string searchfilter = "(samaccountname="+name+")";  //查询域帐号

        // 创建搜索控制器
        searchcontrols searchctls = new searchcontrols();
        string returnedatts[]={"description","samaccountname","useraccountcontrol"};    
        searchctls.setreturningattributes(returnedatts); //设置指定返回的字段,不设置则返回全部
        // 设置搜索范围 深度
        searchctls.setsearchscope(searchcontrols.subtree_scope);
        // 根据设置的域节点、过滤器类和搜索控制器搜索ldap得到结果
        namingenumeration answer = ldapcontext.search(searchbase, searchfilter,searchctls); 
        // 初始化搜索结果数为0
        int totalresults = 0; 
        int rows = 0;
        while (answer.hasmoreelements()) {// 遍历结果集
          searchresult sr = (searchresult) answer.next();// 得到符合搜索条件的dn
          ++rows;
          string dn = sr.getname();
          log.info(dn);
          attributes attrs = sr.getattributes();// 得到符合条件的属性集
          if (attrs != null) {
            try {
              for (namingenumeration ne = attrs.getall(); ne.hasmore();) {
                attribute attr = (attribute) ne.next();// 得到下一个属性
                // 读取属性值
                for (namingenumeration e = attr.getall(); e.hasmore(); totalresults++) {
                  company = e.next().tostring();
                  jsonobject tempjson = new jsonobject();

                  tempjson.put(attr.getid(), company.tostring());
                  resultlist.add(tempjson);
                }
              }
            } catch (namingexception e) {
              log.info("throw exception : " + e.getmessage());
            }
          } 
        } 
                log.info("总共用户数:" + rows);
      } catch (namingexception e) {
        log.info("throw exception : " + e.getmessage());
      }finally {
        try{
          ldapcontext.close();
        }catch (exception e){
          e.printstacktrace();
        }
      }
    }
    return resultlist;
  }

4. 重置用户密码

// 管理员重置用户密码,后强制用户首次登录修改密码
public map<string, string> updateadpwd(jsonobject json) {
    string dn = json.getstring("dn");//要修改的帐号(这个dn是查询的用户信息里的dn的值,而不是域账号)
    string password = json.getstring("password");//新密码

    jsonobject admin = new jsonobject();
    admin.put("username","aaaaaaa");
    admin.put("password", "bbbbbbb");
    map<string,string> map = new hashmap<string,string>();
    ldapcontext ldapcontext = adloginssl(admin); //连接636端口域
    modificationitem[] mods = new modificationitem[2];
    if (ldapcontext!=null){
      try {
        string newquotedpassword = "\"" + password + "\"";
        byte[] newunicodepassword = newquotedpassword.getbytes("utf-16le");
// unicodepwd:修改的字段,newunicodepassword:修改的值
        mods[0] = new modificationitem(dircontext.replace_attribute,
            new basicattribute("unicodepwd", newunicodepassword));
mods[1] = new modificationitem(dircontext.replace_attribute,
            new basicattribute("pwdlastset", "0")); // 首次登录必须修改密码


        // 修改密码
        ldapcontext.modifyattributes(dn, mods); 
        map.put("result", "s");
        map.put("message","成功");
      }catch (exception e){ 
        map.put("result","e");
        map.put("message", "无法重置密码");
      }finally {
        try{
          ldapcontext.close();
        }catch (exception e){
          e.printstacktrace();
        }

      }

    }else {
      log.info("");
      map.put("result","e");
      map.put("message", "验证失败");
    }


    return map;
  }

5. 域账号解锁

// 表示锁定的字段需要测试,不一定这个lockouttime
public map<string, string> deblocking(jsonobject json) {
  jsonobject admin = new jsonobject();
  string dn = json.getstring("dn"); //被解锁的帐号(这个dn指的是查询用户信息里的dn的值,不是域账号)
  admin.put("username","aaaaaa");
  admin.put("password","bbbbbb");
  map<string,string> map = new hashmap<string,string>();
  ldapcontext ldapcontext = adlogin(admin);
  modificationitem[] mods = new modificationitem[1];
  if (ldapcontext!=null){
    try {
      // "0" 表示未锁定,不为0表示锁定
      mods[0] = new modificationitem(dircontext.replace_attribute,
          new basicattribute("lockouttime","0"));
      // 解锁域帐号
      ldapcontext.modifyattributes(dn, mods); 
      map.put("result", "s");
      map.put("message","成功");
    }catch (exception e){ 
      map.put("result","e");
      map.put("message", "解锁失败");
    }finally {
      try{
        ldapcontext.close();
      }catch (exception e){
        e.printstacktrace();
      }

    }

  }else {
    map.put("result","e");
    map.put("message", "验证失败");
  }
  return map;
}

java通过ldap操作ad的增删改查询

package com.smnpc.util;
 
import java.util.hashtable;
import java.util.vector;
 
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.basicattribute;
import javax.naming.directory.basicattributes;
import javax.naming.directory.dircontext;
import javax.naming.directory.initialdircontext;
import javax.naming.directory.modificationitem;
import javax.naming.directory.searchcontrols;
import javax.naming.directory.searchresult;
import javax.naming.ldap.ldapcontext;
 
/**
* java通过ldap操作ad的增删该查询
* @author guob
*/
 
public class ldapbyuser {
dircontext dc = null;
string root = "dc=example,dc=com"; // ldap的根节点的dc
 
/**
* 
* @param dn类似于"cn=ryanhanson,dc=example,dc=com"
* @param employeeid是ad的一个员工号属性
*/
public ldapbyuser(string dn,string employeeid) {
init();
// add();//添加节点
// delete("ou=hi,dc=example,dc=com");//删除"ou=hi,dc=example,dc=com"节点
// renameentry("ou=new,o=neworganization,dc=example,dc=com","ou=neworganizationalunit,o=neworganization,dc=example,dc=com");//重命名节点"ou=new,o=neworganization,dc=example,dc=com"
// searchinformation("dc=example,dc=com", "", "samaccountname=guob");//遍历所有根节点
modifyinformation(dn,employeeid);//修改
// ldapbyuserinfo("guob");//遍历指定节点的分节点
close();
}
 
/**
* 
* ldap连接
* 
* @return ldapcontext
*/
public void init() {
hashtable env = new hashtable();
string ldap_url = "ldap://xxxx:389"; // ldap访问地址
string adminname = "example\\user"; // 注意用户名的写法:domain\user或
string adminpassword = "userpassword"; // 密码
env.put(context.initial_context_factory,
"com.sun.jndi.ldap.ldapctxfactory");
env.put(context.provider_url, ldap_url);
env.put(context.security_authentication, "simple");
env.put(context.security_principal, adminname);
env.put(context.security_credentials, adminpassword);
try {
dc = new initialdircontext(env);// 初始化上下文
system.out.println("认证成功");// 这里可以改成异常抛出。
} catch (javax.naming.authenticationexception e) {
system.out.println("认证失败");
} catch (exception e) {
system.out.println("认证出错:" + e);
}
}
 
/**
* 添加
*/
public void add(string newusername) {
try {
basicattributes attrs = new basicattributes();
basicattribute objclassset = new basicattribute("objectclass");
objclassset.add("samaccountname");
objclassset.add("employeeid");
attrs.put(objclassset);
attrs.put("ou", newusername);
dc.createsubcontext("ou=" + newusername + "," + root, attrs);
} catch (exception e) {
e.printstacktrace();
system.out.println("exception in add():" + e);
}
}
 
/**
* 删除
* 
* @param dn
*/
public void delete(string dn) {
try {
dc.destroysubcontext(dn);
} catch (exception e) {
e.printstacktrace();
system.out.println("exception in delete():" + e);
}
}
 
/**
* 重命名节点
* 
* @param olddn
* @param newdn
* @return
*/
public boolean renameentry(string olddn, string newdn) {
try {
dc.rename(olddn, newdn);
return true;
} catch (namingexception ne) {
system.err.println("error: " + ne.getmessage());
return false;
}
}
 
/**
* 修改
* 
* @return
*/
public boolean modifyinformation(string dn,string employeeid) {
try {
system.out.println("updating...\n");
modificationitem[] mods = new modificationitem[1];
/* 修改属性 */
// attribute attr0 = new basicattribute("employeeid", "w20110972");
// mods[0] = new modificationitem(dircontext.replace_attribute, attr0);
 
/* 删除属性 */
// attribute attr0 = new basicattribute("description",
// "陈轶");
// mods[0] = new modificationitem(dircontext.remove_attribute,
// attr0);
 
/* 添加属性 */
attribute attr0 = new basicattribute("employeeid",employeeid);
mods[0] = new modificationitem(dircontext.add_attribute, attr0);
/* 修改属性 */
dc.modifyattributes(dn+",dc=example,dc=com", mods);
return true;
} catch (namingexception e) {
e.printstacktrace();
system.err.println("error: " + e.getmessage());
return false;
}
}
 
/**
* 关闭ldap连接
*/
public void close() {
if (dc != null) {
try {
dc.close();
} catch (namingexception e) {
system.out.println("namingexception in close():" + e);
}
}
}
 
/**
* @param base :根节点(在这里是"dc=example,dc=com")
* @param scope :搜索范围,分为"base"(本节点),"one"(单层),""(遍历)
* @param filter :指定子节点(格式为"(objectclass=*)",*是指全部,你也可以指定某一特定类型的树节点)
*/
public void searchinformation(string base, string scope, string filter) {
searchcontrols sc = new searchcontrols();
if (scope.equals("base")) {
sc.setsearchscope(searchcontrols.object_scope);
} else if (scope.equals("one")) {
sc.setsearchscope(searchcontrols.onelevel_scope);
} else {
sc.setsearchscope(searchcontrols.subtree_scope);
}
namingenumeration ne = null;
try {
ne = dc.search(base, filter, sc);
// use the namingenumeration object to cycle through
// the result set.
while (ne.hasmore()) {
system.out.println();
searchresult sr = (searchresult) ne.next();
string name = sr.getname();
if (base != null && !base.equals("")) {
system.out.println("entry: " + name + "," + base);
} else {
system.out.println("entry: " + name);
}
 
attributes at = sr.getattributes();
namingenumeration ane = at.getall();
while (ane.hasmore()) {
attribute attr = (attribute) ane.next();
string attrtype = attr.getid();
namingenumeration values = attr.getall();
vector vals = new vector();
// another namingenumeration object, this time
// to iterate through attribute values.
while (values.hasmore()) {
object oneval = values.nextelement();
if (oneval instanceof string) {
system.out.println(attrtype + ": " + (string) oneval);
} else {
system.out.println(attrtype + ": " + new string((byte[]) oneval));
}
}
}
}
} catch (exception nex) {
system.err.println("error: " + nex.getmessage());
nex.printstacktrace();
}
}
/**
* 查询
* 
* @throws namingexception
*/
public void ldapbyuserinfo(string username) {
// create the search controls
searchcontrols searchctls = new searchcontrols();
// specify the search scope
searchctls.setsearchscope(searchcontrols.subtree_scope);
// specify the ldap search filter
string searchfilter = "samaccountname=" + username;
// specify the base for the search 搜索域节点
string searchbase = "dc=example,dc=com";
int totalresults = 0;
string returnedatts[] = { "url", "whenchanged", "employeeid", "name",
"userprincipalname", "physicaldeliveryofficename",
"departmentnumber", "telephonenumber", "homephone", "mobile",
"department", "samaccountname", "whenchanged", "mail" }; // 定制返回属性
 
searchctls.setreturningattributes(returnedatts); // 设置返回属性集
 
// searchctls.setreturningattributes(null); // 不定制属性,将返回所有的属性集
 
try {
namingenumeration answer = dc.search(searchbase, searchfilter,
searchctls);
if (answer == null || answer.equals(null)) {
system.out.println("answer is null");
} else {
system.out.println("answer not null");
}
while (answer.hasmoreelements()) {
searchresult sr = (searchresult) answer.next();
system.out
.println("************************************************");
system.out.println("getname=" + sr.getname());
attributes attrs = sr.getattributes();
if (attrs != null) {
try {
 
for (namingenumeration ne = attrs.getall(); ne
.hasmore();) {
attribute attr = (attribute) ne.next();
system.out.println("attributeid="
+ attr.getid().tostring());
// 读取属性值
for (namingenumeration e = attr.getall(); e
.hasmore(); totalresults++) {
string user = e.next().tostring(); // 接受循环遍历读取的userprincipalname用户属性
system.out.println(user);
}
// system.out.println(" ---------------");
// // 读取属性值
// enumeration values = attr.getall();
// if (values != null) { // 迭代
// while (values.hasmoreelements()) {
// system.out.println(" 2attributevalues="
// + values.nextelement());
// }
// }
// system.out.println(" ---------------");
}
} catch (namingexception e) {
system.err.println("throw exception : " + e);
}
}
}
system.out.println("number: " + totalresults);
} catch (exception e) {
e.printstacktrace();
system.err.println("throw exception : " + e);
}
}
 
/**
* 主函数用于测试
* @param args
*/
public static void main(string[] args) {
new ldapbyuser("cn=ryanhanson","bbs.it-home.org");
}
}

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持。