Java 连接LDAP实现验证与查询用户

在企业级应用中,LDAP常用来进行用户的统一管理和验证。用户登录应用系统时,输入用户名和密码, 应用系统到LDAP服务器验证该用户名密码是否有效。
Java本身提供了JNDI相关的API可以连接和查询LDAP。主要步骤包括:

  1. 设置初始LDAP上下文的属性,并初始化LDAP上下文
  2. 设置查询的属性
  3. 通过上下文查询记录
  4. 获取查询的内容
  5. 关闭 上下文,释放连接
    示例代码如下:
String principal = "Manager";
		String password = "secret";
		String ldapUrl = "ldap://XXX:389";
		LdapContext ctx = null;
		String searchBase = "dc=maxcrc,dc=com";
		String searchDn = "cn=Manager,dc=maxcrc,dc=com";

		//1. 设置初始LDAP上下文的属性,并初始化LDAP上下文
		Hashtable<String, String> env = new Hashtable<String, String>();
		env.put(Context.INITIAL_CONTEXT_FACTORY, "com.sun.jndi.ldap.LdapCtxFactory");// Factory用于创建InitialContext对象
		env.put(Context.SECURITY_AUTHENTICATION, "Simple");
		//env.put(Context.SECURITY_PRINCIPAL, principal);
		env.put(Context.SECURITY_CREDENTIALS, password);
		env.put(Context.SECURITY_PRINCIPAL, searchDn);
		env.put(Context.PROVIDER_URL, ldapUrl);
		try {
			ctx = new InitialLdapContext(env, null);
			//2. 设置查询的属性
			SearchControls constraints = new SearchControls();
			constraints.setSearchScope(SearchControls.SUBTREE_SCOPE);
			constraints.setReturningAttributes(new String[] { "xxx" });
			//3. 通过上下文查询记录
			NamingEnumeration<SearchResult> results = ctx.search(searchBase, "uid=Oscar", constraints);
			//4. 获取查询的内容
			while (results.hasMore()) {
				NameClassPair nc = (NameClassPair) results.next();
				System.out.println(nc);
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
		//5. 关闭	上下文,释放连接
		finally {
			if (ctx != null) {
				try {
					ctx.close();// 4.0 close Connection
					// LOG.info("Close Ldap Successful.");
				} catch (NamingException e) {
					// LOG.error("Exception in ldapClose(): ", e);
				}
			}
		}
  • 0
    点赞
  • 7
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

oscar999

送以玫瑰,手留余香

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值