java AD域连接测试及获取所有用户信息(可去掉禁用账户)

java AD域连接测试及获取所有用户信息(可去掉禁用账户)

(AD域测试需要自己拼接ip 端口 账号 密码等内容,然后获取AD域上账户信息,拿到自己想要的数据)
postman自测OK
在这里插入图片描述代码以下:

   /**
     * 测试连接
     *
     * @param request
     * @return
     */
    @PostMapping(value = "/test")
    @ResponseBody
    @ApiOperation("测试连接")
    @ControllerLog(description = "测试连接")
    public ResponseResult test(@RequestBody Map<String, Object> request) {
        return externalConfigService.testConnection(request);
    }
  @Override
    public ResponseResult testConnection(Map<String, Object> request) {
        boolean testConnect = ADUtil.testConnect(request);
        return ResponseResult.general(200, testConnect ? "测试连接成功" : "测试连接失败", testConnect ? "YES" : "NO");
    }
@Override
    public ResponseResult testConnection(Map<String, Object> request) {
        boolean testConnect = ADUtil.testConnect(request);
        return ResponseResult.general(200, testConnect ? "测试连接成功" : "测试连接失败", testConnect ? "YES" : "NO");
    }
import com.alibaba.fastjson.JSONObject;
import com.model.AdDepartment;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

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.SearchControls;
import javax.naming.directory.SearchResult;
import javax.naming.ldap.InitialLdapContext;
import javax.naming.ldap.LdapContext;
import java.util.Hashtable;
import java.util.Map;
import java.util.Properties;
import java.util.TreeSet;

public class ADUtil {
    private static Logger LOG = LoggerFactory.getLogger(ADUtil.class);

    public static NamingEnumeration<SearchResult> getSearchResult(LdapContext ctx, String searchFilter, String searchBase) throws NamingException {
        //搜索控制器
        SearchControls searchCtls = new SearchControls();
        //创建搜索控制器
        searchCtls.setSearchScope(SearchControls.SUBTREE_SCOPE);
        String returnedAtts[] = {"canonicalName", "distinguishedName", "id",
                "name", "userPrincipalName", "departmentNumber", "telephoneNumber", "homePhone",
                "mobile", "department", "sAMAccountName", "whenChanged", "user", "userAccountControl"}; // 定制返回属性
        searchCtls.setReturningAttributes(returnedAtts);
        NamingEnumeration<SearchResult> answer = ctx.search(searchBase, searchFilter, searchCtls);
        return answer;
    }

    // 连接ad域
    public static LdapContext getContext(Properties env) throws NamingException {
        LdapContext ctx = new InitialLdapContext(env, null);
        return ctx;
    }

    public static String getTreeAdDepartment(Properties env, String domain, String searchBase) {
        LdapContext ctx;
        String result = "";
        try {
            ctx = getContext(env);
            TreeSet<AdDepartment> as = getAdDepartment(ctx, searchBase);
            System.out.println(getTreeAdDepartment(as, domain));
            if (ctx != null) {
                ctx.close();
            }
            JSONObject jsonObject = JSONObject.parseObject(JSONObject.toJSONString(getTreeAdDepartment(as, domain)));
            return jsonObject.toString();
        } catch (NamingException e) {
            e.printStackTrace();
        }
        return result;
    }

    public static AdDepartment getTreeAdDepartment(TreeSet<AdDepartment> treeSet, String domain) {
        AdDepartment root = new AdDepartment();
        root.setName(domain);
        root.setcName(domain);
        for (AdDepartment ad : treeSet) {
            AdDepartment parentAdDepartment = null;
            if ((parentAdDepartment = root.getParentAdDepartmentBycName(ad.getcName())) != null) {
                parentAdDepartment.addChildren(ad);
            } else {
                root.addChildren(ad);
            }
        }
        return root;
    }


    // 获取部门列表
    public static TreeSet<AdDepartment> getAdDepartment(LdapContext ctx, String searchBase) throws NamingException {
        //LDAP搜索过滤器类,此处只获取AD域用户,所以条件为用户user或者person均可
        String searchFilter = "objectClass=User";
        //AD域节点结构
        NamingEnumeration<SearchResult> answer = getSearchResult(ctx, searchFilter, searchBase);
        TreeSet<AdDepartment> treeSet = new TreeSet<AdDepartment>();
        while (answer.hasMoreElements()) {
            SearchResult sr = answer.next();
            AdDepartment adDepartment = new AdDepartment();
            // 是否禁用账户,过滤掉禁用账户
            if (isDisableAccount(sr)) {
                continue;
            }
            adDepartment.setName(getAttrValue(sr, "name"));
            adDepartment.setcName(getAttrValue(sr, "canonicalName"));
            adDepartment.setDistinguishedName(getAttrValue(sr, "distinguishedName"));
            treeSet.add(adDepartment);
        }
        return treeSet;
    }

    private static boolean isDisableAccount(SearchResult sr) throws NamingException {
        Attributes Attrs = sr.getAttributes();
        Attribute attr = Attrs.get("userAccountControl");
        if (attr != null) {
            String control = Integer.toBinaryString(Integer.valueOf((String) attr.get()));
            if ("1".equals(control.substring(control.length() - 2, control.length() - 1))) {
                return true;
            }
        }
        return false;
    }

    /**
     * 获取属性值
     *
     * @param sr
     * @param attr
     * @return
     * @throws NamingException
     */
    public static String getAttrValue(SearchResult sr, String attr) throws NamingException {
        Attributes Attrs = sr.getAttributes();
        if (Attrs.get(attr) == null) {
            return null;
        }
        return Attrs.get(attr).getAll().next().toString();
    }

    private static final String SUN_JNDI_PROVIDER = "com.sun.jndi.ldap.LdapCtxFactory";

    /**
     * 测试连接
     *
     * @param request
     * @return
     */
    public static boolean testConnect(Map<String, Object> request) {
        boolean connectFlag = false;
        String ip = request.get("serverIp").toString();
        String port = request.get("serverPort").toString();
        String domain = request.get("serverDomain").toString();
        String uName = request.get("loginName").toString();
        String uPassword = request.get("loginPassword").toString();
        String URL = "ldap://" + ip + ":" + port;

        if (!LogonUtil.ping(ip)) {
            return false;
        }

        Hashtable<String, String> env = new Hashtable<String, String>();
        //用户名称,cn,ou,dc 分别:用户,组,域
        env.put(Context.SECURITY_PRINCIPAL, uName);
        //用户密码 cn 的密码
        env.put(Context.SECURITY_CREDENTIALS, uPassword);
        //url 格式:协议://ip:端口/组,域   ,直接连接到域或者组上面
        env.put(Context.PROVIDER_URL, URL);
        //LDAP 工厂
        env.put(Context.INITIAL_CONTEXT_FACTORY, SUN_JNDI_PROVIDER);
        //验证的类型     "none", "simple", "strong"
        env.put(Context.SECURITY_AUTHENTICATION, "simple");
        LdapContext ctx = null;
        try {
            ctx = new InitialLdapContext(env, null);
            connectFlag = ctx != null;
        } catch (NamingException e) {
            LOG.info("testConnect false");
        }
        return connectFlag;
    }
public class AdDepartment implements Comparable<AdDepartment>{
    private String id;
    private String name;
    private String cName;
    private String distinguishedName;

    public String getId() {
        return id;
    }

    public void setId(String id) {
        this.id = id;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public String getcName() {
        return cName;
    }

    public void setcName(String cName) {
        this.cName = cName;
    }

    public String getDistinguishedName() {
        return distinguishedName;
    }

    public void setDistinguishedName(String distinguishedName) {
        this.distinguishedName = distinguishedName;
    }

    public List<AdDepartment> getChildren() {
        return children;
    }

    public void setChildren(List<AdDepartment> children) {
        this.children = children;
    }

    private List<AdDepartment> children = new ArrayList<AdDepartment>();


    public AdDepartment getAdDepartmentBycName(String cName) {
        if (this.cName.equals(cName) ) {
            return this;
        }else{
            for (AdDepartment adDepartment : children) {
                AdDepartment adDepartment1 =null;
                if ((adDepartment1 = adDepartment.getAdDepartmentBycName(cName)) != null) {
                    return adDepartment1;
                }
            }
        }
        return null;
    }
    public AdDepartment getParentAdDepartmentBycName(String cName) {
        int index;
        AdDepartment adDepartment = null;
        while ((index = cName.lastIndexOf("/")) != -1) {
            cName = cName.substring(0, index);
            adDepartment = getAdDepartmentBycName(cName);
            if (adDepartment != null) {
                return adDepartment;
            }
        }
        return adDepartment;
    }


    public int compareTo(AdDepartment o) {
        return cName.length() - o.getcName().length();
    }

    public void addChildren(AdDepartment adDepartment) {
        this.children.add(adDepartment);
    }

    @Override
    public String toString() {
        return "AdDepartment{" +
                "id='" + id + '\'' +
                ", name='" + name + '\'' +
                ", cName='" + cName + '\'' +
                ", distinguishedName='" + distinguishedName + '\'' +
                ", children=" + children +
                '}';
    }
}
 public void updateUsersMsg(Integer type, Map<String, Object> map) {
        String ip = map.get("ip").toString();
        String port = map.get("port").toString();
        String domain = map.get("domain").toString();
        String uName = map.get("uName").toString();
        String uPassword = map.get("uPassword").toString();
        String URL = "ldap://" + ip + ":" + port;
        Properties env = new Properties();// 实例化一个Env
        // LDAP 服务器的 URL 地址,
        env.put(Context.SECURITY_AUTHENTICATION, "simple");// LDAP访问安全级别(none,simple,strong),一种模式,这么写就行
        env.put(Context.SECURITY_PRINCIPAL, uName); // 用户名
        env.put(Context.SECURITY_CREDENTIALS, uPassword);// 密码
        env.put(Context.INITIAL_CONTEXT_FACTORY, SUN_JNDI_PROVIDER);// LDAP工厂类
        env.put(Context.PROVIDER_URL, URL);// Url
        LdapContext ctx;
        // 所有数据,解析入库
        String resultStr = "";
        String sDomain = "";
        if (domain.indexOf("@") == -1)
            sDomain = "@" + domain;
        String sB1 = sDomain.substring(1, sDomain.indexOf("."));
        String sB2 = sDomain.substring(sDomain.indexOf(".") + 1, sDomain.length());

        try {
            ctx = ADUtil.getContext(env);
            String searchBase = "DC=" + sB1 + ",DC=" + sB2;
            resultStr = ADUtil.getTreeAdDepartment(env, domain, searchBase);
        } catch (NamingException e) {
            e.printStackTrace();
        }
        Map<String, Object> resultStrMap = (Map<String, Object>) JSONObject.parseObject(resultStr, Map.class);
        List<Object> children = JSONObject.parseObject(JSONObject.toJSONString(resultStrMap.get("children")), List.class);
        // children为获取到的用户数据
        }
  }

以上

  • 0
    点赞
  • 7
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
要通过Java使用LDAP获取AD用户和组织信息,需要使用Java的JNDI API。 以下是一个简单的Java程序,演示如何使用JNDI API连接AD获取用户和组织信息: ``` import java.util.*; import javax.naming.*; import javax.naming.directory.*; public class ADInfo { public static void main(String[] args) { String ldapURL = "ldap://AD服务器地址:389"; String ldapUser = "CN=LDAP查询用户,OU=xxx,DC=xxx,DC=xxx"; String ldapPassword = "LDAP查询用户密码"; String searchBase = "OU=xxx,DC=xxx,DC=xxx"; Hashtable<String, String> env = new Hashtable<String, String>(); env.put(Context.INITIAL_CONTEXT_FACTORY, "com.sun.jndi.ldap.LdapCtxFactory"); env.put(Context.PROVIDER_URL, ldapURL); env.put(Context.SECURITY_AUTHENTICATION, "simple"); env.put(Context.SECURITY_PRINCIPAL, ldapUser); env.put(Context.SECURITY_CREDENTIALS, ldapPassword); try { DirContext ctx = new InitialDirContext(env); SearchControls searchControls = new SearchControls(); searchControls.setSearchScope(SearchControls.SUBTREE_SCOPE); String filter = "(objectCategory=user)"; NamingEnumeration<SearchResult> results = ctx.search(searchBase, filter, searchControls); while (results.hasMore()) { SearchResult searchResult = results.next(); Attributes attributes = searchResult.getAttributes(); Attribute attribute = attributes.get("cn"); String cn = (String) attribute.get(); System.out.println(cn); } filter = "(objectCategory=organizationalUnit)"; results = ctx.search(searchBase, filter, searchControls); while (results.hasMore()) { SearchResult searchResult = results.next(); Attributes attributes = searchResult.getAttributes(); Attribute attribute = attributes.get("ou"); String ou = (String) attribute.get(); System.out.println(ou); } ctx.close(); } catch (NamingException e) { e.printStackTrace(); } } } ``` 在上面的代码中,替换以下变量: - ldapURL:AD服务器地址和端口号 - ldapUser:用于查询AD的LDAP用户的DN - ldapPassword:用于查询AD的LDAP用户的密码 - searchBase:要搜索的AD的基本DN 该程序连接AD并搜索用户和组织。它使用过滤器来限制搜索结果,只搜索用户和组织单位对象。它还使用SearchControls对象来设置搜索范围。 对于每个搜索结果,程序从属性中提取cn或ou,并将其打印到控制台上。 请注意,此代码需要在Java应用程序中包含JNDI API类路径。如果您使用Maven或Gradle之类的构建工具,则可以将以下依赖项添加到项目中: ``` <dependency> <groupId>com.sun.jndi</groupId> <artifactId>ldap</artifactId> <version>1.2.1</version> </dependency> ```
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值