我一直在尝试构建在Tomcat 9上运行的Web应用程序,该应用程序通过LDAP服务器对用户进行身份验证。请在下面查看我的代码:
String username = request.getParameter("uname");
String password = request.getParameter("password");
String base = "DC=xsoltns,DC=y";
String dn = "CN=Admin,CN=Users," + base;
String ldap_url = "ldap://address:389";
Properties props = new Properties();
props.put(Context.INITIAL_CONTEXT_FACTORY, ("com.sun.jndi.ldap.LdapCtxFactory"));
props.put(Context.PROVIDER_URL, ldap_url);
props.put(Context.SECURITY_PRINCIPAL, dn);
props.put(Context.SECURITY_CREDENTIALS, "adminpassword");
try
{
InitialDirContext context = new InitialDirContext(props);
String principle_name = username+"@mydomain.com";
SearchControls ctrls = new SearchControls();
ctrls.setReturningAttributes(new String[] {"givenName", "sn", "memberOf"});
ctrls.setSearchScope(SearchControls.SUBTREE_SCOPE);
NamingEnumeration<javax.naming.directory.SearchResult> answers =
context.search(base, "(uid="+principle_name+")", ctrls);
javax.naming.directory.SearchResult result = answers.nextElement();
String user = result.getNameInNamespace();
try
{
props = new Properties();
props.put(Context.INITIAL_CONTEXT_FACTORY, "com.sun.jndi.ldap.LdapCtxFactory");
props.put(Context.PROVIDER_URL, ldap_url);
props.put(Context.SECURITY_PRINCIPAL, user);
props.put(Context.SECURITY_CREDENTIALS, password);
context = new InitialDirContext(props);
//user authenticated
} catch (Exception e)
{
//error with user auth
}
} catch (Exception e)
{
//error with admin auth
}
该程序已使用Admin帐户成功绑定,但根据提供的用户名找不到该用户。构建此应用程序时,我一直在使用先前的答案LDAP Authentication using Java作为参考。我的目标是提供用户名,然后在目录中搜索用户的全名(作为CN来提供辅助身份验证)。经过一些测试,我发现 user 和 answers 返回空值,即未找到用户。我不太明白为什么会这样,搜索还需要提供其他内容吗?我该怎么办?