如果你真的想比较一个字段(不限于用户名和密码),你可以在search方法上使用下面的wrapper:
public boolean compare(LdapContext ctx, String dn, String filter) {
NamingEnumeration<SearchResult> answer = null;
try {
SearchControls searchCtls = new SearchControls();
searchCtls.setSearchScope(SearchControls.OBJECT_SCOPE);
searchCtls.setReturningAttributes(new String[0]);
answer = ctx.search(dn, filter, searchCtls);
if (answer == null || !answer.hasMore()) {
return false; // E.g.: wrong filter
}
} catch (NamingException ex) {
return false; // E.g.: wrong DN
}
return true;
}
ctx 可能在哪里:
LdapContext ctx = new InitialLdapContext(getEnvironment(userName, password), null);
getEnvironment 方法可以是:
private Hashtable<String, Object> getEnvironment(String userName, String password) {
Hashtable<String, Object> env = new Hashtable<>();
env.put(Context.INITIAL_CONTEXT_FACTORY, "com.sun.jndi.ldap.LdapCtxFactory");
env.put(Context.PROVIDER_URL, LDAP_HOST_389);
env.put(Context.SECURITY_AUTHENTICATION, "DIGEST-MD5");
env.put(Context.SECURITY_PRINCIPAL, userName);
env.put(Context.SECURITY_CREDENTIALS, password);
return env;
}
如果你调用上面的compare方法,你会得到:
你也可以看看LDAP Compare documentation from Oracle。