java - 与管理员绑定后使用 LDAP 对用户进行身份验证?
问题描述
我一直在尝试构建一个在 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
}
该程序使用管理员帐户成功绑定,但未根据提供的用户名定位用户。在构建此应用程序时,我一直在使用以前的答案LDAP Authentication using Java作为参考。我的目标是提供用户名,然后在目录中搜索用户的全名(作为 CN 提供二级身份验证)。经过一些测试,我发现user和answers都返回 null,即没有找到用户。我不太明白为什么会这样,我还需要为搜索提供什么吗?我应该怎么办?
解决方案
推荐阅读
- amazon-ec2 - 如何通过 SSH 隧道通过 AWS 堡垒/跳转服务器从笔记本电脑访问 phpMyAdmin 到使用 .ssh/config 的 EC2 实例
- pascal - 在帕斯卡中交换两个数字
- android - 如何创建一个可以点击其他应用程序的自动点击器应用程序?
- julia - 在 Julia 中创建长度为 n 的向量
- react-native - 如何解决 Module parse failed: Unexpected token (11:9) react-router-native
- angular - Angular gapi 将简单文本上传到 Google Drive
- android - 如何根据android中的屏幕尺寸更改edittext宽度?
- java - Concurrent HashMap 中 Rehashing 期间的检索
- vue.js - VueJS通过代码加载模板组件?
- mongodb - MongoDB - 查找数组长度小于或等于 5 的文档