我已经使用 Java 连接到 LDAP 服务器:
Hashtable<String, String> env = new Hashtable<String, String>();
env.put(Context.INITIAL_CONTEXT_FACTORY, "com.sun.jndi.ldap.LdapCtxFactory");
env.put(Context.PROVIDER_URL, "ldap://XXX");
env.put(Context.SECURITY_AUTHENTICATION, "simple");
env.put(Context.SECURITY_PRINCIPAL, "DOMAIN\\user.name");
env.put(Context.SECURITY_CREDENTIALS, "password");
DirContext ctx = new InitialDirContext(env);
if(ctx != null){
// get details : samaccount, mail, userprincipal, all fields from AD
}
我是所有计算机语言的新手,但在 PHP 中我可以使用定义过滤器
a samaccountname
(与前面代码中的 user.name
相同)并且搜索返回
该用户的所有详细信息的关联数组。我怎样才能在Java中做到这一点?
只需使用 samaccountname
(用户只需输入 user.name
值及其密码),绑定(bind)完成并创建上下文后
获取他的所有详细信息。
提前致谢。
(PS:我在谷歌上没有找到任何可以提供帮助的内容)。
最佳答案
您可以提供搜索库和过滤器,这是一个示例:
String USER_SEARCH_BASE = "OU=somegroup,dc=company,dc=com";
String USER_SEARCH_FILTER = "(&(sAMAccountName=%username%)(objectclass=user))"
然后在上下文中搜索用户:
Hashtable<String, String> env = new Hashtable<String, String>();
env.put(Context.INITIAL_CONTEXT_FACTORY, "com.sun.jndi.ldap.LdapCtxFactory");
env.put(Context.PROVIDER_URL, "ldap://XXX");
env.put(Context.SECURITY_AUTHENTICATION, "simple");
env.put(Context.SECURITY_PRINCIPAL, "DOMAIN\\user.name");
env.put(Context.SECURITY_CREDENTIALS, "password");
DirContext ctx = new InitialDirContext(env);
if(ctx != null){
String []requiredAttributes = {"sn","cn","sAMAccountName","memberOf"};
SearchControls controls = new SearchControls();
controls.setSearchScope(SearchControls.SUBTREE_SCOPE);
controls.setReturningAttributes(requiredAttributes);
SearchResult searchResult = null;
NamingEnumeration user = ctx.search(USER_SEARCH_BASE, USER_SEARCH_FILTER, controls);
while(users.hasMore()){
searchResult=(SearchResult)users.next();
Attributes attr = searchResult.getAttributes();
String commonName = attr.get("cn").get(0).toString();
System.out.println("Common Name: " + commonName);
}
}
或者您可以调试上下文并检查所有可用的属性。 希望有帮助。
关于java - LDAP 上的登录用户获取所有详细信息,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54325767/