public static void main(String[] args)
{
String INITCTX = "com.sun.jndi.ldap.LdapCtxFactory";
String MY_HOST = "ldap://Localhost:1389";
String MGR_DN = "cn=John,ou=Users,o=IT,dc=QuizPortal";
String MGR_PW = "password";
//Identify service provider to use
Hashtable env = new Hashtable();
env.put(Context.INITIAL_CONTEXT_FACTORY, INITCTX);
env.put(Context.PROVIDER_URL, MY_HOST);
env.put(Context.SECURITY_AUTHENTICATION, "simple");
env.put(Context.SECURITY_PRINCIPAL, MGR_DN);
env.put(Context.SECURITY_CREDENTIALS, MGR_PW);
try
{
// Create the initial directory context
InitialDirContext initialContext = new InitialDirContext(env);
System.out.println("Context Sucessfully Initialized");
}
catch(Exception e)
{
System.err.println(e);
}
}
我想问一下什么时候将 MGR_DN = "cn=John,ou=Users,o=IT,dc=QuizPortal"
设置为 MGR_DN = "uid=103,ou =Users,o=IT,dc=QuizPortal"
。基本上从cn改成uid,都会报错
javax.naming.AuthenticationException: [LDAP: error code 49 - Invalid Credentials]
当指定为 cn=John
而不是 uid=103
时,我通过了身份验证。不能用uid指定吗?
最佳答案
如果您事先不知道确切的 DN,您应该先在 LDAP 目录中进行搜索。这或多或少可以像这样完成(确保你捕获了相关的异常):
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);
return true;
}
// Exception otherwise ...
在这里,搜索过滤器是 "(&(cn="+ identifier + "))"
(所以,例如 (&(cn=John))
),但您可以改用 uid
。结果的唯一性取决于 LDAP 服务器的配置。基本 DN 还取决于它的设置方式(在您的示例中可能是 ou=Users,o=IT,dc=QuizPortal
)。
关于java - 使用 JNDI 的 LDAP 用户密码认证,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3456870/