JNDI LDAP 在同一个 InitialDirContext 对象中创建 2 个连接

JNDI LDAP create 2 connection In the the same InitialDirContext object

我需要创建 1 个 ldap 连接(我使用一个应用程序帐户),我需要从这个连接创建其他连接(用户连接)以检查 uid 和密码是否正确。

Properties env = new Properties();
env.put(Context.INITIAL_CONTEXT_FACTORY, "com.sun.jndi.ldap.LdapCtxFactory");
env.put(Context.PROVIDER_URL, ldapServerUrl);
env.put(Context.SECURITY_AUTHENTICATION, "none");

SearchControls searchCtrls = new SearchControls();
searchCtrls.setReturningAttributes(new String[] {});
searchCtrls.setSearchScope(SearchControls.SUBTREE_SCOPE);

String filter = "(&(cn=" + identifier + "))";

DirContext ctx = null;
ctx = new InitialDirContext(env);
NamingEnumeration<SearchResult> answer = ctx.search(
   ldapBaseDN, filter, searchCtrls);

String fullDN = null;
if (answer.hasMore()) {
    fullDN = answer.next().getNameInNamespace();

    ctx.close();
    ctx = null;

    env.put(Context.SECURITY_AUTHENTICATION, "simple");
    env.put(Context.SECURITY_PRINCIPAL, fullDN);
    env.put(Context.SECURITY_CREDENTIALS, password);

    ctx = new InitialDirContext(env);
    // here I must create the user connection for check if the uid and password is good.

    return true;
}

谢谢。

在 LDAP DIT 中找到用户后,您应该修改环境以包含用户的 DN 和密码,然后使用相同的 Context.

发出 LdapContext.reconnect()

您不需要创建单独的 'physical' 连接。