使用JNDI进行LDAP身份验证

时间:2017-11-30 10:28:10

标签: java ldap jndi

我想测试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

有没有人有经验,可以就如何正确传递这些值来指出哪些错误?当然我想连接而不是引发异常。

1 个答案:

答案 0 :(得分:1)

SECURITY_PRINCIPAL需要是您要验证的用户的整个DN。

通常你必须事先搜索DIT才能找到这个,使用用户的某些独特属性,比如他的电子邮件地址,通常你必须认证为拥有权利的DIT内置的其他管理用户做那个搜索。然后,当您找到DN时,更改SECURITY_PRINCIPAL并重新连接。