LDAP Query: Retrieve Basic User Attributes in Java

In this article, we make LDAP Query to retrieve basic attributes. In previous article, we have seen how to connect to active directory (AD) using Java provided LdapContext object. It may not be always the situation that you are satisfied with authentication of users against the AD database. You may want to retrieve all user details for one or other purpose. Obviously, that is why you have taken pain to store those in a secured database by paying huge licensing fees to Microsoft. Here to explore further, we are taking your java application, which can be a tiny standalone program, or a full-fledge application deployed on a fancy and costly application server, and connecting to AD to retrieve user attributes. In this article we will try to retrieve basic attributes of user. While doing it we need to do following things.

Steps for LDAP Query:

1.Create AD connection (i.e. context) using LDAP (as discussed in previous article).

2.Define search base

3.Prepare search query

4.Define search controls

5.Search AD using context object from step 1 and the search parameters in steps 2, 3 and 4.

6.Process resultset to retrieve the desired basic user attributes.

LdapContext object provides many overloaded search methods to suite different needs based on available search parameters. You can choose the one suitable to you. If the user does not exist in AD then it will return no element in result set. You can raise an invalid user exception for this scenario. Also if the query attributes e.g. mail, telephonenumber is not set in AD then this search will not return the attribute. So this null attribute scenario needs to be handled.

Active Directory is a database, hence it has itโ€™s own column names for different resource attributes. We need to know these column names and then query AD. ย All attributes can be found at this location. You can click on the attributes and use Ldap-Display-Name to retrieve data using above program.

import java.util.Hashtable;

import javax.naming.Context;
import javax.naming.NamingEnumeration;
import javax.naming.NamingException;
import javax.naming.directory.Attributes;
import javax.naming.directory.SearchControls;
import javax.naming.directory.SearchResult;
import javax.naming.ldap.InitialLdapContext;
import javax.naming.ldap.LdapContext;

public class RetrieveUserAttributes {

	public static void main(String[] args) {
		RetrieveUserAttributes retrieveUserAttributes = new RetrieveUserAttributes();
		retrieveUserAttributes.getUserBasicAttributes("testuser", retrieveUserAttributes.getLdapContext());
	}

	public LdapContext getLdapContext(){
		LdapContext ctx = null;
		try{
			Hashtable<String, String> env = new Hashtable<String, String>();
			env.put(Context.INITIAL_CONTEXT_FACTORY,
					"com.sun.jndi.ldap.LdapCtxFactory");
			env.put(Context.SECURITY_AUTHENTICATION, "Simple");
			env.put(Context.SECURITY_PRINCIPAL, "your username");
			env.put(Context.SECURITY_CREDENTIALS, "Password");
			env.put(Context.PROVIDER_URL, "ldap://serverlocation:389");
			ctx = new InitialLdapContext(env, null);
			System.out.println("Connection Successful.");
		}catch(NamingException nex){
			System.out.println("LDAP Connection: FAILED");
			nex.printStackTrace();
		}
		return ctx;
	}

	private User getUserBasicAttributes(String username, LdapContext ctx) {
		User user=null;
		try {

			SearchControls constraints = new SearchControls();
			constraints.setSearchScope(SearchControls.SUBTREE_SCOPE);
			String[] attrIDs = { "distinguishedName",
					"sn",
					"givenname",
					"mail",
					"telephonenumber"};
			constraints.setReturningAttributes(attrIDs);
			//First input parameter is search bas, it can be "CN=Users,DC=YourDomain,DC=com"
			//Second Attribute can be uid=username
			NamingEnumeration answer = ctx.search("DC=YourDomain,DC=com", "sAMAccountName="
					+ username, constraints);
			if (answer.hasMore()) {
				Attributes attrs = ((SearchResult) answer.next()).getAttributes();
				System.out.println("distinguishedName "+ attrs.get("distinguishedName"));
				System.out.println("givenname "+ attrs.get("givenname"));
				System.out.println("sn "+ attrs.get("sn"));
				System.out.println("mail "+ attrs.get("mail"));
				System.out.println("telephonenumber "+ attrs.get("telephonenumber"));
			}else{
				throw new Exception("Invalid User");
			}

		} catch (Exception ex) {
			ex.printStackTrace();
		}
		return user;
	}

}

 

 

14 Comments

  1. I like it.

    But I would like to get all the attributes.
    Here, you just get a specific attribute.

    I wanna a list of attribute-name=atttribute-value.

    How you do that?

    Thanks

  2. Some years ago from this post … And Still Helpful

    Thank you very much!

    These tips/examples helped me to resolve every problem found in an implementation’s LDAP connections, And retrieve user’s info.

    Again, thank you very much!

  3. Nice article. I am new to LDAP, your article helped a lot to connect to AD server and get user details.

    Thanks buddy !!!!!

  4. Can anyone provide me a java code for a login application?
    requirements are:-
    jsp,servlet & LDAP…credentials will be provided at jsp will get verified from LDAP and resultant will be a new jsp.
    pls. help me out.waiting for your reply.

  5. Hi ๐Ÿ™‚ !! I liked your explaianation ๐Ÿ™‚ !! Do you have any information regarding LDAP change notifications? I am trying to monitor changes on specfic attributes in AD,but i was unable to find a way. Currently Iam using persistent search to monitor the changes, it is notifying me whenever there is a change in any ofthe attribute but I want to monitor changes in only prticular attributes like Password, User ID etc. I would be very thankful to you if you can provde me with any suggestion.

    Thank You ๐Ÿ™‚

  6. Hi,
    Thank you Deepak. This is very nice article to search data in LDAP. Can you give me some idea how should I insert fake data in LDAP to run test case?

  7. Hi Deepak,
    Thank you for your blog…This is very helpful…
    Your explanation is very good…i.e. any one understand easily..

  8. If someone knows this error?
    Connection Successful.
    java.lang.Exception: Invalid User
    at com.ldap.LDAP.getUserBasicAttributes(LDAP.java:68)
    at com.ldap.LDAP.main(LDAP.java:21)

Leave a Reply

Your email address will not be published.


*