在 Java 中使用 LDAP 获取组
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/34491680/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Get Groups using Ldap in java
提问by
How can i get a particular user groups using Active Directory ? I am getting all groups but i want to get groups which user is belonging
如何使用 Active Directory 获取特定用户组?我正在获取所有组,但我想获取用户所属的组
public static String ldapUri = "ldap://pdc.example.com:389";
public static String usersContainer = "cn=users,dc=example,dc=com";
public ArrayList<String> getUserGroups(String email, String password){
ArrayList<String> list = new ArrayList<String>();
Hashtable env = new Hashtable();
env.put(Context.INITIAL_CONTEXT_FACTORY, "com.sun.jndi.ldap.LdapCtxFactory");
env.put(Context.PROVIDER_URL, ldapUri);
env.put(Context.SECURITY_PRINCIPAL, email);
env.put(Context.SECURITY_CREDENTIALS, password);
try {
DirContext ctx = new InitialDirContext(env);
SearchControls ctls = new SearchControls();
String[] attrIDs = { "cn" };
ctls.setReturningAttributes(attrIDs);
ctls.setSearchScope(SearchControls.ONELEVEL_SCOPE);
NamingEnumeration answer = ctx.search(usersContainer, " (objectclass=group)", ctls);
while (answer.hasMore()) {
SearchResult rslt = (SearchResult) answer.next();
Attributes attrs = rslt.getAttributes();
String groups = attrs.get("cn").toString();
String [] groupname = groups.split(":");
String userGroup = groupname[1];
System.out.println(attrs.get("cn"));
}
ctx.close();
} catch (NamingException e) {
e.printStackTrace();
}
return list;
}
回答by
I am getting all groups of a user by using this
我通过使用这个来获取用户的所有组
String[] attrIDs = {"cn"};
ctls.setReturningAttributes(attrIDs);
String[] attributes = {"memberOf"};
ctls.setReturningAttributes(attributes);
NamingEnumeration<?> answer = ctx.search(usersContainer, "(&(objectclass=user)(sAMAccountName=userName))", ctls);
回答by Sai Ganesh Pittala
If you are using Active Directory. User has the attribute 'memberOf'; fire a search query for specific user and include 'memberOf' in return attributes.
如果您使用的是 Active Directory。用户具有属性“memberOf”;为特定用户触发搜索查询,并在返回属性中包含“memberOf”。
String[] attrIDs = { "cn", "memberOf" };
ctls.setReturningAttributes(attrIDs);
ctls.setSearchScope(SearchControls.ONELEVEL_SCOPE);
NamingEnumeration answer = ctx.search(usersContainer, "(&(objectclass=person)(cn=*sahi*))", ctls);
'memberOf' attribute holds the groups which the user belongs to.
'memberOf' 属性保存用户所属的组。