在企业级应用中,LDAP常用来进行用户的统一管理和验证。用户登录应用系统时,输入用户名和密码, 应用系统到LDAP服务器验证该用户名密码是否有效。
Java本身提供了JNDI相关的API可以连接和查询LDAP。主要步骤包括:
- 设置初始LDAP上下文的属性,并初始化LDAP上下文
- 设置查询的属性
- 通过上下文查询记录
- 获取查询的内容
- 关闭 上下文,释放连接
示例代码如下:
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);
}
}
}