java 获取AD域下用户数据

话不多说,上代码

使用的依赖jar有两个(ldapbp-1.0.jar,spring-ldap-core-2.3.2.RELEASE.jar)

	import javax.naming.AuthenticationException;
    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.DirContext;
    import javax.naming.directory.InitialDirContext;
    import javax.naming.directory.SearchControls;
    import javax.naming.directory.SearchResult;

    /**
	 * 使用java连接AD域,获取域账号信息
	 * 
	 * @return 域账户List
	 * @throws
	 * @param url 连接AD域服务器的url,ip + 端口号(默认389)
	 * @param username AD域用户名
	 * @param password 用户密码
	 */
	private List connect(String url, String username, String password) {
		List<Map<String,String>> userList = new ArrayList<Map<String,String>>();
		DirContext ctx = null;
		Hashtable<String, String> HashEnv = new Hashtable<String, String>();
		HashEnv.put(Context.SECURITY_AUTHENTICATION, "simple"); // LDAP访问安全级别(none,simple,strong)
		HashEnv.put(Context.SECURITY_PRINCIPAL, username); // AD的用户名
		HashEnv.put(Context.SECURITY_CREDENTIALS, password); // AD的密码
		HashEnv.put(Context.INITIAL_CONTEXT_FACTORY, "com.sun.jndi.ldap.LdapCtxFactory"); // LDAP工厂类
		HashEnv.put("com.sun.jndi.ldap.connect.timeout", "20000");// 连接超时设置为20秒
		HashEnv.put(Context.PROVIDER_URL, "ldap://" + url);
		try {
			ctx = new InitialDirContext(HashEnv);// 初始化上下文
			System.out.println("身份验证成功!");
			// 域节点
			String searchBase = "DC=xxx,DC=cn";
			// LDAP搜索过滤器类
			String searchFilter = "(&(objectCategory=person)(sn=*xxxx*))"; // 查询用户,同时可以添加自己需要的查询条件,*代表模糊查询,跟sql中like一样
			// 创建搜索控制器
			SearchControls searchCtls = new SearchControls();
			// 设置搜索等级
			searchCtls.setSearchScope(SearchControls.SUBTREE_SCOPE); // Specify
			//displayName名称(name),sAMAccountName登录名称(id),Department部门,Mail邮箱
			String returnedAtts[] = { "displayName", "sAMAccountName","Department","Mail"};// 定制返回属性,还有很多属性,可自行百度
			searchCtls.setReturningAttributes(returnedAtts); // 设置返回属性集
			// 根据设置的域节点、过滤器类和搜索控制器搜索LDAP得到结果
			NamingEnumeration answer = ctx.search(searchBase, searchFilter, searchCtls);// 根据过滤条件查找数据
			while (answer.hasMoreElements()) {// 遍历结果集
				SearchResult sr = (SearchResult) answer.next();
				Attributes Attrs = sr.getAttributes();// 得到域用户属性集
				if (Attrs != null) {
					try {
						Map<String,String> m = new HashMap();
						for (NamingEnumeration ne = Attrs.getAll(); ne.hasMore();) {
							Attribute Attr = (Attribute) ne.next();// 得到下一个属性
							String key = Attr.getID().toString();
							// 读取属性值
							for (NamingEnumeration e = Attr.getAll(); e.hasMore();) {
								String value= e.next().toString();
								m.put(key, value);
							}
						}
						userList.add(m);
					} catch (NamingException e) {
						System.err.println("Throw Exception : " + e);
					}
				}
				ctx.close();
			}
			
//			for (int i = 0; i < userList.size(); i++) {
//				Map<String, String> m = userList.get(i);
//				for(Map.Entry<String, String> entry : m.entrySet()){
//				    String mapKey = entry.getKey();
//				    String mapValue = entry.getValue();
//				    System.out.println("第"+(i+1)+"个用户key = "+mapKey+" , value = "+mapValue);
//				}
//				System.out.println("-----------------------------");
//			}
		} catch (AuthenticationException e) {
			System.out.println("身份验证失败!");
			e.printStackTrace();
		} catch (javax.naming.CommunicationException e) {
			System.out.println("AD域连接失败!");
			e.printStackTrace();
		} catch (Exception e) {
			System.out.println("身份验证未知异常!");
			e.printStackTrace();
		} finally {
			if (null != ctx) {
				try {
					ctx.close();
					ctx = null;
				} catch (Exception e) {
					e.printStackTrace();
				}
			}
		}
		return userList;
	}

发现一篇总结更好的文章,链接:获取和验证Windows AD域的用户信息 - 走看看

  • 1
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 2
    评论
要通过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:用于查询ADLDAP用户的DN - ldapPassword:用于查询ADLDAP用户的密码 - 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> ```
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值