【发布时间】:2017-11-30 10:28:10
【问题描述】:
我想测试 LDAP 用户的给定用户和密码是否正确。
我整理了一下,jndi是要使用的库。
我找到了这个简单的类:
package myldap;
import java.util.Hashtable;
import javax.naming.AuthenticationException;
import javax.naming.Context;
import javax.naming.NamingEnumeration;
import javax.naming.NamingException;
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;
// boolean function to test user and pwd
public static boolean userVerify(String user, String password){
boolean userVerify = false;
Hashtable env = new Hashtable();
env.put(Context.INITIAL_CONTEXT_FACTORY,"com.sun.jndi.ldap.LdapCtxFactory");
env.put(Context.PROVIDER_URL, "ldap://192.168.48.10");
env.put(Context.SECURITY_AUTHENTICATION, "simple");
env.put(Context.SECURITY_PRINCIPAL, "CN=" + user + ",conn");
env.put(Context.SECURITY_CREDENTIALS, password);
try {
DirContext authContext = new InitialDirContext(env);
userVerify = true;
authContext.close();
} catch (AuthenticationException authEx) {
//("Authentication Exception!");
userVerify = false;
} catch (NamingException namEx) {
//("Something went wrong!");
userVerify = false;
}
return userVerify;
}
因为我试图让它工作,所以我在玩参数。 我在函数中输入的值是
INITIAL_CONTEXT_FACTORY,"com.sun.jndi.ldap.LdapCtxFactory");
PROVIDER_URL, "ldap://192.168.48.10");
SECURITY_AUTHENTICATION, "simple");
SECURITY_PRINCIPAL, "CN=" + user + ",conn");
SECURITY_CREDENTIALS, password);
通过上面我得到AuthenticationException,这是我可以达到的最好结果,通过改变我得到NamingException的东西,所以我似乎不太接近解决方案。
尤其是我不确定SECURITY_PRINCIPAL。
有没有人有经验并且可以就如何正确传递这些值来确定哪些是错误的提供建议?当然我想连接而不是引发异常。
【问题讨论】: