I don't know java that much but I need to change a code. The background here is we have the code working in LDAP which will give us the groups assigned to the user which has logged in. Now, we have to switch to OpenLDAP for some reason and here the problem arises. Here we are not able to get the groups assigned to the user.
Previously I was using to get the groups
The context name is here ou=People,dc=maxcrc,dc=com
NamingEnumeration<SearchResult> search
= context.search(contextName,
"(sAMAccountName=" + userId + ")", constraints);
Now, I have tried various combination like
NamingEnumeration<SearchResult> search
= context.search(contextName,
"(uid=" + userId + ")", constraints);
and
NamingEnumeration<SearchResult> search
= context.search(contextName,
"(&(objectClass=groupOfNames)(cn=+userId)", constraints);
and others.
The problem is here I am not getting the groups name. So, is there wrong in how I am searching for groups or what I am not getting. Could anyone please help me.
This is our code
public static HashMap getGroupList(
DirContext context, String userId, String key)
throws NamingException, NullArgumentException,
InvalidStringValueException, ParserException {
//setting sonstraints ans searach control to subtree scope
HashMap groupList = new HashMap();
SearchControls constraints = new SearchControls();
constraints.setSearchScope(SearchControls.ONELEVEL_SCOPE);
constraints.setReturningAttributes(new String[]{"cn", MEMBER_OF_ATTRIBUTE});
String contextName = parser.getConfigNodeValue("contextName");
logger.debug("Context Name: " + contextName);
logger.debug("Finding Group List for user ID: " + userId);
NamingEnumeration<SearchResult> search
= context.search(contextName,
SAMAC_COUNT_NAME + userId + CLOSE_BRACKET, constraints);
//searching attribute
logger.debug("searching attribute");
SearchResult searchResult = null;
String value = "";
while (search.hasMoreElements()) {
searchResult = search.next();
String groupName = searchResult.getAttributes().get(MEMBER_OF_ATTRIBUTE).toString();
groupList.put(groupName, groupName);
}
return groupList;
}
EDIT:
here context name is ou=People,dc=maxcrc,dc=com and I have applied the various search filter as (uid=userId), also (&(objectClass=groupOfNames)(uid=userId)), also (&(objectClass=user)(uid=userId)), but I am getting nothing out. I need to know how to search in here.
Directory is simple here-
In dc=maxcrc dc=com there is ou=People
and there is a user inside that demo and the demo has is a part of a group. Object class is inetOrgPerson for a user
the output was nothing
That doesn't mean the attribute was empty. If that had been the case you would have seen the output of logger.debug(groupName + " group name found for " + userId);. As you didn't, clearly the search itself didn't return anything, i.e. something wrong with your filter or start DN.
EDIT Re your edit, only the first filter makes sense. The second one is a syntax error, and the third one searches the groups rather than the users, and it is the users that will have the memberOf attribute, not the groups. There is still not enough information here to comment further.
EDIT 2
context name is ou=People,dc=maxcrc,dc=com
OK.
and I have applied the various search filter as (uid=userId)
Do you mean (uid={0}) with a parameter of the value of userId? You should. And what was the value of userId?
this also (&(objectClass=groupOfNames)(uid=userId))
This is just nonsense:
There won't be (shouldn't be) groups under ou=People;
Group objects won't have a memberOf attribute. Users will have a memberOf attribute, showing what groups they are a member of. Looking for that inside the groups makes no sense whatsoever.
this also (&(objectClass=user)(uid=userId))
See above. This requires that user objects have an objectClass of user. Do they? If not, what do they have, and why aren't you using that?
And please answer the question about what the relevant part of the directory tree looks like. Including the object classes.
I was wrong all the time. There is no memberof attribute in our OpenLDAP so the code will not work.
So I need to change the code a little bit such that I authenticate the user and then I should query every group present and check whether that username is present in those groups.
So, even if there is no memberof I can work out.
This is sample code I used-
import javax.naming.NamingException;
public class LdapQuery {
public static void main(String[] args) throws NamingException {
SimpleLdapAuthentication obj = new SimpleLdapAuthentication();
obj.ldapquery();
}
}
and here is the method
import java.util.Hashtable;
import javax.naming.AuthenticationException;
import javax.naming.Context;
import javax.naming.NamingEnumeration;
import javax.naming.NamingException;
import javax.naming.directory.DirContext;
import javax.naming.directory.InitialDirContext;
import javax.naming.directory.SearchControls;
import javax.naming.directory.SearchResult;
public class SimpleLdapAuthentication {
public String ldapquery() {
String distName = "";
String username = "cn=demo,ou=People,dc=saas,dc=com";
String[] userID = new String[2];
userID[0] = "Users";
userID[1] = "Developers";
int size = userID.length;
String password = "sacs3";
String groupName = "";
String base = "ou=People,dc=maxcrc,dc=com";
//String searchFilter = "cn=" + username + "," + base;
String ldapURL = "ldap://yourldapurl";
Hashtable<String, String> environment = new Hashtable<String, String>();
environment.put(Context.INITIAL_CONTEXT_FACTORY, "com.sun.jndi.ldap.LdapCtxFactory");
environment.put(Context.PROVIDER_URL, ldapURL);
environment.put(Context.SECURITY_AUTHENTICATION, "simple");
environment.put(Context.SECURITY_PRINCIPAL, username);
environment.put(Context.SECURITY_CREDENTIALS, password);
String[] returnAttribute = {"member"};
SearchControls srchControls = new SearchControls();
srchControls.setReturningAttributes(returnAttribute);
srchControls.setSearchScope(SearchControls.SUBTREE_SCOPE);
for (int i = 0; i <= size - 1; i++) {
String searchFilter = "(cn=" + userID[i] + ")";
try {
DirContext authContext = new InitialDirContext(environment);
//System.out.println("Authentication Successful");
NamingEnumeration<SearchResult> search = authContext.search(base, searchFilter, srchControls);
// Probably want to test for nulls here
distName = search.nextElement().toString();
String[] splitBasedOnColon = distName.split("\\:");
for (String x : splitBasedOnColon) {
if (x.startsWith("cn")) {
String[] splitGroupName = x.split("\\=");
groupName = splitGroupName[1];
}
}
if (distName.contains(username)) {
System.out.println("User is part of the group: " + groupName);
}
} catch (AuthenticationException authEx) {
System.out.println("Authentication failed!");
} catch (NamingException namEx) {
System.out.println("Something went wrong!");
namEx.printStackTrace();
} catch (NullPointerException notFound) {
System.out.println("User is not part group : "+ userID[i]);
// notFound.printStackTrace();
}
}
return distName;
}
}
Related
At the same time of providing authentication to the user in LDAP within Microsoft Active Directory, I'm trying to get all groups that specific user belongs to. The following code is in Java.
What I'm doing at the moment is the following:
public static List authenticate(String username, String password) throws Exception {
String LDAPURL = MY_LDAP_URL;
String userBase = MY_USERBASE; //format "dc=***,dc=com"
ArrayList<String> groups = new ArrayList<String>();
Hashtable<String, String> environment = new Hashtable<String, String>();
environment.put(Context.INITIAL_CONTEXT_FACTORY,
"com.sun.jndi.ldap.LdapCtxFactory");
environment.put(Context.PROVIDER_URL, LDAPURL);
environment.put(Context.SECURITY_AUTHENTICATION, "simple");
environment.put(Context.SECURITY_PRINCIPAL, username);
environment.put(Context.SECURITY_CREDENTIALS, password);
DirContext ctx =
new InitialDirContext(environment);
SearchControls ctls = new SearchControls();
String[] attributes = {"cn", "memberOf"};
ctls.setReturningAttributes(attributes);
ctls.setSearchScope( SearchControls.SUBTREE_SCOPE );
String searchFilters = "{sAMAccountName="+username+"}";
NamingEnumeration<?> answer = ctx.search(userBase, searchFilters, ctls);
if(answer == null || !answer.hasMore()) {
logger.info("No result found");
}
else {
SearchResult result = (SearchResult) answer.next();
Attributes attrs = result.getAttributes();
Attribute memberAttr = attrs.get("memberOf");
NamingEnumeration e = memberAttr.getAll();
while(e.hasMore()) {
String group = (String) e.next();
groups.add(group);
logger.info(group);
}
}
return groups;
}
I have tried several ways of doing my query, for example:
String searchFilters = "(&(uid="+username+"),(ou=users),(memberOf=*))"
Or
String searchFilters = "(&(objectClass=groupOfNames)(member=cn=" + username + ")(memberOf=*))"
Or
String searchFilters = "(&(userPrincipalName=" + username + ")(memberOf=*))"
In none of the cases any groups were retrieved. In some of the cases the login itself failed as well (in some cases it worked but still no groups returned).
What is the correct way to retrieve the groups?
Although you can bind with "username" and some other attributes, using ANR, ONLY when using Microsoft Active Directory, you will need to obtain the Fully Distinguished Name for the user to perform many LDAP Searches.
Assuming username is the samAccountName, which is always Unique within a AD Forrest, your Authentication should work.
After Authentication you can obtain the DN of the entry and then perform a search for Groups the user is a member.
For all groups the user is a member, including nested groups this will usually work.
(member:1.2.840.113556.1.4.1941:=(CN=UserName,CN=Users,DC=YOURDOMAIN,DC=NET))
We have several JNDI Examples in a code repository.
I created LDAP AD server in Windows 2008 server using the steps mentioned in the following link:
https://blogs.msdn.microsoft.com/robert_mcmurray/2011/09/16/ftp-and-ldap-part-2-how-to-set-up-an-active-directory-lightweight-directory-services-ad-lds-server/#01b
The following program has to search for users in LDAP AD. It connects with the LDAP server successfully, but the user search is unsuccessful. I am not sure why.
public class LDAPTest {
String ldapHost = "ldap://hostname:389";
String searchBase = "CN=LDAPServer,DC=SITDomain,DC=local";
public static void main(String[] args) {
LDAPTest ldapConnect = new LDAPTest();
ldapConnect.authenticate("john", "****");
}
public Map authenticate(String user, String pass) {
String returnedAtts[] = { "dintinguishedName" };
String searchFilter = "(& (userPrincipalName="+user+")(objectClass=user))";
// Create the search controls
SearchControls searchCtls = new SearchControls();
searchCtls.setReturningAttributes(returnedAtts);
// Specify the search scope
searchCtls.setSearchScope(SearchControls.SUBTREE_SCOPE);
Hashtable<Object, Object> env = new Hashtable<Object, Object>();
env.put(Context.INITIAL_CONTEXT_FACTORY, "com.sun.jndi.ldap.LdapCtxFactory");
env.put(Context.PROVIDER_URL, this.ldapHost);
env.put(Context.SECURITY_AUTHENTICATION, "simple");
env.put(Context.SECURITY_PRINCIPAL,"CN=ryan,CN=grp,CN=LDAPServer,DC=SITDomain,DC=local");
env.put(Context.SECURITY_CREDENTIALS, pass);
LdapContext ctxGC = null;
boolean ldapUser = false;
try {
ctxGC = new InitialLdapContext(env, null);
// Search objects in GC using filters
NamingEnumeration<SearchResult> answer = ctxGC.search(this.searchBase, searchFilter, searchCtls);
while (answer.hasMoreElements()) {
SearchResult sr = answer.next();
System.out.println(">>>" + sr.getName());
Attributes attrs = sr.getAttributes();
Map amap = null;
if (attrs != null) {
System.out.println(attrs.size());
System.out.println(">>>>>>" + attrs.get("dintinguishedName"));
amap = new HashMap();
NamingEnumeration<Attribute> ne = (NamingEnumeration<Attribute>) attrs.getAll();
while (ne.hasMore()) {
Attribute attr = ne.next();
amap.put(attr.getID(), attr.get());
System.out.println(attr.getID()+">>>>>>" + attr.get());
ldapUser = true;
}
ne.close();
}
}
} catch (NamingException ex) {
ex.printStackTrace();
System.out.println(ex.getMessage());
}
return null;
}
}
LDAP server dir image
Not sure if it is a copy/paste error or a typo in the code, but the user attribute being returned is spelled incorrectly. The attribute name dintinguishedName should be distinguishedName. I would also expect to see an initial bind with a known good user (e.g. an account specifically created for the application), a search for the user, retrieval of the distinguishedName, and a second attempt to bind with the returned distinguishedName and user supplied password. Instead I'm seeing a hard-coded ID (ryan) using the user-supplied password. Which may work if the two accounts happen to have the same password. Below this post, I have included the code I use to authenticate against my LDAP servers, including Active Directory.
I wanted universal code, and most other LDAP servers require you use the distinguishedName in the bind operation. But for Active Directory, specifically, you can bind without knowing the distinguishedName of the user -- LDAP bind to AD can be performed with sAMAccountName (domain\user) and userPrincipalName (user#domain.TLD). If you have a single tree in a single forest (i.e. you know the value to append to the user ID to form sAMAccountName or userPrincipalName), you can perform a bind operation as the user. Should you need additional information about the person beyond their authentication validation, on return code 0 (successful authentication), search for the user & retrieve the information.
// Editable variables -- ensure you change these to your application's details
String strSysUID = "uid=YOURSYSTEMIDGOESHERE,ou=OrgUnitName,dc=Org,dc=Name";
String strSysPassword = "YourSystemPasswordGoesHere";
String strAuthorizationGroup = "LJL_Test";
String strTrustStorePassword = "YourTrustStorePassword"
String trustStoreFile = ".\\ADTrust";
String sLDAPServer = "ldaps://ldap.domain.gTLD:636";
String strUserBaseDN = "ou=UserOU,dc=Org,dc=Name";
String strGroupBaseDN = "ou=GroupOU,dc=Org,dc=Name";
String strUserIDSchemaAttribute = "sAMAccountName="; // attribute that holds user logon name
String strGroupMembershipSchemaAttribute = "member"; // attribute that holds member list in group object
// End of editable variables
System.setProperty("javax.net.ssl.trustStore", trustStoreFile);
System.setProperty("javax.net.ssl.trustStorePassword", strTrustStorePassword);
// Obtain UID and PWD from user
String sUserUID = "";
String sUserPwd = "";
BufferedReader in = new BufferedReader(new InputStreamReader(System.in));
System.out.print("Please enter your username: ");
try{
sUserUID = in.readLine();
}catch(Exception er) { er.printStackTrace(); }
System.out.print("Please enter your password: ");
try{
sUserPwd = in.readLine();
}catch(Exception er) { er.printStackTrace(); }
// Initial context for system bind
Hashtable env = new Hashtable(11);
env.put(Context.INITIAL_CONTEXT_FACTORY, "com.sun.jndi.ldap.LdapCtxFactory");
env.put(Context.PROVIDER_URL, sLDAPServer);
env.put(Context.SECURITY_PROTOCOL, "ssl");
// Authenticate as system ID and password
env.put(Context.SECURITY_AUTHENTICATION, "simple");
env.put(Context.SECURITY_PRINCIPAL, strSysUID);
env.put(Context.SECURITY_CREDENTIALS, strSysPassword);
try {
DirContext ctx = new InitialDirContext(env);
// Using the system credentials, search for a user matching the logon ID provided by the user
String sFilter = strUserIDSchemaAttribute + sUserUID;
NamingEnumeration UserDNAnswer = ctx.search(strUserBaseDN, sFilter, null);
String sReturnedFQDN = "";
// If only one record should be returns, validate that exactly one record is located and throw an error otherwise
while (UserDNAnswer.hasMore()) {
SearchResult sr = (SearchResult) UserDNAnswer.next();
// Store the DN of the user re have found
sReturnedFQDN = sr.getNameInNamespace();
}
// Check group membership, can be done after the password is validated if you wish
// Example LDAP filter is "(&(cn=NameOfGroupToCheck)(uniqueMember=FQDNOfUserBeingTested))"
String sGroupFilter = "(&(cn=" + strAuthorizationGroup + ")(" + strGroupMembershipSchemaAttribute + "=" + sReturnedFQDN + "))";
NamingEnumeration GroupMembershipAnswer = ctx.search(strGroupBaseDN, sGroupFilter, null);
String sReturnedGroupDN = "";
while (GroupMembershipAnswer.hasMore()) {
SearchResult srGroup = (SearchResult) GroupMembershipAnswer.next();
sReturnedGroupDN = srGroup.getNameInNamespace();
}
ctx.close();
// If an entry was returned, then the user is a member of the group. We should validate the user's password
if(sReturnedGroupDN.equals("cn=" + strAuthorizationGroup+ "," + strGroupBaseDN)){
System.out.println(sReturnedFQDN + " is a member of " + sReturnedGroupDN + " and now we will validate the password.");
// Now establish a new LDAP connection to validate the credentials supplied
Hashtable envUser = new Hashtable(11);
envUser.put(Context.INITIAL_CONTEXT_FACTORY, "com.sun.jndi.ldap.LdapCtxFactory");
envUser.put(Context.PROVIDER_URL, sLDAPServer);
// Authenticate using the searched FQDN for the user and the password provided by the user
envUser.put(Context.SECURITY_AUTHENTICATION, "simple");
envUser.put(Context.SECURITY_PRINCIPAL, sReturnedFQDN);
envUser.put(Context.SECURITY_CREDENTIALS, sUserPwd);
// Doing this so a login failure throws a code
try{
DirContext ctxUser = new InitialDirContext(envUser);
System.out.println("Successfully authenticated as " + sUserUID);
ctxUser .close;
}
// User credentials failure
catch (NamingException e) {
e.printStackTrace();
}
}
// If no group matched the filter, the user is not a group member and an authorisation failure can be returned
else{
System.out.println(sReturnedFQDN + " is NOT a member of " + sReturnedGroupDN + " and there is no need to verify the password.");
}
}
// System credentials failure
catch (NamingException e) {
e.printStackTrace();
}
}
I have written an application that retrieves Active Directory groups and flattens them, i.e. includes recursively members of subgroup to the top parent group.
It works fine for small groups, but with larger groups I am facing a problem.
If number of members does not exceed 1500, they are listed in the member attribute. If there are more - then this attribute is empty and attribute with name member;range:0-1499 appears, containing first 1500 members.
My problem that I don't know how to get the rest of member set over 1500.
We have groups with 8-12 thousand members. Do I need to run another query?
On the Microsoft site I have seen C# code snippet on the similar matter, but couldn't make much sense of it, as they were showing how to specify a range, but not how to plug it into query. If someone knows how to do it in Java, I'd appreciate a tip.
This will obviously give you the next ones:
String[] returnedAtts = { "member;range=1500-2999" };
You need to fetch the users chunk by chunk (1500 chunks) Just make a counter and update you search and retrieve the next ones until you have all of them.
With your help I have a full working code
// Initialize
LdapContext ldapContext = null;
NamingEnumeration<SearchResult> results = null;
NamingEnumeration<?> members = null;
try {
// Initialize properties
Properties properties = new Properties();
properties.put(Context.INITIAL_CONTEXT_FACTORY, "com.sun.jndi.ldap.LdapCtxFactory");
properties.put(Context.PROVIDER_URL, "ldap://" + ldapUrl);
properties.put(Context.SECURITY_PRINCIPAL, adminLoginADOnPremise);
properties.put(Context.SECURITY_CREDENTIALS, adminPasswordADOnPremise);
// Initialize ldap context
ldapContext = new InitialLdapContext(properties, null);
int range = 0;
boolean finish = false;
while (finish != true) {
// Set search controls
SearchControls searchCtls = new SearchControls();
searchCtls.setSearchScope(SearchControls.SUBTREE_SCOPE);
searchCtls.setReturningAttributes(generateRangeArray(range));
// Get results
results = ldapContext.search(ldapBaseDn, String.format("(samAccountName=%s)", groupName), searchCtls);
if (results.hasMoreElements() == true) {
SearchResult result = results.next();
try {
members = result.getAttributes().get(generateRangeString(range)).getAll();
while (members.hasMore()) {
String distinguishedName = (String) members.next();
logger.debug(distinguishedName);
}
range++;
} catch (Exception e) {
// Fails means there is no more result
finish = true;
}
}
}
} catch (NamingException e) {
logger.error(e.getMessage());
throw new Exception(e.getMessage());
} finally {
if (ldapContext != null) {
ldapContext.close();
}
if (results != null) {
results.close();
}
}
Two functions missing from the working code example by #Nicolas, I guess they would be something like:
public static String[] generateRangeArray(int i) {
String range = "member;range=" + i * 1500 + "-" + ((i + 1) * 1500 - 1);
String[] returnedAtts = { range };
return returnedAtts;
}
public static String generateRangeString(int i) {
String range = "member;range=" + i * 1500 + "-" + ((i + 1) * 1500 - 1);
return range;
}
The code does not handle the case if the AD group is not so large that the member attribute actually needs to be "chunked", that is if the "member" attribute exists instead.
I am facing problem while applying logical not query.
For example,
NamingEnumeration<SearchResult> results =
context.search("ou=people,dc=example,dc=com", "sn=Kumaran", searcCon);
Above statement is working absolutely fine, it is returning all the person entries whose sn is Kumaran.
Suppose that I change the statement to get all the person entries whose sn is not Kumaran.
NamingEnumeration<SearchResult> results =
context.search("ou=people,dc=example,dc=com", "(!sn=Kumaran)", searcCon);
I am getting following error:
Exception in thread "main" javax.naming.directory.InvalidSearchFilterException: Unbalanced parenthesis; remaining name 'ou=people,dc=example,dc=com'
at com.sun.jndi.ldap.Filter.findRightParen(Filter.java:694)
at com.sun.jndi.ldap.Filter.encodeFilterList(Filter.java:733)
at com.sun.jndi.ldap.Filter.encodeComplexFilter(Filter.java:657)
at com.sun.jndi.ldap.Filter.encodeFilter(Filter.java:118)
at com.sun.jndi.ldap.Filter.encodeFilterString(Filter.java:74)
at com.sun.jndi.ldap.LdapClient.search(LdapClient.java:548)
at com.sun.jndi.ldap.LdapCtx.doSearch(LdapCtx.java:1985)
at com.sun.jndi.ldap.LdapCtx.searchAux(LdapCtx.java:1844)
at com.sun.jndi.ldap.LdapCtx.c_search(LdapCtx.java:1769)
at com.sun.jndi.toolkit.ctx.ComponentDirContext.p_search(ComponentDirContext.java:392)
at com.sun.jndi.toolkit.ctx.PartialCompositeDirContext.search(PartialCompositeDirContext.java:358)
at com.sun.jndi.toolkit.ctx.PartialCompositeDirContext.search(PartialCompositeDirContext.java:341)
at javax.naming.directory.InitialDirContext.search(InitialDirContext.java:267)
at jndi_tutorial.Test.getPeopleSnIsKumaran(Test.java:34)
at jndi_tutorial.Test.main(Test.java:62)
Following is my code
public static void printResults(NamingEnumeration<SearchResult> results)
throws NamingException {
while (results.hasMoreElements()) {
SearchResult res = results.next();
Attributes atbs = res.getAttributes();
Attribute nameAttr = atbs.get("cn");
String name = (String) nameAttr.get();
Attribute descriptionAtr = atbs.get("description");
String description = (String) descriptionAtr.get();
System.out.println(description);
System.out.println("Name is :" + name + ",description is :"
+ description);
}
}
/* Get all people whose sn is not equal to Kumaran */
public static void getAllExcludeKumaran() throws NamingException {
SearchControls searcCon = new SearchControls();
searcCon.setSearchScope(SearchControls.SUBTREE_SCOPE);
NamingEnumeration<SearchResult> results = context.search(
"ou=people,dc=example,dc=com", "(!(sn=Kumaran))", searcCon);
printResults(results);
}
Reference
https://technet.microsoft.com/en-us/library/aa996205(v=exchg.65).aspx
Try to add parenthesis (!(sn=Kumaran))
UPDATE:
Try this
...
SearchControls searcCon = new SearchControls();
String[] attributeFilter = { "cn", "description" };
searcCon.setReturningAttributes(attributeFilter);
searcCon.setSearchScope(SearchControls.SUBTREE_SCOPE);
...
See RFC 2254:
filter ::= "(" filtercomp ")"
not ::= "!" filter
Your code should be like
context.search("ou=people,dc=example,dc=com", "((!sn=Kumaran))", searcCon);
It should work for you.
I am looking for a query, when entered a name it should check whether there are any sub employees reporting to that entered name. If there are any, then it should return all the list of child users(employees) and sub child users reporting to that employee.
I wrote a query, when entered a username, it gets all the data associated with him, but I am confused now how to get only the users & sub-users & sub-sub users names that report to that search term.
Is there a way to do it with AD or do I need to implement DFS search? If either option, then please give me some hints to do it.
try {
// Create Initial Context
LdapContext ctxGC = new InitialLdapContext(env, null);
// ctxGC.setRequestControls(null);
String searchFilter = "(&(objectClass=user)(sAMAccountName=" + searchTerm + ")(!(displayName=ADM*)))";
NamingEnumeration<?> namingEnum = ctxGC.search("OU=User,DC=emea,DC=xyz,DC=biz", searchFilter, getSearchControls());
Deque<Node> stack = new ArrayDeque<Node>(); // Do I need to implement tree here or is there any other way to get sub users info from LDAP search??
while (namingEnum.hasMoreElements()) {
SearchResult result = (SearchResult) namingEnum.next();
Attributes attrs = result.getAttributes();
if (attrs != null) {
NamingEnumeration ne = attrs.getAll();
while (ne.hasMore()) {
Attribute attr = (Attribute) ne.next();
}
}
}
namingEnum.close();
} catch (Exception e) {
e.printStackTrace();
}
}
private static SearchControls getSearchControls() {
SearchControls searchCtls = new SearchControls();
searchCtls.setSearchScope(SearchControls.SUBTREE_SCOPE);
searchCtls.setReturningAttributes(new String[]{"*"});
return searchCtls;
}
To get the list of users reporting to a manager, I just need to change the search filter query and retrieve the manager credentials, then it returns the list of all users that are reporting to that person. If there are no users reporting to him, then it returns nothing.
So, the searchFilter need to be changed like the following.
String searchFilter = "(&(objectClass=user)(manager=CN=Its\\\\, Zaif,OU=xx,OU=xx,OU=StandardUser,OU=xx,DC=emea,DC=xyz,DC=biz) (!(displayName=ADM*)))";